This repository has been archived by the owner on Mar 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
199 lines (183 loc) · 6.47 KB
/
index.js
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
const { getInput, setFailed, info } = require('@actions/core')
const github = require('@actions/github')
const request = require('request-promise')
function getStatusEmoji (status) {
switch (status) {
case 'success': return ':heavy_check_mark:'
case 'failure': return ':x:'
case 'neutral': return ':black_medium_square:'
case 'cancelled': return ':cancel:' // A custom emoji, included in this repo as cancel.png
case 'skipped': return ':cancel:'
case 'timed_out': return ':x:'
case 'action_required': return ':exclamation:'
default: return ':black_medium_square:'
}
}
function getStatusText (status) {
switch (status) {
case 'success': return 'was *successful*!'
case 'failure': return '*failed*!'
case 'neutral': return 'finished.'
case 'cancelled': return 'was *cancelled*!'
case 'skipped': return 'was *skipped*!'
case 'timed_out': return '*timed out*!'
case 'action_required': return '*requires action*!'
default: return 'finished.'
}
}
const green = '#2ea350'
const red = '#d40200'
const yellow = '#e09c31'
const gray = '#808080'
function getStatusColor (status) {
switch (status) {
case 'success': return green
case 'failure': return red
case 'neutral': return gray
case 'cancelled': return gray
case 'skipped': return gray
case 'timed_out': return red
case 'action_required': return yellow
default: return gray
}
}
// https://api.slack.com/reference/surfaces/formatting#escaping
const ampRegex = /&/g
const ltRegex = /</g
const gtRegex = />/g
function escapeForSlack (string) {
return string.replace(ampRegex, '&').replace(ltRegex, '<').replace(gtRegex, '>')
}
const asteriskRegex = /\*/g
function removeAsterisks (string) {
return string.replace(asteriskRegex, '')
}
async function getFullName (githubUsername) {
try {
const { name } = await request({
method: 'GET',
uri: `https://api.github.com/users/${githubUsername}`,
json: true,
headers: { 'User-Agent': 'byu-oit/github-action-slack' } // GitHub requires a User-Agent, even if it's bogus
})
return name || '?'
} catch (e) {
return '?'
}
}
function getTeamIdFromWebhookUrl (webhookUrl) {
// Webhook URLs look something like
// https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
// We need this: ^^^^^^^^^
const teamId = webhookUrl.substring(33, 42)
return teamId.startsWith('T') ? teamId : '' // Simple sanity check
}
async function run () {
try {
const { context: { eventName } } = github
if (eventName !== 'push' && eventName !== 'pull_request') {
throw Error('Events other than `push` and `pull_request` are not supported.')
}
const status = getInput('status', { required: true })
const channel = getInput('channel', { required: true })
const webhookUrl = getInput('webhook-url', { required: true })
const {
context: {
sha,
workflow,
actor: githubUsername,
runId,
runNumber,
payload: {
action, // Activity Type from https://help.github.com/en/actions/reference/events-that-trigger-workflows#pull-request-event-pull_request
ref,
head_commit: {
message: headCommitMessage
} = {},
repository: {
full_name: repoName
},
pull_request: {
number: pullRequestNumber,
title
} = {}
}
}
} = github
const branch = (eventName === 'push')
? ref.slice('refs/heads/'.length) // ref = 'refs/heads/master'
: github.context.payload.pull_request.head.ref // 'master'
const message = (eventName === 'push')
? headCommitMessage.split('\n')[0]
: title
const fullName = await getFullName(githubUsername)
const boldableWorkflow = removeAsterisks(workflow)
const boldableRepoAndBranch = removeAsterisks(`${repoName}@${branch}`)
const eventMessage = (eventName === 'push')
? `Commit <https://github.com/${repoName}/commit/${sha}|${sha.substring(0, 8)}> pushed`
: `Pull request <https://github.com/${repoName}/pull/${pullRequestNumber}|#${pullRequestNumber}> ${action}`
const body = {
channel,
attachments: [
{
color: getStatusColor(status),
fallback: `The ${escapeForSlack(workflow)} workflow on ${escapeForSlack(repoName)}@${escapeForSlack(branch)} ${getStatusText(status)}`,
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `The *${escapeForSlack(boldableWorkflow)}* workflow on <https://github.com/${repoName}/tree/${branch}|*${escapeForSlack(boldableRepoAndBranch)}*> ${getStatusText(status)}`
},
accessory: {
type: 'button',
text: {
type: 'plain_text',
text: 'View Run',
emoji: false
},
url: `https://github.com/${repoName}/actions/runs/${runId}`
}
},
{
type: 'divider'
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `${getStatusEmoji(status)} *${escapeForSlack(message)}*`
}
},
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `<https://github.com/${repoName}/actions?query=workflow%3A"${encodeURIComponent(workflow)}"|*${escapeForSlack(boldableWorkflow)}*> #${runNumber}: ${eventMessage} by <https://github.com/${githubUsername}|${escapeForSlack(githubUsername)}> (${escapeForSlack(fullName)})`
}
]
},
{
type: 'divider'
}
]
}
]
}
await request({
method: 'POST',
uri: webhookUrl,
body,
json: true
})
const channelQuery = `?channel=${encodeURIComponent(channel.replace(/^#/, ''))}` // Can be a channel ID or name (without #)
const teamId = getTeamIdFromWebhookUrl(webhookUrl)
const teamQuery = teamId ? `&team=${encodeURIComponent(teamId)}` : '' // Will try to use default Slack workspace if not provided
const linkToChannel = `https://slack.com/app_redirect${channelQuery}${teamQuery}`
info(`Slack notification posted to ${channel}! 🎉\n\nLink to channel: ${linkToChannel}`)
} catch (e) {
setFailed(e.message || e)
}
}
run()