-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathShared-AutoLabelMsftContributor.yml
More file actions
450 lines (293 loc) · 15.2 KB
/
Shared-AutoLabelMsftContributor.yml
File metadata and controls
450 lines (293 loc) · 15.2 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
name: Label Microsoft contrib and close PR
permissions:
pull-requests: write
contents: read
on:
workflow_call:
inputs:
PayloadJson:
required: true
type: string
secrets:
AccessToken:
required: true
ClientId:
required: true
PrivateKey:
required: true
jobs:
build:
name: Run Script
if: github.repository_owner == 'MicrosoftDocs'
runs-on: ubuntu-latest
steps:
- 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:
PayloadJson: ${{ inputs.PayloadJson }}
AppGitHubAccessToken: ${{ steps.app-token.outputs.token }}
AccessToken: ${{ secrets.AccessToken }}
ClientId: ${{ secrets.ClientId }}
PrivateKey: ${{ secrets.PrivateKey }}
IsPublicOnlyRepo: ${{ contains(github.event.repository.topics, 'publiconly') }}
run: |
$CurrentDateTime = Get-Date
# Get payload data from GitHub.
$GitHubData = $env:PayloadJson | ConvertFrom-Json -Depth 50
$GitRequestEvent = $GitHubData.event_name
$GitHubAction = $GithubData.event.action
$AccessToken = $env:AccessToken
$AppGitHubAccessToken = $env:AppGitHubAccessToken
$ClientId = $env:ClientId
$PrivateKey = $env:PrivateKey
$IsPublicOnlyRepo = [System.Convert]::ToBoolean($env:IsPublicOnlyRepo)
$RepoName = $GitHubData.event.repository.name
$RepoUrl = $GitHubData.event.repository.url
# URL of the org team to check. We're using the "everyone" team in MicrosoftDocs.
$OrgTeamUrl = "https://api.github.com/orgs/microsoftdocs/teams/everyone/memberships/"
$WorkflowsResourcePath = "https://api.github.com/repos/MicrosoftDocs/microsoft-365-docs/contents/.github/workflows/resources"
$WorkflowsRef = "workflows-prod"
#####################
#####################
# Test-Label
Function Test-Label {
[CmdletBinding()]
param(
$Name,
$RepoUri,
$Headers
)
# 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 {
$LabelResults = Invoke-WebRequest -UseBasicParsing -Uri $LabelUri -Headers $Headers -ErrorAction Stop
$LabelFound = $True
} Catch {
$LabelFound = $False
}
# Return boolean to calling statement
$LabelFound
}
#####################
#####################
# New-Label
Function New-Label {
[CmdletBinding()]
param(
$Name,
$Color,
$Description,
$RepoUri,
$Headers
)
# 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 {
$Result = Invoke-WebRequest -UseBasicParsing -Uri $RepoUri -Headers $Headers -Body $Body -Method POST
} Catch {
$Result = $Error[0].Exception.Message
}
# Return boolean to calling statement
$Result
}
#####################
#####################
# Set-Label
Function Set-Label {
param(
$IssueUrl,
$LabelName,
$Headers
)
# Construct label URL based on 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 pull request
Try {
$Result = Invoke-WebRequest -UseBasicParsing -Uri $IssueLabelUrl -Body $Body -Headers $Headers -Method POST
} Catch {
}
# Send results back to calling statement as an array
$functionresult = @()
$Functionresult += $IssueLabelUrl
$functionresult += $error
$functionresult += $Result
$functionresult
}
#####################
#####################
# Close-Pr
Function Close-Pr {
param(
$PrUrl,
$Headers
)
$Body = @{
state = "closed"
} | ConvertTo-Json
Try {
Write-Host "Closing PR URL: $PrUrl"
Invoke-RestMethod -Uri $PrUrl -Headers $Headers -Method PATCH -Body $Body -ErrorAction Stop
$PrClosed = $True
} Catch {
Write-Host "ERROR: Failed to close PR URL: $PrUrl. Error: $_"
$PrClosed = $False
}
Return $PrClosed
}
#####################
#####################
# Set-PrMessage
Function Set-PrMessage {
Param(
$Message,
$CommentsUrl,
$Headers
)
$BodyHash = @{}
$BodyHash.body = $Message
$BodyJson = $BodyHash | ConvertTo-Json
$BodyJson
Try {
Write-Host "Setting message on comment URL: $CommentsUrl"
$Result = Invoke-RestMethod -Uri $CommentsUrl -Body $BodyJson -Headers $Headers -Method POST -ErrorAction Stop
$PostCommentSuccess = $True
} Catch {
Write-Host "ERROR: Failed to post message to comments URL: $CommentsUrl. Error: $_"
$PostCommentSuccess = $False
}
Return $PostCommentSuccess
}
#####################
#####################
# Get-PrMessage
Function Get-PrMessage {
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$PrMessageFileName,
[Parameter(Mandatory=$True)]
$Headers
)
$PrMessageFile = "$WorkflowsResourcePath/$PrMessageFileName`?ref=$WorkflowsRef"
Try {
Write-Host "Getting PR message from $PrMessageFile"
$PrMessageData = Invoke-RestMethod -Uri $PrMessageFile -Headers $Headers
$PrMessage = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($PrMessageData.content));
} Catch {
Write-Host "Failed to get PR message $PrMessageFileName. Error: $_"
$PrMessage = $Null
}
Return $PrMessage
}
#####################
#####################
# Main
Write-Host "Repo: $($GitHubData.event.repository.name)"
Write-Host "Sender: $($GitHubData.event.sender.login)"
Write-Host "Request type: $GitRequestEvent"
Write-Host "GitHub action: $($GitHubData.event.action)"
# Create general GitHub HTTP authentication header
$GitHubHeaders = @{}
$GitHubHeaders.Add("Authorization","token $($AccessToken)")
$GitHubHeaders.Add("User-Agent", "OfficeDocs")
$GitHubHeaders.Add("Accept","application/vnd.github.mercy-preview+json")
# Create team read GitHub HTTP authentication header. Need a token that has access to org scope. Get-GitHubAppInstallationToken
# requests an installation token from our GitHub app so that we can authenticate. GITHUB_TOKEN that is used to populate $AccessToken
# doesn't have access to org scope so using our GitHub app's access.
$TeamReadGitHubHeaders = @{}
$TeamReadGitHubHeaders.Add("Authorization","token $($AppGitHubAccessToken)")
$TeamReadGitHubHeaders.Add("User-Agent", "OfficeDocs")
$TeamReadGitHubHeaders.Add("Accept","application/vnd.github.mercy-preview+json")
# -and ($GitHubData.event.action -eq "opened")
# Only process event types of 'pull_request_target' that are 'opened' (PR created)
If (($GitRequestEvent -eq "pull_request_target") -and ($GitHubAction -eq "opened")) {
$Contributor = $GitHubData.event.pull_request.user.login
$LabelName = "Microsoft submitter"
$LabelColor = "0269ef"
$LabelDescription = ""
$LabelExists = $False
# Create the member URL to check
$ContributorTeamUrl = $OrgTeamUrl + $Contributor
Write-Host "Checking to see if $Contributor is a member of the MicrosoftDocs `"everyone`" team."
Try {
# Check to see if the contributor is a member of the MicrosoftDocs "everyone" team
$TeamResult = Invoke-RestMethod -Uri $ContributorTeamUrl -Headers $TeamReadGitHubHeaders -ErrorAction Stop
If ($TeamResult.state -eq "active") {
Write-Host "Submitter is an active member of the MicrosoftDocs `"everyone`" team."
# Check to see if the label exists in the repo
If (Test-Label -Name $LabelName -RepoUri $GitHubData.event.repository.labels_url -Headers $GitHubHeaders) {
Write-Host "$LabelName label exists."
$LabelExists = $True
} Else {
Write-Host "$LabelName doesn't exist. Creating."
Try {
# Create the label because it doesn't exist in the repo
$LabelResult = New-Label -Name $LabelName -Color $LabelColor -Description $LabelDescription -RepoUri $GitHubData.event.repository.labels_url -Headers $GitHubHeaders -ErrorAction Stop
} Catch {
$LabelExists = $False
}
# Check the result of the New-Label command to verify it was created successfully
If ($($LabelResult.statusdescription) -eq "Created") {
Write-Host "$LabelName created."
$LabelExists = $True
} Else {
Write-Host "WARNING: $LabelName creation failed. Error: $($Error[0].Exception.Message)."
$LabelExists = $False
}
}
# Only attempt to apply the label if it exists in the repo
If ($LabelExists) {
Write-Host "Setting label on PR."
$LabelUrl = $GitHubData.event.pull_request.issue_url
Write-Host "Using pull request URL $LabelUrl."
# Apply the label to the pull request
Try {
Set-Label -IssueUrl $LabelUrl -LabelName $LabelName -Headers $GitHubHeaders
} Catch {
Write-Host "ERROR: Error setting label. $($Error[0].ErrorDetails.Message)."
}
}
If ($IsPublicOnlyRepo) {
Write-Host "Repo is a public-only repo. Not closing PR."
} Else {
$PrUrl = $GitHubData.event.pull_request.url
$CommentsUrl = $GitHubData.event.pull_request.comments_url
$CloseSuccess = Close-Pr -PrUrl $PrUrl -Headers $GitHubHeaders
If ($CloseSuccess) {
$PrMessage = Get-PrMessage -PrMessageFileName "AutoLabelMsftContributor-PrCloseMessage.md" -Headers $GitHubHeaders
If ($PrMessage) {
Set-PrMessage -Message $PrMessage -Headers $GitHubHeaders -CommentsUrl $CommentsUrl
}
}
}
} Else {
Write-Host "Submitter isn't an active member of the MicrosoftDocs `"everyone`" team."
}
} Catch {
Write-Host "Submitter isn't an active member of the MicrosoftDocs `"everyone`" team."
}
} Else {
Write-Host "Not an opened pull request."
}