forked from microsoft/PowerShellForGitHub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GitHubBranches.ps1
2202 lines (1753 loc) · 72.6 KB
/
GitHubBranches.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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
@{
GitHubBranchTypeName = 'GitHub.Branch'
GitHubBranchProtectionRuleTypeName = 'GitHub.BranchProtectionRule'
GitHubBranchPatternProtectionRuleTypeName = 'GitHub.BranchPatternProtectionRule'
MaxProtectionRules = 100
MaxPushAllowances = 100
MaxReviewDismissalAllowances = 100
}.GetEnumerator() | ForEach-Object {
Set-Variable -Scope Script -Option ReadOnly -Name $_.Key -Value $_.Value
}
filter Get-GitHubRepositoryBranch
{
<#
.SYNOPSIS
Retrieve branches for a given GitHub repository.
.DESCRIPTION
Retrieve branches for a given GitHub repository.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER OwnerName
Owner of the repository.
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 repository.
The OwnerName and RepositoryName will be extracted from here instead of needing to provide
them individually.
.PARAMETER Name
Name of the specific branch to be retrieved. If not supplied, all branches will be retrieved.
.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.Branch
GitHub.Content
GitHub.Event
GitHub.Issue
GitHub.IssueComment
GitHub.Label
GitHub.Milestone
GitHub.PullRequest
GitHub.Project
GitHub.ProjectCard
GitHub.ProjectColumn
GitHub.Reaction
GitHub.Release
GitHub.ReleaseAsset
GitHub.Repository
.OUTPUTS
GitHub.Branch
List of branches within the given repository.
.EXAMPLE
Get-GitHubRepositoryBranch -OwnerName microsoft -RepositoryName PowerShellForGitHub
Gets all branches for the specified repository.
.EXAMPLE
$repo = Get-GitHubRepository -OwnerName microsoft -RepositoryName PowerShellForGitHub
$repo | Get-GitHubRepositoryBranch
Gets all branches for the specified repository.
.EXAMPLE
Get-GitHubRepositoryBranch -Uri 'https://github.com/PowerShell/PowerShellForGitHub' -BranchName master
Gets information only on the master branch for the specified repository.
.EXAMPLE
$repo = Get-GitHubRepository -OwnerName microsoft -RepositoryName PowerShellForGitHub
$repo | Get-GitHubRepositoryBranch -BranchName master
Gets information only on the master branch for the specified repository.
.EXAMPLE
$repo = Get-GitHubRepository -OwnerName microsoft -RepositoryName PowerShellForGitHub
$branch = $repo | Get-GitHubRepositoryBranch -BranchName master
$branch | Get-GitHubRepositoryBranch
Gets information only on the master branch for the specified repository, and then does it
again. This tries to show some of the different types of objects you can pipe into this
function.
#>
[CmdletBinding(DefaultParameterSetName = 'Elements')]
[OutputType({$script:GitHubBranchTypeName})]
[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.")]
[Alias('Get-GitHubBranch')]
param(
[Parameter(ParameterSetName='Elements')]
[string] $OwnerName,
[Parameter(ParameterSetName='Elements')]
[string] $RepositoryName,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
ParameterSetName='Uri')]
[Alias('RepositoryUrl')]
[string] $Uri,
[Parameter(ValueFromPipelineByPropertyName)]
[string] $BranchName,
[switch] $ProtectedOnly,
[string] $AccessToken
)
Write-InvocationLog
$elements = Resolve-RepositoryElements
$OwnerName = $elements.ownerName
$RepositoryName = $elements.repositoryName
$telemetryProperties = @{
'OwnerName' = (Get-PiiSafeString -PlainText $OwnerName)
'RepositoryName' = (Get-PiiSafeString -PlainText $RepositoryName)
}
$uriFragment = "repos/$OwnerName/$RepositoryName/branches"
if (-not [String]::IsNullOrEmpty($BranchName)) { $uriFragment = $uriFragment + "/$BranchName" }
$getParams = @()
if ($ProtectedOnly) { $getParams += 'protected=true' }
$params = @{
'UriFragment' = $uriFragment + '?' + ($getParams -join '&')
'Description' = "Getting branches for $RepositoryName"
'AccessToken' = $AccessToken
'TelemetryEventName' = $MyInvocation.MyCommand.Name
'TelemetryProperties' = $telemetryProperties
}
return (Invoke-GHRestMethodMultipleResult @params | Add-GitHubBranchAdditionalProperties)
}
filter New-GitHubRepositoryBranch
{
<#
.SYNOPSIS
Creates a new branch for a given GitHub repository.
.DESCRIPTION
Creates a new branch for a given GitHub repository.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER OwnerName
Owner of the repository.
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 repository.
The OwnerName and RepositoryName will be extracted from here instead of needing to provide
them individually.
.PARAMETER BranchName
The name of the origin branch to create the new branch from.
.PARAMETER TargetBranchName
Name of the branch to be created.
.PARAMETER Sha
The SHA1 value of the commit that this branch should be based on.
If not specified, will use the head of BranchName.
.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.Branch
GitHub.Content
GitHub.Event
GitHub.Issue
GitHub.IssueComment
GitHub.Label
GitHub.Milestone
GitHub.PullRequest
GitHub.Project
GitHub.ProjectCard
GitHub.ProjectColumn
GitHub.Release
GitHub.Repository
.OUTPUTS
GitHub.Branch
.EXAMPLE
New-GitHubRepositoryBranch -OwnerName microsoft -RepositoryName PowerShellForGitHub -TargetBranchName new-branch
Creates a new branch in the specified repository from the master branch.
.EXAMPLE
New-GitHubRepositoryBranch -Uri 'https://github.com/microsoft/PowerShellForGitHub' -BranchName develop -TargetBranchName new-branch
Creates a new branch in the specified repository from the 'develop' origin branch.
.EXAMPLE
$repo = Get-GithubRepository -Uri https://github.com/You/YourRepo
$repo | New-GitHubRepositoryBranch -TargetBranchName new-branch
You can also pipe in a repo that was returned from a previous command.
.EXAMPLE
$branch = Get-GitHubRepositoryBranch -OwnerName microsoft -RepositoryName PowerShellForGitHub -BranchName main
$branch | New-GitHubRepositoryBranch -TargetBranchName beta
You can also pipe in a branch that was returned from a previous command.
.EXAMPLE
New-GitHubRepositoryBranch -Uri 'https://github.com/microsoft/PowerShellForGitHub' -Sha 1c3b80b754a983f4da20e77cfb9bd7f0e4cb5da6 -TargetBranchName new-branch
You can also create a new branch based off of a specific SHA1 commit value.
#>
[CmdletBinding(
SupportsShouldProcess,
DefaultParameterSetName = 'Elements',
PositionalBinding = $false
)]
[OutputType({$script:GitHubBranchTypeName})]
[Alias('New-GitHubBranch')]
param(
[Parameter(ParameterSetName = 'Elements')]
[string] $OwnerName,
[Parameter(ParameterSetName = 'Elements')]
[string] $RepositoryName,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
Position = 1,
ParameterSetName = 'Uri')]
[Alias('RepositoryUrl')]
[string] $Uri,
[Parameter(ValueFromPipelineByPropertyName)]
[string] $BranchName = 'master',
[Parameter(
Mandatory,
ValueFromPipeline,
Position = 2)]
[string] $TargetBranchName,
[Parameter(ValueFromPipelineByPropertyName)]
[string] $Sha,
[string] $AccessToken
)
Write-InvocationLog
$elements = Resolve-RepositoryElements
$OwnerName = $elements.ownerName
$RepositoryName = $elements.repositoryName
$telemetryProperties = @{
'OwnerName' = (Get-PiiSafeString -PlainText $OwnerName)
'RepositoryName' = (Get-PiiSafeString -PlainText $RepositoryName)
}
$originBranch = $null
if (-not $PSBoundParameters.ContainsKey('Sha'))
{
try
{
$getGitHubRepositoryBranchParms = @{
OwnerName = $OwnerName
RepositoryName = $RepositoryName
BranchName = $BranchName
}
if ($PSBoundParameters.ContainsKey('AccessToken'))
{
$getGitHubRepositoryBranchParms['AccessToken'] = $AccessToken
}
Write-Log -Level Verbose "Getting $BranchName branch for sha reference"
$originBranch = Get-GitHubRepositoryBranch @getGitHubRepositoryBranchParms
$Sha = $originBranch.commit.sha
}
catch
{
# Temporary code to handle current differences in exception object between PS5 and PS7
$throwObject = $_
if ($PSVersionTable.PSedition -eq 'Core')
{
if ($_.Exception -is [Microsoft.PowerShell.Commands.HttpResponseException] -and
($_.ErrorDetails.Message | ConvertFrom-Json).message -eq 'Branch not found')
{
$throwObject = "Origin branch $BranchName not found"
}
}
else
{
if ($_.Exception.Message -like '*Not Found*')
{
$throwObject = "Origin branch $BranchName not found"
}
}
Write-Log -Message $throwObject -Level Error
throw $throwObject
}
}
$uriFragment = "repos/$OwnerName/$RepositoryName/git/refs"
$hashBody = @{
ref = "refs/heads/$TargetBranchName"
sha = $Sha
}
if (-not $PSCmdlet.ShouldProcess($BranchName, 'Create Repository Branch'))
{
return
}
$params = @{
'UriFragment' = $uriFragment
'Body' = (ConvertTo-Json -InputObject $hashBody)
'Method' = 'Post'
'Description' = "Creating branch $TargetBranchName for $RepositoryName"
'AccessToken' = $AccessToken
'TelemetryEventName' = $MyInvocation.MyCommand.Name
'TelemetryProperties' = $telemetryProperties
}
return (Invoke-GHRestMethod @params | Add-GitHubBranchAdditionalProperties)
}
filter Remove-GitHubRepositoryBranch
{
<#
.SYNOPSIS
Removes a branch from a given GitHub repository.
.DESCRIPTION
Removes a branch from a given GitHub repository.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER OwnerName
Owner of the repository.
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 repository.
The OwnerName and RepositoryName will be extracted from here instead of needing to provide
them individually.
.PARAMETER BranchName
Name of the branch to be removed.
.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.Branch
GitHub.Content
GitHub.Event
GitHub.Issue
GitHub.IssueComment
GitHub.Label
GitHub.Milestone
GitHub.PullRequest
GitHub.Project
GitHub.ProjectCard
GitHub.ProjectColumn
GitHub.Release
GitHub.Repository
.OUTPUTS
None
.EXAMPLE
Remove-GitHubRepositoryBranch -OwnerName microsoft -RepositoryName PowerShellForGitHub -BranchName develop
Removes the 'develop' branch from the specified repository.
.EXAMPLE
Remove-GitHubRepositoryBranch -OwnerName microsoft -RepositoryName PowerShellForGitHub -BranchName develop -Force
Removes the 'develop' branch from the specified repository without prompting for confirmation.
.EXAMPLE
$branch = Get-GitHubRepositoryBranch -Uri https://github.com/You/YourRepo -BranchName BranchToDelete
$branch | Remove-GitHubRepositoryBranch -Force
You can also pipe in a repo that was returned from a previous command.
#>
[CmdletBinding(
SupportsShouldProcess,
DefaultParameterSetName = 'Elements',
PositionalBinding = $false,
ConfirmImpact = 'High')]
[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.")]
[Alias('Remove-GitHubBranch')]
[Alias('Delete-GitHubRepositoryBranch')]
[Alias('Delete-GitHubBranch')]
param(
[Parameter(ParameterSetName = 'Elements')]
[string] $OwnerName,
[Parameter(ParameterSetName = 'Elements')]
[string] $RepositoryName,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
Position = 1,
ParameterSetName = 'Uri')]
[Alias('RepositoryUrl')]
[string] $Uri,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
Position = 2)]
[string] $BranchName,
[switch] $Force,
[string] $AccessToken
)
Write-InvocationLog
$elements = Resolve-RepositoryElements
$OwnerName = $elements.ownerName
$RepositoryName = $elements.repositoryName
$telemetryProperties = @{
'OwnerName' = (Get-PiiSafeString -PlainText $OwnerName)
'RepositoryName' = (Get-PiiSafeString -PlainText $RepositoryName)
}
$uriFragment = "repos/$OwnerName/$RepositoryName/git/refs/heads/$BranchName"
if ($Force -and (-not $Confirm))
{
$ConfirmPreference = 'None'
}
if (-not $PSCmdlet.ShouldProcess($BranchName, "Remove Repository Branch"))
{
return
}
$params = @{
'UriFragment' = $uriFragment
'Method' = 'Delete'
'Description' = "Deleting branch $BranchName from $RepositoryName"
'AccessToken' = $AccessToken
'TelemetryEventName' = $MyInvocation.MyCommand.Name
'TelemetryProperties' = $telemetryProperties
}
Invoke-GHRestMethod @params | Out-Null
}
filter Get-GitHubRepositoryBranchProtectionRule
{
<#
.SYNOPSIS
Retrieve branch protection rules for a given GitHub repository.
.DESCRIPTION
Retrieve branch protection rules for a given GitHub repository.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER OwnerName
Owner of the repository.
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 repository.
The OwnerName and RepositoryName will be extracted from here instead of needing to provide
them individually.
.PARAMETER BranchName
Name of the specific branch to be retrieved. If not supplied, all branches will be retrieved.
.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.Branch
GitHub.Content
GitHub.Event
GitHub.Issue
GitHub.IssueComment
GitHub.Label
GitHub.Milestone
GitHub.PullRequest
GitHub.Project
GitHub.ProjectCard
GitHub.ProjectColumn
GitHub.Release
GitHub.Repository
.OUTPUTS
GitHub.BranchProtectionRule
.EXAMPLE
Get-GitHubRepositoryBranchProtectionRule -OwnerName microsoft -RepositoryName PowerShellForGitHub -BranchName master
Retrieves branch protection rules for the master branch of the PowerShellForGithub repository.
.EXAMPLE
Get-GitHubRepositoryBranchProtectionRule -Uri 'https://github.com/microsoft/PowerShellForGitHub' -BranchName master
Retrieves branch protection rules for the master branch of the PowerShellForGithub repository.
#>
[CmdletBinding(
PositionalBinding = $false,
DefaultParameterSetName = 'Elements')]
[OutputType({ $script:GitHubBranchProtectionRuleTypeName })]
[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(ParameterSetName = 'Elements')]
[string] $OwnerName,
[Parameter(ParameterSetName = 'Elements')]
[string] $RepositoryName,
[Parameter(
Mandatory,
Position = 1,
ValueFromPipelineByPropertyName,
ParameterSetName = 'Uri')]
[Alias('RepositoryUrl')]
[string] $Uri,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
Position = 2)]
[string] $BranchName,
[string] $AccessToken
)
Write-InvocationLog
$elements = Resolve-RepositoryElements
$OwnerName = $elements.ownerName
$RepositoryName = $elements.repositoryName
$telemetryProperties = @{
'OwnerName' = (Get-PiiSafeString -PlainText $OwnerName)
'RepositoryName' = (Get-PiiSafeString -PlainText $RepositoryName)
}
$params = @{
UriFragment = "repos/$OwnerName/$RepositoryName/branches/$BranchName/protection"
Description = "Getting branch protection status for $RepositoryName"
Method = 'Get'
AcceptHeader = $script:lukeCageAcceptHeader
AccessToken = $AccessToken
TelemetryEventName = $MyInvocation.MyCommand.Name
TelemetryProperties = $telemetryProperties
}
return (Invoke-GHRestMethod @params | Add-GitHubBranchProtectionRuleAdditionalProperties)
}
filter New-GitHubRepositoryBranchProtectionRule
{
<#
.SYNOPSIS
Creates a branch protection rule for a branch on a given GitHub repository.
.DESCRIPTION
Creates a branch protection rules for a branch on a given GitHub repository.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER OwnerName
Owner of the repository.
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 repository.
The OwnerName and RepositoryName will be extracted from here instead of needing to provide
them individually.
.PARAMETER BranchName
Name of the specific branch to create the protection rule on.
.PARAMETER StatusChecks
The list of status checks to require in order to merge into the branch.
.PARAMETER RequireUpToDateBranches
Require branches to be up to date before merging. This setting will not take effect unless
at least one status check is defined.
.PARAMETER EnforceAdmins
Enforce all configured restrictions for administrators.
.PARAMETER DismissalUsers
Specify the user names of users who can dismiss pull request reviews. This can only be
specified for organization-owned repositories.
.PARAMETER DismissalTeams
Specify which teams can dismiss pull request reviews.
.PARAMETER DismissStaleReviews
If specified, approving reviews when someone pushes a new commit are automatically
dismissed.
.PARAMETER RequireCodeOwnerReviews
Blocks merging pull requests until code owners review them.
.PARAMETER RequiredApprovingReviewCount
Specify the number of reviewers required to approve pull requests. Use a number between 1
and 6.
.PARAMETER RestrictPushUsers
Specify which users have push access.
.PARAMETER RestrictPushTeams
Specify which teams have push access.
.PARAMETER RestrictPushApps
Specify which apps have push access.
.PARAMETER RequireLinearHistory
Enforces a linear commit Git history, which prevents anyone from pushing merge commits to a
branch. Your repository must allow squash merging or rebase merging before you can enable a
linear commit history.
.PARAMETER AllowForcePushes
Permits force pushes to the protected branch by anyone with write access to the repository.
.PARAMETER AllowDeletions
Allows deletion of the protected branch by anyone with write access to the repository.
.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.Repository
GitHub.Branch
.OUTPUTS
GitHub.BranchRepositoryRule
.NOTES
Protecting a branch requires admin or owner permissions to the repository.
.EXAMPLE
New-GitHubRepositoryBranchProtectionRule -OwnerName microsoft -RepositoryName PowerShellForGitHub -BranchName master -EnforceAdmins
Creates a branch protection rule for the master branch of the PowerShellForGithub repository
enforcing all configuration restrictions for administrators.
.EXAMPLE
New-GitHubRepositoryBranchProtectionRule -Uri 'https://github.com/microsoft/PowerShellForGitHub' -BranchName master -RequiredApprovingReviewCount 1
Creates a branch protection rule for the master branch of the PowerShellForGithub repository
requiring one approving review.
#>
[CmdletBinding(
PositionalBinding = $false,
SupportsShouldProcess,
DefaultParameterSetName = 'Elements')]
[OutputType({$script:GitHubBranchProtectionRuleTypeName })]
param(
[Parameter(ParameterSetName = 'Elements')]
[string] $OwnerName,
[Parameter(ParameterSetName = 'Elements')]
[string] $RepositoryName,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
Position = 1,
ParameterSetName = 'Uri')]
[Alias('RepositoryUrl')]
[string] $Uri,
[Parameter(
Mandatory,
ValueFromPipelineByPropertyName,
Position = 2)]
[string] $BranchName,
[string[]] $StatusChecks,
[switch] $RequireUpToDateBranches,
[switch] $EnforceAdmins,
[string[]] $DismissalUsers,
[string[]] $DismissalTeams,
[switch] $DismissStaleReviews,
[switch] $RequireCodeOwnerReviews,
[ValidateRange(1, 6)]
[int] $RequiredApprovingReviewCount,
[string[]] $RestrictPushUsers,
[string[]] $RestrictPushTeams,
[string[]] $RestrictPushApps,
[switch] $RequireLinearHistory,
[switch] $AllowForcePushes,
[switch] $AllowDeletions,
[string] $AccessToken
)
Write-InvocationLog
$elements = Resolve-RepositoryElements
$OwnerName = $elements.ownerName
$RepositoryName = $elements.repositoryName
$telemetryProperties = @{
OwnerName = (Get-PiiSafeString -PlainText $OwnerName)
RepositoryName = (Get-PiiSafeString -PlainText $RepositoryName)
}
$getGitHubRepositoryBranchProtectRuleParms = @{
OwnerName = $OwnerName
RepositoryName = $RepositoryName
BranchName = $BranchName
}
$ruleExists = $true
try
{
Get-GitHubRepositoryBranchProtectionRule @getGitHubRepositoryBranchProtectRuleParms |
Out-Null
}
catch
{
# Temporary code to handle current differences in exception object between PS5 and PS7
if ($PSVersionTable.PSedition -eq 'Core')
{
if ($_.Exception -is [Microsoft.PowerShell.Commands.HttpResponseException] -and
($_.ErrorDetails.Message | ConvertFrom-Json).message -eq 'Branch not protected')
{
$ruleExists = $false
}
else
{
throw $_
}
}
else
{
if ($_.Exception.Message -like '*Branch not protected*')
{
$ruleExists = $false
}
else
{
throw $_
}
}
}
if ($ruleExists)
{
$message = ("Branch protection rule for branch $BranchName already exists on Repository " +
$RepositoryName)
Write-Log -Message $message -Level Error
throw $message
}
if ($PSBoundParameters.ContainsKey('DismissalTeams') -or
$PSBoundParameters.ContainsKey('RestrictPushTeams'))
{
$teams = Get-GitHubTeam -OwnerName $OwnerName -RepositoryName $RepositoryName
}
$requiredStatusChecks = $null
if ($PSBoundParameters.ContainsKey('StatusChecks') -or
$PSBoundParameters.ContainsKey('RequireUpToDateBranches'))
{
if ($null -eq $StatusChecks)
{
$StatusChecks = @()
}
$requiredStatusChecks = @{
strict = $RequireUpToDateBranches.ToBool()
contexts = $StatusChecks
}
}
$dismissalRestrictions = @{}
if ($PSBoundParameters.ContainsKey('DismissalUsers'))
{
$dismissalRestrictions['users'] = $DismissalUsers
}
if ($PSBoundParameters.ContainsKey('DismissalTeams'))
{
$dismissalTeamList = $teams | Where-Object -FilterScript { $DismissalTeams -contains $_.name }
$dismissalRestrictions['teams'] = @($dismissalTeamList.slug)
}
$requiredPullRequestReviews = @{}
if ($PSBoundParameters.ContainsKey('DismissStaleReviews'))
{
$requiredPullRequestReviews['dismiss_stale_reviews'] = $DismissStaleReviews.ToBool()
}
if ($PSBoundParameters.ContainsKey('RequireCodeOwnerReviews'))
{
$requiredPullRequestReviews['require_code_owner_reviews'] = $RequireCodeOwnerReviews.ToBool()
}
if ($dismissalRestrictions.count -gt 0)
{
$requiredPullRequestReviews['dismissal_restrictions'] = $dismissalRestrictions
}
if ($PSBoundParameters.ContainsKey('RequiredApprovingReviewCount'))
{
$requiredPullRequestReviews['required_approving_review_count'] = $RequiredApprovingReviewCount
}
if ($requiredPullRequestReviews.count -eq 0)
{
$requiredPullRequestReviews = $null
}
if ($PSBoundParameters.ContainsKey('RestrictPushUsers') -or
$PSBoundParameters.ContainsKey('RestrictPushTeams') -or
$PSBoundParameters.ContainsKey('RestrictPushApps'))
{
if ($null -eq $RestrictPushUsers)
{
$RestrictPushUsers = @()
}
if ($null -eq $RestrictPushTeams)
{
$restrictPushTeamSlugs = @()
}
else
{
$restrictPushTeamList = $teams | Where-Object -FilterScript {
$RestrictPushTeams -contains $_.name }
$restrictPushTeamSlugs = @($restrictPushTeamList.slug)
}
$restrictions = @{
users = $RestrictPushUsers
teams = $restrictPushTeamSlugs
}
if ($PSBoundParameters.ContainsKey('RestrictPushApps'))
{
$restrictions['apps'] = $RestrictPushApps
}
}
else
{
$restrictions = $null
}
$hashBody = @{
required_status_checks = $requiredStatusChecks
enforce_admins = $EnforceAdmins.ToBool()
required_pull_request_reviews = $requiredPullRequestReviews
restrictions = $restrictions
}
if ($PSBoundParameters.ContainsKey('RequireLinearHistory'))
{
$hashBody['required_linear_history'] = $RequireLinearHistory.ToBool()
}
if ($PSBoundParameters.ContainsKey('AllowForcePushes'))
{
$hashBody['allow_force_pushes'] = $AllowForcePushes.ToBool()
}
if ($PSBoundParameters.ContainsKey('AllowDeletions'))
{
$hashBody['allow_deletions'] = $AllowDeletions.ToBool()
}
if (-not $PSCmdlet.ShouldProcess(
"'$BranchName' branch of repository '$RepositoryName'",
'Create GitHub Repository Branch Protection Rule'))
{
return
}
$jsonConversionDepth = 3
$params = @{
UriFragment = "repos/$OwnerName/$RepositoryName/branches/$BranchName/protection"
Body = (ConvertTo-Json -InputObject $hashBody -Depth $jsonConversionDepth)
Description = "Setting $BranchName branch protection status for $RepositoryName"
Method = 'Put'
AcceptHeader = $script:lukeCageAcceptHeader
AccessToken = $AccessToken
TelemetryEventName = $MyInvocation.MyCommand.Name
TelemetryProperties = $telemetryProperties
}
return (Invoke-GHRestMethod @params | Add-GitHubBranchProtectionRuleAdditionalProperties)
}
filter Remove-GitHubRepositoryBranchProtectionRule
{
<#
.SYNOPSIS
Remove branch protection rules from a given GitHub repository.
.DESCRIPTION
Remove branch protection rules from a given GitHub repository.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER OwnerName
Owner of the repository.
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 repository.
The OwnerName and RepositoryName will be extracted from here instead of needing to provide
them individually.
.PARAMETER BranchName
Name of the specific branch to remove the branch protection rule from.
.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.Repository
GitHub.Branch
.OUTPUTS
None
.EXAMPLE
Remove-GitHubRepositoryBranchProtectionRule -OwnerName microsoft -RepositoryName PowerShellForGitHub -BranchName master
Removes branch protection rules from the master branch of the PowerShellForGithub repository.