-
Notifications
You must be signed in to change notification settings - Fork 2.3k
576 lines (383 loc) · 23.9 KB
/
Shared-TierManagement.yml
File metadata and controls
576 lines (383 loc) · 23.9 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
name: Tier management
permissions:
pull-requests: write
contents: write
on:
workflow_call:
inputs:
PayloadJson:
required: true
type: string
EnableWriteSignOff:
required: True
type: string
EnableReadOnlySignoff:
required: True
type: string
secrets:
AccessToken:
required: true
jobs:
tier-management:
name: Tier management
if: github.repository_owner == 'MicrosoftDocs' && github.event_name == 'issue_comment'
runs-on: ubuntu-latest
steps:
- name: Script
shell: pwsh
env:
PayloadJson: ${{ inputs.PayloadJson }}
AccessToken: ${{ secrets.AccessToken }}
EnableWriteSignOff: ${{ inputs.EnableWriteSignOff }}
EnableReadOnlySignoff: ${{ inputs.EnableReadOnlySignoff }}
run: |
# Get GitHub data and event
$GitHubData = $env:PayloadJson | ConvertFrom-Json -Depth 50
$GitRequestEvent = $GitHubData.event_name
$AccessToken = $env:AccessToken
$EnableWriteSignOff = [bool][int]$env:EnableWriteSignOff
# Disabling read-only sign off globally. Switch to TCP doesn't include a read-only sign off and all changes must go through DRI.
# $EnableReadOnlySignoff = [bool][int]$env:EnableReadOnlySignoff
$EnableReadOnlySignoff = $False
$DefaultBranch = $GitHubData.event.repository.default_branch
$GitHubState = $GitHubData.event.issue.state
$GitHubAction = $GitHubData.event.action
$GitHubSender = $GitHubData.event.sender.login
$GitHubRepoName = $GitHubData.event.repository.name
$RepoLabelUrl = $GitHubData.event.repository.labels_url
$IssueUrl = $GitHubData.event.issue.url
$CommentsUrl = $GitHubData.event.issue.comments_url
$PrIssueNumber = $GitHubData.event.issue.number
$PrUrl = $GitHubData.event.issue.pull_request.url
$CommentUser = $GitHubData.event.comment.user.login
$UserPermissionUrl = $GitHubData.event.repository.collaborators_url.Replace("{/collaborator}", "/$CommentUser/permission" )
$GitHubHeaders = @{}
$GitHubHeaders.Add("Authorization","token $($AccessToken)")
$GitHubHeaders.Add("User-Agent", "OfficeDocs")
$ReadyLabelColor = "13FC1F"
$ReadyLabelDescription = "PR is ready for managed service review"
$ReadyLabel = "Ready for Managed Service"
$ReviewResponseHours = 24
$SignOffString = "#sign-off"
$SignOffLabelColor = "46ce1c"
$SignOffLabelDescription = "The pull request is ready to be reviewed and merged by PubOps."
$SignOffLabel = "Sign off"
$InvalidTargetBranchString = "Hi @{1}<br><br>The target (base) branch of this PR, **{2}**, doesn't support the **{0}** command. The **{0}** command can only be used to merge pull requests into the default branch **{3}** or into branches beginning with **release-**.<br><br>Please retarget your PR to either the default branch **{3}** or to a release branch.<br><br>If you have questions, please post a message to https://aka.ms/askanadmin." # Variable substitution happens in script.
$Tier3LabelMissingString = "hi @{1},<br><br>The **{0}** command can't be used on this PR because the none of the files included in it are classified as Tier3/Selfserve. At least one file needs to be classified as Tier3/Selfserve. Please work with the owner of the article(s) (found in the **ms.author** metadata field in the article) to review and merge this PR.<br><br>If you're the owner of the article(s) and your alias is specified in **ms.author**, work with the Magic content team that owns the content set to classify the article(s) as Tier3/Selfserve.<br><br>If you have questions, please post a message to https://aka.ms/askanadmin." -f $SignOffString, $CommentUser
$PrSubmittedToReviewString = "Hi @{0},<br><br>This PR has been sent to our publishing team for review to ensure content quality and completeness. A member of our publishing team will contact you within {1} business hours.<br><br>If you have questions, please post a message to https://aka.ms/askanadmin." -f $CommentUser, $ReviewResponseHours
$SignOffRegex = "(?m)^\s*$SignOffString\s*$"
#####################
#####################
# 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-PrMessage
Function Set-PrMessage {
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$Message
)
$BodyHash = @{}
$BodyHash.body = $Message
$BodyJson = $BodyHash | ConvertTo-Json
$BodyJson
Try {
$Result = Invoke-WebRequest -UseBasicParsing -Uri $CommentsUrl -Body $BodyJson -Headers $GitHubHeaders -Method POST -ErrorAction Stop
$PostCommentSuccess = $True
} Catch {
$PostCommentSuccess = $False
}
Return $PostCommentSuccess
}
#####################
#####################
# Main
Write-Host "Repo: $GitHubRepoName"
Write-Host "Sender: $GitHubSender"
Write-Host "Request event: $GitRequestEvent"
Write-Host "GitHub action: $GitHubAction"
Write-Host "GitHub state: $GitHubState"
Write-Host "Default branch: $DefaultBranch"
Write-Host "PR/Issue number: $PrIssueNumber"
Write-Host "Write sign-off enabled: $EnableWriteSignOff"
Write-Host "Read sign-off enabled: $EnableReadOnlySignoff"
If (($GitRequestEvent -eq "issue_comment") -and (($GitHubAction -eq "created") -or ($GitHubAction -eq "edited"))) {
Write-Host "Comment added or edited on PR."
# Get the contents of the comment that was added to the PR
$CommentBody = $GitHubData.event.comment.body
# Check to see if comment includes $SignOffString by checking if it matches $SignOffRegex
$SignOffFound = $CommentBody -match $SignOffRegex
Write-Host "Regex result: $SignOffFound."
If ($SignOffFound) {
Write-Host "Sign off string `"$SignOffString`" found on PR/Issue #$PrIssueNumber."
# Get permission level of user who created the comment. Need to use .role_name instead of .permission because .permission provides only legacy values.
# .role_name provides legacy plus triage, maintain, and custom roles like write-elevated.
$UserPermission = $(Invoke-RestMethod -Method GET -Headers $GitHubHeaders -Uri $UserPermissionUrl).role_name
Write-Host "User $CommentUser permission level: $UserPermission."
# If user has triage or above, add $SignOffLabel. If not, check whether $ReadyLabel should be added.
If (($UserPermission -like "write*") -or ($UserPermission -eq "maintain") -or ($UserPermission -eq "triage") -or ($UserPermission -eq "admin")) {
# Check to see if sign off for triage and above is enabled for the current repo.
If ($EnableWriteSignOff) {
Write-Host "User $CommentUser has the permission level: $UserPermission. Setting $SignOffLabel label."
# Get PR data so we can get the base branch of the PR. Doing this here so we don't need to do unnecessary calls if other criteria fail.
$PrData = Invoke-RestMethod -Method GET -Headers $GitHubHeaders -Uri $PrUrl
$TargetBranch = $PrData.base.ref
# Check if label exists on the repo.
$LabelExists = Test-RepoLabel -RepoUri $RepoLabelUrl -Name $SignOffLabel
If (!$LabelExists) {
# Create label on the repo if it doesn't exist.
New-RepoLabel -RepoUri $RepoLabelUrl -Name $SignOffLabel -Color $SignOffLabelColor -Description $SignOffLabelDescription
}
$LabelResultsArray = Test-Prlabel -LabelArray $SignOffLabel -IssueUrl $IssueUrl
# Only add the label if it doesn't already exist on the PR
If (!$LabelResultsArray.$SignOffLabel) {
Write-Host "Label $SignOffLabel doesn't exist on $IssueUrl. Adding label."
# Add the label to the PR
Set-PrLabel -IssueUrl $IssueUrl -LabelName $SignOffLabel
}
} Else {
Write-Host "Sign off for users with triage permission or higher is disabled on $GitHubRepoName."
}
} Else {
# Check to see if sign off for read only is enabled for the current repo.
If ($EnableReadOnlySignoff) {
# Get PR data so we can get the base branch of the PR. Doing this here so we don't need to do unnecessary calls if other criteria fail.
$PrData = Invoke-RestMethod -Method GET -Headers $GitHubHeaders -Uri $PrUrl
$TargetBranch = $PrData.base.ref
# Make sure the PR targets branches we care about.
If (($TargetBranch -eq $DefaultBranch) -or ($TargetBranch -like "release-*")) {
Write-Host "Pull request target branch $TargetBranch matches the default branch $DefaultBranch."
# Check if label exists on the repo.
$LabelExists = Test-RepoLabel -RepoUri $RepoLabelUrl -Name $ReadyLabel
If (!$LabelExists) {
# Create label on the repo if it doesn't exist.
New-RepoLabel -RepoUri $RepoLabelUrl -Name $ReadyLabel -Color $ReadyLabelColor -Description $ReadyLabelDescription
}
# Check to see whether $ReadyLabel or Tier3/Selfserve labels exist on the PR. Hashtable that's returned includes the label name and a boolean
# that indicates whether the labels exist on the PR.
# The reason this isn't part of the above repo-level check is because the all the PR-level labels can be retrieved with a single call to GitHub.
# If we included the PR-level checks in the same block as the repo-level checks, we'd be requesting the PR-level repos <number of labels to add> times.
# Don't confuse with the previous ForEach which is a repo-level check.
$LabelResultsArray = Test-Prlabel -LabelArray $ReadyLabel, "Tier3", "Selfserve" -IssueUrl $IssueUrl
Write-Host "Number of items in LabelResultsArray: $($LabelResultsArray.Count)."
# Only add $ReadyLabel if the labels "Tier3" or "Selfserve" exist on the PR
If (($LabelResultsArray.Tier3) -or ($LabelResultsArray.Selfserve)) {
Write-Host "Tier3/Selfserve label exists on $IssueUrl. OK to add $ReadyLabel label."
# Only add the label if it doesn't already exist on the PR
If (!$LabelResultsArray.$ReadyLabel) {
Write-Host "Label $ReadyLabel doesn't exist on $IssueUrl. Adding label."
# Add the label to the PR and post a message to the commenter
Set-PrLabel -IssueUrl $IssueUrl -LabelName $ReadyLabel
Set-PrMessage -Message $PrSubmittedToReviewString
}
} Else {
Write-Host "Tier3/Selfserve label doesn't exist on $IssueUrl. Not adding $ReadyLabel label."
# Post a message to the commenter telling them they don't have the right permissions to use the command.
Set-PrMessage -Message $Tier3LabelMissingString
}
} Else {
Write-Host "Pull request target branch $TargetBranch doesn't match the default branch $DefaultBranch."
# Need to do the string variable replacement here because $TargetBranch doesn't exist until the PR data call a few lines above.
$InvalidTargetBranchString = $InvalidTargetBranchString -f $SignOffString, $CommentUser, $TargetBranch, $DefaultBranch
# Post a message to the commenter telling them they're targeting a branch other than $DefaultBranch or "release-*".
Set-PrMessage -Message $InvalidTargetBranchString
} # Target branch check
} Else {
Write-Host "Sign off for users with read-only permission is disabled on $GitHubRepoName."
}
} # Permission check (triage/write/maintain/admin vs readonly)
} # Sign off string check
} # PR event and action check
set-draft:
name: Set PR as draft
if: github.repository_owner == 'MicrosoftDocs' && github.event_name == 'pull_request_target' && !contains(github.event.pull_request.user.login, '[bot]')
runs-on: ubuntu-latest
steps:
- name: Script
shell: pwsh
env:
PayloadJson: ${{ inputs.PayloadJson }}
AccessToken: ${{ secrets.AccessToken }}
run: |
# Get GitHub data and event
$GitHubData = $env:PayloadJson | ConvertFrom-Json -Depth 50
$GitRequestEvent = $GitHubData.event_name
$AccessToken = $env:AccessToken
$DefaultBranch = $GitHubData.event.repository.default_branch
$GitHubSender = $GitHubData.event.sender.login
$PrUrl = $GitHubData.event.pull_request.url
$CommentsUrl = $GitHubData.event.pull_request.comments_url
$UserPermissionUrl = $GitHubData.event.repository.collaborators_url.Replace("{/collaborator}", "/$GitHubSender/permission" )
$DraftMessage = "<h1>Pull request set to Draft</h1><p>Hi @{0}. <p>To avoid accidentally publishing the changes in this pull request prematurely, its state has been changed to <b>Draft</b>.<p>When you're ready for the changes in this pull request to be published live, select the <b>Ready for review</b> button at the bottom of the page.<p>If you have questions, please post a message to <a href=`"https://aka.ms/askanadmin`">https://aka.ms/askanadmin</a>."
# Create github HTTP authentication header
$GitHubHeaders = @{}
$GitHubHeaders.Add("Authorization","token $($AccessToken)")
$GitHubHeaders.Add("User-Agent", "OfficeDocs")
#####################
#####################
# Set-PrMessage
Function Set-PrMessage {
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$Message
)
$BodyHash = @{}
$BodyHash.body = $Message
$BodyJson = $BodyHash | ConvertTo-Json
$BodyJson
Try {
$Result = Invoke-WebRequest -UseBasicParsing -Uri $CommentsUrl -Body $BodyJson -Headers $GitHubHeaders -Method POST -ErrorAction Stop
$PostCommentSuccess = $True
} Catch {
$PostCommentSuccess = $False
}
Return $PostCommentSuccess
}
#####################
#####################
# Main
# Get permission level of user who created the comment. Need to use .role_name instead of .permission because .permission provides only legacy values.
# .role_name provides legacy plus triage, maintain, and custom roles like write-elevated.
$UserPermission = $(Invoke-RestMethod -Method GET -Headers $GitHubHeaders -Uri $UserPermissionUrl).role_name
Write-Host "User $GitHubSender permission level: $UserPermission."
# If user has triage or above, do nothing, otherwise switch PR to draft.
If (($UserPermission -like "write*") -or ($UserPermission -eq "maintain") -or ($UserPermission -eq "triage") -or ($UserPermission -eq "admin")) {
Write-Host "User has $UserPermission access. Not switching PR to draft."
} Else {
Write-Host "PR URL: $PrUrl"
# REST: get PR node_id
$PrData = Invoke-RestMethod -Method Get -Headers $GitHubHeaders -Uri $PrUrl
$PrNodeId = $PrData.node_id
Write-Host "Setting PR $($PrData.number) to draft. Node ID: $PrNodeId."
$Body = @{
query = @'
mutation($id: ID!){
convertPullRequestToDraft(input:{pullRequestId:$id}) {
pullRequest { number url isDraft }
}
}
'@
variables = @{ id = $PrNodeId }
} | ConvertTo-Json -Depth 5
Try {
$Resp = Invoke-RestMethod -Method Post -Uri "https://api.github.com/graphql" -Headers $GitHubHeaders -ContentType 'application/json' -Body $Body
# Show errors if any, otherwise show the PR
If ($Resp.errors) {
Write-Error ("GraphQL error(s): " + ($Resp.errors | ConvertTo-Json -Depth 10))
} Else {
$Resp.data.convertPullRequestToDraft.pullRequest | ConvertTo-Json -Depth 5
}
$DraftMessage = $DraftMessage -f $GitHubSender
Set-PrMessage -Message $DraftMessage
} Catch {
Write-Host "ERROR: Failed to set PR to draft. Error: $_"
}
}