-
Notifications
You must be signed in to change notification settings - Fork 6
/
slack-webhook.ts
201 lines (180 loc) · 4.13 KB
/
slack-webhook.ts
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
import fetch from 'node-fetch'
import { setupEnvironment } from './utils'
type Status = 'success' | 'failure' | 'cancelled'
type Env = {
WORKFLOW_NAME?: string
SUITE?: string
STATUS?: Status
SLACK_WEBHOOK_URL?: string
}
const statusConfig = {
success: {
color: parseInt('57ab5a', 16),
emoji: ':white_check_mark:',
},
failure: {
color: parseInt('e5534b', 16),
emoji: ':x:',
},
cancelled: {
color: parseInt('768390', 16),
emoji: ':octagonal_sign:',
},
}
async function run() {
if (!process.env.GITHUB_ACTIONS) {
throw new Error('This script can only run on GitHub Actions.')
}
if (!process.env.SLACK_WEBHOOK_URL) {
console.warn(
"Skipped beacuse process.env.SLACK_WEBHOOK_URL was empty or didn't exist",
)
return
}
if (!process.env.GITHUB_TOKEN) {
console.warn(
"Not using a token because process.env.GITHUB_TOKEN was empty or didn't exist",
)
}
const env = process.env as Env
assertEnv('WORKFLOW_NAME', env.WORKFLOW_NAME)
assertEnv('SUITE', env.SUITE)
assertEnv('STATUS', env.STATUS)
assertEnv('SLACK_WEBHOOK_URL', env.SLACK_WEBHOOK_URL)
await setupEnvironment()
const webhookContent = {
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `${statusConfig[env.STATUS].emoji} ${env.SUITE}`,
},
},
{
type: 'actions',
elements: await actionsElements(env.SUITE),
},
{
type: 'divider',
},
],
}
const res = await fetch(env.SLACK_WEBHOOK_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(webhookContent),
})
if (res.ok) {
console.log('Sent Webhook')
} else {
console.error(`Webhook failed ${res.status}:`, await res.text())
}
}
function assertEnv<T>(
name: string,
value: T,
): asserts value is Exclude<T, undefined> {
if (!value) {
throw new Error(`process.env.${name} is empty or does not exist.`)
}
}
async function createRunUrl(suite: string) {
const result = await fetchJobs()
if (!result) {
return undefined
}
if (result.total_count <= 0) {
console.warn('total_count was 0')
return undefined
}
const job = result.jobs.find((job) => job.name === process.env.GITHUB_JOB)
if (job) {
return job.html_url
}
// when matrix
const jobM = result.jobs.find(
(job) => job.name === `${process.env.GITHUB_JOB} (${suite})`,
)
return jobM?.html_url
}
interface GitHubActionsJob {
name: string
html_url: string
}
async function fetchJobs() {
const url = `${process.env.GITHUB_API_URL}/repos/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}/jobs`
const res = await fetch(url, {
headers: {
Accept: 'application/vnd.github.v3+json',
...(process.env.GITHUB_TOKEN
? {
Authorization: `token ${process.env.GITHUB_TOKEN}`,
// eslint-disable-next-line no-mixed-spaces-and-tabs
}
: undefined),
},
})
if (!res.ok) {
console.warn(
`Failed to fetch jobs (${res.status} ${res.statusText}): ${res.text()}`,
)
return null
}
const result = await res.json()
return result as {
total_count: number
jobs: GitHubActionsJob[]
}
}
async function actionsElements(
suite: string,
): Promise<{ type: string; text: object; value: string; url: string }[]> {
const runUrl = await createRunUrl(suite)
const nxText = await nxRepoInfo()
return [
{
type: 'button',
text: {
type: 'plain_text',
text: 'CI Run details',
emoji: true,
},
value: 'ci_run_details',
url: runUrl as string,
},
{
type: 'button',
text: {
type: 'plain_text',
text: nxText.tagName,
emoji: true,
},
value: 'nx_tag_details',
url: nxText.tagLink,
},
]
}
async function nxRepoInfo() {
const repoText = 'nrwl/nx'
const nextVersion = await nextNxVersion()
const link = `https://github.com/nrwl/nx/commits/${nextVersion}`
return {
tagLink: link,
tagName: `${repoText}@${nextVersion}`,
}
}
run().catch((e) => {
console.error('Error sending webhook:', e)
})
async function nextNxVersion(): Promise<string> {
return fetch(`https://registry.npmjs.org/nx`)
.then((response) => response.json())
.then(
(jsonData) =>
(jsonData as any)?.['dist-tags']?.['next'] ??
(jsonData as any)?.['dist-tags']?.['latest'],
)
}