-
Notifications
You must be signed in to change notification settings - Fork 2.3k
1611 lines (1068 loc) · 66.1 KB
/
Shared-AutoLabelAssign.yml
File metadata and controls
1611 lines (1068 loc) · 66.1 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
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
name: Auto label and assign pull requests
permissions:
pull-requests: write
contents: read
on:
workflow_call:
inputs:
PayloadJson:
required: true
type: string
ExcludedUserList:
required: true
type: string
ExcludedBranchList:
required: true
type: string
AutoAssignUsers:
required: true
type: string
AutoAssignReviewers:
required: true
type: string
AutoLabel:
required: true
type: string
secrets:
AccessToken:
required: true
PrivateKey:
required: true
ClientId:
required: true
jobs:
build:
name: Run Script
if: github.repository_owner == 'MicrosoftDocs' && contains(github.event.repository.topics, 'build')
runs-on: ubuntu-latest
steps:
- name: Check out repo
id: checkout-repo
uses: actions/checkout@v4
with:
ref: ${{ fromJson(inputs.PayloadJson).event.pull_request.head.sha }}
- name: Create App Token
id: app-token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ secrets.ClientId }}
private-key: ${{ secrets.PrivateKey }}
owner: ${{ github.repository_owner }}
- name: Script
shell: pwsh
env:
GlobalExcludedReviewerList: '[
"dstrome",
"sc-dstrome",
"garycentric",
"garymoore-sc",
"serdarsoysal",
"cx-ktsuji",
"dawntanner",
"pamgreen-msft",
"pebaum",
"SerdarSoysal",
"vinaypamnani-msft"
]'
PayloadJson: ${{ inputs.PayloadJson }}
AccessToken: ${{ secrets.AccessToken }}
AppGitHubAccessToken: ${{ steps.app-token.outputs.token }}
AutoAssignUsers: ${{ inputs.AutoAssignUsers }}
AutoAssignReviewers: ${{ inputs.AutoAssignReviewers }}
AutoLabel: ${{ inputs.AutoLabel }}
ExcludedUserList: ${{ inputs.ExcludedUserList }}
ExcludedBranchList: ${{ inputs.ExcludedBranchList }}
run: |
# Get runspace info
$RepoRoot = $env:GITHUB_WORKSPACE
$RepoName = $env:GITHUB_REPOSITORY
$WorkflowName = $env:GITHUB_WORKFLOW -replace '[\\/:*?"<>|\s]', '_'
$WorkflowRunId = $env:GITHUB_RUN_ID
$WorkflowRunAttempt = $env:GITHUB_RUN_ATTEMPT
$GitHubData = $env:PayloadJson | ConvertFrom-Json -Depth 50
$AccessToken = $env:AccessToken
$GlobalExcludedReviewerList = $env:GlobalExcludedReviewerList | ConvertFrom-Json
$GitHubApiUrl = "https://api.github.com/repos/MicrosoftDocs/"
$GitRequestEvent = $GitHubData.event_name
$DefaultBranch = $GitHubData.event.repository.default_branch
$PrCreator = $GitHubData.event.pull_request.user.login
$TargetBranch = $GitHubData.event.pull_request.base.ref
$GitHubState = $GitHubData.event.pull_request.state
$GitHubAction = $GitHubData.event.action
$PrNumber = $GitHubData.event.pull_request.number
$IsPrDraft = $GitHubData.event.pull_request.draft
$GitHubSender = $GitHubData.event.sender.login
$GitHubRepoName = $GitHubData.event.repository.name
$RepoLabelUrl = $GitHubData.event.repository.labels_url
$PrFileListUrl = "$($GitHubData.event.pull_request.url)/files"
$IssueUrl = $GitHubData.event.pull_request.issue_url
$PrUrl = $GitHubData.event.pull_request.url
$PrHtmlUrl = $GitHubData.event.pull_request.html_url
$CommentsUrl = $GitHubData.event.pull_request.comments_url
$UserPermissionUrl = $GitHubData.event.repository.collaborators_url.Replace("{/collaborator}", "/$PrCreator/permission" )
$AutoAssignUsers = [bool][int]$env:AutoAssignUsers # If it works, it works!
$AutoAssignReviewers = [bool][int]$env:AutoAssignReviewers # Ditto
$AutoLabel = [bool][int]$env:AutoLabel # Ditto ditto
$ExcludedUserList = $env:ExcludedUserList | ConvertFrom-Json
$ExcludedBranchList = $env:ExcludedBranchList | ConvertFrom-Json
$AppGitHubAccessToken = $env:AppGitHubAccessToken
# Set GitHub REST API headers
$GitHubHeaders = @{}
$GitHubHeaders.Add("Authorization","token $AccessToken")
$GitHubHeaders.Add("User-Agent", "OfficeDocs")
# Create github HTTP authentication header using GitHub app installation token
$AppGitHubAccessHeaders = @{}
$AppGitHubAccessHeaders.Add("Authorization","token $($AppGitHubAccessToken)")
$AppGitHubAccessHeaders.Add("User-Agent", "OfficeDocs")
# Regex for string matches
$AuthorRegex = "(?m)^(author:\s{0,3})([\w-]{1,39})(?=\s*(?:#|$))"
$ServiceRegex = "(ms\.service:\s{0,3})([\w|\-|\.]{1,60})"
$SubServiceRegex = "(ms\.subservice:\s{0,3})([\w|\-|\.]{1,60})"
$TechnologyRegex = "(ms\.technology:\s{0,3})([\w|\-|\.]{1,60})"
$ProdRegex = "(ms\.prod:\s{0,3})([\w|\-|\.]{1,60})"
$TierRegex = "(\s*-\s*)(tier\d|Selfserve)"
$LabelColor = "BFDADC"
$LabelDescription = ""
# Central workflow logging parameters
$LoggingRepoName = "officedocs-pr"
$LoggingBranch = "logging"
$LoggingRootDir = ".github/workflow-logs"
$Year = Get-Date -Format yyyy
$Month = Get-Date -Format MM
$LoggingFilePath = "$LoggingRootDir/$RepoName/$Year/$Month/PR$PrNumber/workflow-runs/$WorkflowName/${WorkflowRunId}_${WorkflowRunAttempt}.csv"
$LoggingData = [pscustomobject][ordered]@{
RepoName = $RepoName
PrNumber = $PrNumber
PrUrl = $PrHtmlUrl
PrCreator = $PrCreator
WorkflowSender = $GitHubSender
PrIsDraft = $IsPrDraft
InitialReviewerList = $Null
ValidatedReviewerList = $Null
ReviewStatus = $Null
ReviewDetails = $Null
ServiceSubService = $Null
PrEvent = $GitRequestEvent
PrAction = $GitHubAction
PrState = $GitHubState
WorkflowName = $WorkflowName
WorkflowRunId = $WorkflowRunId
TimeStamp = (Get-Date).ToString("o")
}
# Path to GE Taxonomy service/subservice to Content Lead GitHub team mapping file.
$ServiceToGitHubTeamMapRepo = "officedocs-pr"
$ServiceToGitHubTeamMapFilePath = "/contents/.github/workflows/resources/service-subservice-to-github-team-map.csv"
$ServiceToGitHubTeamMapRef = "main"
$ServiceToGitHubTeamMapUrl = $GitHubApiUrl + $ServiceToGitHubTeamMapRepo + $ServiceToGitHubTeamMapFilePath + "?ref=$ServiceToGitHubTeamMapRef"
# Path to central workflow resources location.
$WorkflowsResourcePath = "https://api.github.com/repos/MicrosoftDocs/microsoft-365-docs/contents/.github/workflows/resources"
$WorkflowsRef = "workflows-prod"
# Set repo variables
$RepoUrl = $GitHubData.event.repository.url
Write-Host "Repository URL: $RepoUrl"
#####################
#####################
# Convert-DocFxMetadataPatternToRegex
Function Convert-DocFxMetadataPatternToRegex {
Param (
[string]$Pattern
)
$Clean = ($Pattern -replace '\\', '/') -replace '^\./', ''
$Regex = [Regex]::Escape($Clean) -replace '/\\\*\\\*/', '/(?:[^/]+/)*' `
-replace '/\\\*\\\*$', '/.*' `
-replace '\\\*\\\*', '.*' `
-replace '\\\*', '[^/]*' `
-replace '\\\?', '[^/]'
# Both absolute (starts with /) and relative patterns should anchor to repo root
Return $Clean.StartsWith('/') ? "^$($Regex.TrimStart('/'))$" : "^$Regex$"
}
#####################
#####################
# Get-DocFxFileMetadataFromPattern
Function Get-DocFxFileMetadataFromPattern {
[CmdletBinding()]
Param (
[object]$PatternTable,
[Parameter(Mandatory = $true)]
[string]$FilePath
)
If ($PatternTable -ne $Null) {
If ($PatternTable -isnot [hashtable]) {
$Ordered = [ordered]@{}
$PatternTable.PSObject.Properties | ForEach-Object { $Ordered[$_.Name] = $_.Value }
$PatternTable = $Ordered
}
$NormPath = ($FilePath -replace '\\', '/') -replace '^\./', ''
Foreach ($Pattern in $PatternTable.Keys) {
If ($NormPath -match (Convert-DocFxMetadataPatternToRegex -Pattern $Pattern)) {
Return $PatternTable[$Pattern]
}
}
} Else {
Write-Host "No data for specified attribute found in DocFx fileMetadata config."
}
Return $null
}
#####################
#####################
# Get-DocFxConfig
Function Get-DocFxConfig {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[string]$FilePath
)
If (-not $RepoRoot) {
Throw 'Repository root could not be determined.'
}
Try {
$FullPath = (Resolve-Path -LiteralPath $FilePath -ErrorAction Stop).Path
$RepoRoot = (Resolve-Path -LiteralPath $RepoRoot -ErrorAction Stop).Path.TrimEnd([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar)
$FileResolved = $True
} Catch {
Write-Host "Unable to resolve $FilePath. File may have been deleted."
$FileResolved = $False
}
If ($FileResolved) {
# Confirm the file is inside the repo
If (-not $FullPath.StartsWith($RepoRoot, [StringComparison]::OrdinalIgnoreCase)) {
Throw 'FilePath is not located underneath the repository root.'
}
# Walk up the tree
$CurrentDir = Split-Path -Path $FullPath -Parent
While ($CurrentDir) {
$Candidate = Join-Path -Path $CurrentDir -ChildPath 'docfx.json'
If (Test-Path -LiteralPath $Candidate -PathType Leaf) {
Write-Host "Getting DocFx config from $Candidate"
Return (Get-Content -LiteralPath $Candidate -Raw) | ConvertFrom-Json -AsHashtable
}
If ($CurrentDir.TrimEnd([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar) -eq $RepoRoot) {
Break
}
# Get the parent of the current folder
$CurrentDir = Split-Path -Path $CurrentDir -Parent
}
}
If ($FileResolved) {
Write-Host "ERROR: File path $FullPath and repo root $RepoRoot were resolved but no docfx.json file was found."
}
# Only reached if $FilePath isn't resolved or if While loop falls through without finding docfx.json.
Return $null
}
#####################
#####################
# Get-FileMetadata
Function Get-FileMetadata {
[cmdletbinding()]
Param (
$PrFileList
)
# Initialize output $FileArray.
$FileArray = @()
# Iterate through each file in the PR.
ForEach ($File in $PrFileList) {
# Initialize variables.
$FileData = @{}
$FileName = $File.filename
$MetadataFound = $False
# Check to see whether current file is markdown or YAML. Those are the only files we care about. Ignore the rest.
$IsContentFile = ($FileName.EndsWith(".md") -or $FileName.EndsWith(".yml")) -and !$FileName.ToLower().Contains("/toc.")
# Only process content files.
If ($IsContentFile) {
Write-Host "Processing file $FileName."
# Retrieve file contents from GitHub. File contents is returned in Base 64 so after contents is retrieved, convert from Base 64 to plain text.
$FileContentsBase64 = Invoke-RestMethod -Method GET -Uri $File.contents_url -Headers $GitHubHeaders
$FileContents = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($FileContentsBase64.content))
# Retrieve DocFx configuration that applies to current file. Retrieving for each file is inefficient but most PRs only have a few files in them.
# Pre-processing to be more efficient could actually use more cycles.
$DocFxConfig = Get-DocFxConfig -FilePath $FileName
# Check to see if the file contents contains a string that matches the $AuthorRegex regex pattern. If yes, add value to $Author. If not, check
# fileMetadata and globalMetadata in that order in DocFx. If there's a match in either of those, return value. If not, or if DocFx couldn't be
# found, return null.
If ($FileContents -match $AuthorRegex) {
$Author = $Matches[2]
$MetadataFound = $True
Write-Host "Found author $Author in file."
} ElseIf ($DocFxConfig -ne $Null) {
Write-Host "Author not found in article. Checking DocFx fileMetadata for $FileName."
$Author = Get-DocFxFileMetadataFromPattern -PatternTable $DocFxConfig.build.fileMetadata.author -FilePath $FileName
If ($Author -ne $Null) {
Write-Host "Author $Author found in DocFx fileMetadata."
$MetadataFound = $True
} Else {
$Author = $DocFxConfig.build.globalMetadata.author
If ($Author -ne $Null) {
Write-Host "Author $Author found in DocFx globalMetadata."
$MetadataFound = $True
} Else {
Write-Host "Author not found in DocFx globalMetadata. Returning null."
$Author = $Null
}
}
} Else {
Write-Host "WARNING: Unable to retrieve author information from article file and unable to retrieve from docfx.json because it couldn't be found. This is expected if file was deleted."
$Author = $Null
}
# Check to see if file contents contains a string that matches the $ServiceRegex regex pattern. If yes, add value to $Service. If not, check
# fileMetadata and globalMetadata in that order in DocFx. If there's a match in either of those, return value. If not, or if DocFx couldn't be
# found, return null.
If ($FileContents -match $ServiceRegex) {
$Service = $Matches[2]
$MetadataFound = $True
Write-Host "Found service $Service in file."
} ElseIf ($DocFxConfig -ne $Null) {
Write-Host "Service not found in article. Checking DocFx fileMetadata for $FileName."
$Service = Get-DocFxFileMetadataFromPattern -PatternTable $DocFxConfig.build.fileMetadata.'ms.service' -FilePath $FileName
If ($Service -ne $Null) {
Write-Host "Service $Service found in DocFx fileMetadata."
$MetadataFound = $True
} Else {
$Service = $DocFxConfig.build.globalMetadata.'ms.service'
If ($Service -ne $Null) {
Write-Host "Service $Service found in DocFx globalMetadata."
$MetadataFound = $True
} Else {
Write-Host "Service not found in DocFx globalMetadata. Returning null."
$Service = $Null
}
}
} Else {
Write-Host "WARNING: Unable to retrieve service information from article file and unable to retrieve from docfx.json because it couldn't be found. This is expected if file was deleted."
$Service = $Null
}
# Check to see if file contents contains a string that matches the $SubServiceRegex regex pattern. If yes, add value to $SubService. If not, check
# fileMetadata and globalMetadata in that order in DocFx. If there's a match in either of those, return value. If not, or if DocFx couldn't be
# found, return null.
If ($FileContents -match $SubServiceRegex) {
$SubService = $Matches[2]
$MetadataFound = $True
Write-Host "Found sub service $SubService in file."
} ElseIf ($DocFxConfig -ne $Null) {
Write-Host "SubService not found in article. Checking DocFx fileMetadata for $FileName."
$SubService = Get-DocFxFileMetadataFromPattern -PatternTable $DocFxConfig.build.fileMetadata.'ms.subservice' -FilePath $FileName
If ($SubService -ne $Null) {
Write-Host "SubService $SubService found in DocFx fileMetadata."
} Else {
$SubService = $DocFxConfig.build.globalMetadata.'ms.subservice'
If ($SubService -ne $Null) {
Write-Host "SubService $SubService found in DocFx globalMetadata."
} Else {
Write-Host "SubService not found in DocFx globalMetadata. Returning null."
$SubService = $Null
}
}
} Else {
Write-Host "WARNING: Unable to retrieve subservice information from article file and unable to retrieve from docfx.json because it couldn't be found. This is expected if file was deleted."
$SubService = $Null
}
# Check to see if file contents contains a string that matches the $ProdRegex regex pattern. If yes, add value to $Product. Then check TechnologyRegex regex pattern.
# If value isn't matched, assign $Null and don't check Technology.
If ($FileContents -match $ProdRegex) {
$Product = $Matches[2]
$MetadataFound = $True
Write-Host "Found product $Product."
If ($FileContents -match $TechnologyRegex) {
$Technology = $Matches[2]
$MetadataFound = $True
Write-Host "Found technology $Technology."
} Else {
$Technology = $Null
}
} Else {
$Product = $Null
}
# Check to see if the file contents contains a string that matches the $TierRegex regex pattern. If yes, add value to $Tier, if not assign $Null.
If ($FileContents -match $TierRegex) {
$Tier = $Matches[2]
$MetadataFound = $True
Write-Host "Found tier $Tier."
} Else {
$Tier = $Null
}
# Add results of above tests to an output object. Each property contains the results of the associated tests from above.
$FileData = @{
Service = $Service
SubService = $SubService
Product = $Product
Technology = $Technology
Tier = $Tier
Author = $Author
FileName = $FileName
}
# If any metadata or author data was found, add it to the $FileArray output array.
If ($MetadataFound) {
Write-Host "Metadata or author data found on $FileName. Adding to output array."
$FileArray += $FileData
}
}
}
# Return $FileArray output array to calling statement.
Return $FileArray
}
Function Format-FileMetadata {
[cmdletbinding()]
Param (
$FileMetadata
)
# Initialize arrays
$MetadataArray = @()
$AuthorArray = @()
# Iterate through each file in the $FileMetaData array. Each element is an individual file found in the PR with six properties containing metadata field values.
Foreach ($File in $FileMetadata) {
# Check whether each property contains data and, if so, add it to the $MetaDataArray and AuthorArray arrays with the format <field value/field type> or <author>.
If ($File.Service -ne $Null) {$MetadataArray += "$($File.Service)/svc"}
If ($File.SubService -ne $Null) {$MetadataArray += "$($File.SubService)/subsvc"}
If ($File.Product -ne $Null) {$MetadataArray += "$($File.Product)/prod"}
If ($File.Technology -ne $Null) {$MetadataArray += "$($File.Technology)/tech"}
If ($File.Tier -ne $Null) {$MetadataArray += $File.Tier.SubString(0,1).ToUpper() + $File.Tier.SubString(1).ToLower()}
If ($File.Author -ne $Null) {$AuthorArray += $File.Author}
}
# Because there might be multiple files in the $MetaDataArray and $AuthorArrays with the same metadata and author data, duplicate values might have been added to the output arrays.
# We only need one instance of each metadata field or author value so the following removes any duplicate values.
$MetadataArray = $MetadataArray | Select-Object -Unique
$AuthorArray = $AuthorArray | Select-Object -Unique
# Added the output arrays to an output hash table.
$OutputHashTable = @{
FileMetadata = $MetadataArray
AuthorMetadata = $AuthorArray
}
# Output the output hash table to the calling statement.
Return $OutputHashTable
}
#####################
#####################
# Test-RepoLabel
Function Test-RepoLabel {
[CmdletBinding()]
param(
$Name,
$RepoUri
)
# Replace placeholder text in the URL retrieved from the GitHub API with the name of the label we're looking for
$LabelUri = $RepoUri.Replace("{/name}","/$Name")
# Check to see if the label we want exists in the repo
Try {
Write-Host "Checking to see if label $Name exists in repo URL $LabelUri."
$LabelResults = Invoke-WebRequest -UseBasicParsing -Uri $LabelUri -Headers $GitHubHeaders -ErrorAction Stop
$LabelFound = $True
} Catch {
# OK if label doesn't exist. Just means we need to create it.
$LabelFound = $False
}
# Return boolean to calling statement
$LabelFound
}
#####################
#####################
# New-RepoLabel
Function New-RepoLabel {
[CmdletBinding()]
param(
$Name,
$Color,
$Description,
$RepoUri
)
# Remove placeholder text from repo URL
$RepoUri = $RepoUri.Replace("{/name}","")
$Result = $Null
# Construct the JSON statement that will be sent to GitHub as the body of the web request. Include the name of the label, its color, and description.
# Convert hash table to JSON
$Body = @{}
$Body.Add("name", $Name)
$Body.Add("color", $Color)
$Body.Add("description", $description)
$Body = $Body | ConvertTo-Json
# Try to submit the request to GitHub API to create the label
Try {
Write-Host "Creating label $Name with color $Color on repo $RepoUri."
$Result = Invoke-RestMethod -Uri $RepoUri -Headers $GitHubHeaders -Body $Body -Method POST
} Catch {
Write-Error "ERROR: Failed to create new label $Name on repo $RepoUri. Error: $($Error[0].Exception.Message)."
}
}
#####################
#####################
# Test-PrLabel
Function Test-Prlabel {
[CmdletBinding()]
param(
$LabelArray,
$IssueUrl
)
# Replace placeholder text in the URL retrieved from the GitHub API with the name of the label we're looking for
$IssueLabelUrl = "$IssueUrl/labels"
$LabelHashTable = @{}
$LabelResults = $Null
# Get list of labels on issue/PR
Try {
Write-Host "Getting labels on issue $IssueLabelUrl."
$LabelResults = Invoke-RestMethod -Uri $IssueLabelUrl -Headers $GitHubHeaders -ErrorAction Stop
} Catch {
Write-Error "ERROR: Failed to get list of labels on $IssueLabelUrl. Error: $($Error[0].Exception.Message)."
}
ForEach ($Label in $LabelArray) {
If ($LabelResults -ne $Null) {
If ($LabelResults.name.Contains($Label)) {
$LabelHashTable.Add($Label, $True)
} Else {
$LabelHashTable.Add($Label, $False)
}
} Else {
$LabelHashTable.Add($Label, $False)
}
}
# Return array of labels on Issue/PR
Return $LabelHashTable
}
#####################
#####################
# Set-PrLabel
Function Set-PrLabel {
param(
$IssueUrl,
$LabelName
)
# Construct label URL based on issue or pull request URL
$IssueLabelUrl = "$IssueUrl/labels"
# Construct JSON statement that will be sent to GitHub as the body of the web request. Includes only the label name. GitHub expects an array even thought it's a single value
# Convert array to JSON
$Body = @()
$Body += $LabelName
$Body = ConvertTo-Json -InputObject $Body
# Try to submit the request to GitHub API to apply they label to the issue or pull request
Try {
Write-Host "Setting label $LabelName on URL $IssueLabelUrl."
$Result = Invoke-RestMethod -Uri $IssueLabelUrl -Body $Body -Headers $GitHubHeaders -Method POST
} Catch {
Write-Error "ERROR: Failed to set label on URL $IssueLabelUrl. Error: $($Error[0].Exception.Message)."
}
}
#####################
#####################
# Set-PrAssignee
Function Set-PrAssignee {
param(
$IssueUrl,
$GitHubAssignees
)
$UsersToAssign = @()
# $ExcludedUserList is a list of users from $DataTableData that shouldn't be assigned to PRs for some reason. If it's $Null, no users need to be excluded.
If ($ExcludedUserList -ne $Null) {
# Loop through each of the eligible assignees found in the PR.
ForEach ($User in $GitHubAssignees) {
# Check if an assignee is found in the exclusion list. If yes, exclude the user by not adding to users to assign list. If no, add the user to the users to assign list.
If ($ExcludedUserList.Contains($User)) {
Write-Host "Excluding $User from assignment list."
} Else {
$UsersToAssign += $User
}
}
} Else {
$UsersToAssign = $GitHubAssignees
}
# Construct JSON statement that will be sent to GitHub as the body of the web request. GitHub expects an array regardless of whether it's a single value or multiple.
# Convert array to JSON
$Body = @{}
$Body.Add("assignees", $UsersToAssign)
$Body = $Body | ConvertTo-Json
$AssigneeUrl = "$IssueUrl/assignees"
# Try to submit the request to GitHub API to apply they label to the issue or pull request
Try {
Write-Host "Setting accounts $UsersToAssign on URL $AssigneeUrl."
$Result = Invoke-RestMethod -Uri $AssigneeUrl -Body $Body -Headers $GitHubHeaders -Method POST
} Catch {
Write-Error "ERROR: Failed assign GitHub accounts on URL $AssigneeUrl. Error: $($Error[0].Exception.Message)."
}
}
#####################
#####################
# Set-PrReviewer
Function Set-PrReviewer {
param(
$PrUrl,
$GitHubReviewers
)
# Ensure ExcludedUserList is always an array (handles $null and single string)
$ExcludedUserList = @($ExcludedUserList)
$UsersToReview = @()
ForEach ($User in $GitHubReviewers) {
If ($User -eq $PrCreator) {
Write-Host "Excluding $User — PR creator."
Continue
}
If ($ExcludedUserList -and ($ExcludedUserList -contains $User)) {
Write-Host "Excluding $User — in exclusion list."
Continue
}
If (-not ($UsersToReview -contains $User)) {
Write-Host "Adding $User to reviewer list."
$UsersToReview += $User
}
}
# Construct JSON statement that will be sent to GitHub as the body of the web request. GitHub expects an array regardless of whether it's a single value or multiple.
# Convert array to JSON
$Body = @{}
$Body.Add("reviewers", @($UsersToReview))
$Body = $Body | ConvertTo-Json
$ReviewerUrl = "$PrUrl/requested_reviewers"
# Try to submit the request to GitHub API to apply they label to the issue or pull request
Try {
Write-Host "Setting accounts $UsersToReview on URL $ReviewerUrl."
$Result = Invoke-RestMethod -Uri $ReviewerUrl -Body $Body -Headers $GitHubHeaders -Method POST
} Catch {
Write-Host "ERROR: Failed assign GitHub accounts on URL $ReviewerUrl. Error: $_."
}
}
#####################
#####################
# Get-ServiceGitHubTeamMappingTable
Function Get-ServiceGitHubTeamMappingTable {
Try {
Write-Host "Getting service/subservice to GitHub team mapping from $ServiceToGitHubTeamMapUrl"
$GitHubMappingTableData = Invoke-RestMethod -Uri $ServiceToGitHubTeamMapUrl -Headers $AppGitHubAccessHeaders
$GitHubMappingTable = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($GitHubMappingTableData.content));
} Catch {
Write-Host "Failed to get service/subservice to GitHub user mapping from $ServiceToGitHubTeamMapUrl"
$GitHubMappingTable = $Null
}
Return $GitHubMappingTable
}
#####################
#####################
# Expand-ServiceSubServiceRows
Function Expand-ServiceSubServiceRows {
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true)]
[String]$CsvContent
)
# Parse the CSV content
$CsvData = $CsvContent | ConvertFrom-Csv
# Initialize array to hold expanded rows
$ExpandedRows = @()
ForEach ($Row in $CsvData) {
# Get the services and subservices, handling null/empty values
$Services = If ([String]::IsNullOrWhiteSpace($Row.Service)) { @('') }
Else { $Row.Service -split ';' | ForEach-Object { $_.Trim() } }
$SubServices = If ([String]::IsNullOrWhiteSpace($Row.SubService)) { @('') }
Else { $Row.SubService -split ';' | ForEach-Object { $_.Trim() } }
# Create a new row for each combination of service and subservice
ForEach ($Service in $Services) {
ForEach ($SubService in $SubServices) {
$NewRow = [PSCustomObject]@{
Product = $Row.Product
Service = $Service
SubService = $SubService
GitHubTeam = $Row.GitHubTeam
}
$ExpandedRows += $NewRow
}
}
}
Return $ExpandedRows
}
#####################
#####################
# Get-GitHubReviewerTeams
Function Get-GitHubReviewerTeams {
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true)]
[string]$Service,
[Parameter(Mandatory = $false)]
[string]$SubService,
[Parameter(Mandatory = $true)]
[array]$DataArray
)
$GitHubTeam = @()
Write-Host "Article service: $Service"
Write-Host "Article subservice: $SubService"
# Filter data based on Service match
$ServiceMatches = $DataArray | Where-Object { $_.service -eq $Service }
Write-Host "Service matches:"
$ServiceMatches | ForEach-Object { Write-Host $_ }
If ($ServiceMatches) {
Write-Host "Service found"
# Check for exact match scenarios
If ($SubService) {
Write-Host "Subservice provided"
# SubService provided - look for exact match