This repository has been archived by the owner on Sep 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcodebuild.ts
278 lines (262 loc) · 7.71 KB
/
codebuild.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
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
import { MessageAttachment, WebClient } from '@slack/web-api';
import {
Channel,
findMessageForId,
MessageResult,
updateOrAddAttachment,
} from './slack';
import {
CodeBuildStatus,
CodeBuildEvent,
CodeBuildStateEvent,
} from './codebuildTypes';
export const buildStatusToColor = (status: CodeBuildStatus): string => {
switch (status) {
case 'IN_PROGRESS':
return '#439FE0';
case 'SUCCEEDED':
return 'good';
case 'TIMED_OUT':
return 'danger';
case 'STOPPED':
return 'danger';
case 'FAILED':
return 'danger';
case 'FAULT':
return 'warning';
case 'CLIENT_ERROR':
return 'warning';
default:
return 'danger';
}
};
const buildStatusToText = (status: CodeBuildStatus): string => {
switch (status) {
case 'IN_PROGRESS':
return 'started';
case 'SUCCEEDED':
return 'passed';
case 'TIMED_OUT':
return 'timed out';
case 'STOPPED':
return 'stopped';
case 'FAILED':
return 'failed';
case 'FAULT':
return 'errored';
case 'CLIENT_ERROR':
return 'had client error';
default:
return 'unknown status';
}
};
export const projectLink = (event: CodeBuildEvent): string => {
return `<https://${event.region}.console.aws.amazon.com/codebuild/home?region=${event.region}#/projects/${event.detail['project-name']}/view|${event.detail['project-name']}>`;
};
// Get the build ID from the Codebuild event
export const buildId = (event: CodeBuildEvent): string => {
return event.detail['build-id'].split(':').slice(-1)[0];
};
// Convert seconds to minutes + seconds
export const timeString = (seconds: number | undefined): string => {
const minute = 60;
if (seconds !== undefined) {
return `${
seconds > minute ? `${Math.floor(seconds / minute)}m` : ''
}${seconds % minute}s`;
}
return '';
};
// a commit sha has a length of 40 chars
const SHA_LENGTH = 40;
// Git revision, possibly with URL
const gitRevision = (event: CodeBuildEvent): string => {
if (event.detail['additional-information'].source.type === 'GITHUB') {
const sourceVersion =
event.detail['additional-information']['source-version'];
if (sourceVersion === undefined) {
return 'unknown';
}
const githubProjectUrl = event.detail[
'additional-information'
].source.location.slice(0, -'.git'.length);
// PR
const pr = sourceVersion.match(/^pr\/(\d+)/);
if (pr) {
return `<${githubProjectUrl}/pull/${pr[1]}|Pull request #${pr[1]}>`;
}
if (sourceVersion.length === SHA_LENGTH) {
return `<${githubProjectUrl}/commit/${sourceVersion}|${sourceVersion}>`;
}
// Branch
return `<${githubProjectUrl}/tree/${sourceVersion}|${sourceVersion}>`;
}
return event.detail['additional-information']['source-version'] || 'unknown';
};
export const buildPhaseAttachment = (
event: CodeBuildEvent,
): MessageAttachment => {
const { phases } = event.detail['additional-information'];
if (phases) {
return {
fallback: `Current phase: ${phases[phases.length - 1]['phase-type']}`,
text: phases
.filter(
phase =>
phase['phase-type'] !== 'SUBMITTED' &&
phase['phase-type'] !== 'COMPLETED',
)
.map(phase => {
if (phase['duration-in-seconds'] !== undefined) {
return `${
phase['phase-status'] === 'SUCCEEDED'
? ':white_check_mark:'
: ':x:'
} ${phase['phase-type']} (${timeString(
phase['duration-in-seconds'],
)})`;
}
return `:building_construction: ${phase['phase-type']}`;
})
.join(' '),
title: 'Build Phases',
};
}
return {
fallback: `not started yet`,
text: '',
title: 'Build Phases',
};
};
// Construct the build message
const buildEventToMessage = (
event: CodeBuildStateEvent,
): MessageAttachment[] => {
const startTime = Date.parse(
event.detail['additional-information']['build-start-time'],
);
// URL to the Codebuild view for the build
const buildUrl = `https://${
event.region
}.console.aws.amazon.com/codebuild/home?region=${event.region}#/builds/${
event.detail['build-id'].split('/')[1]
}/view/new`;
if (event.detail['additional-information']['build-complete']) {
const minute = 60;
const msInS = 1000;
const endTime = Date.parse(event.time);
const elapsedTime = endTime - startTime;
const minutes = Math.floor(elapsedTime / minute / msInS);
const seconds = Math.floor(elapsedTime / msInS - minutes * minute);
const completeText = `<${buildUrl}|Build> of ${projectLink(
event,
)} ${buildStatusToText(event.detail['build-status'])} after ${
minutes ? `${minutes} min ` : ''
}${seconds ? `${seconds} sec` : ''}`;
return [
{
color: buildStatusToColor(event.detail['build-status']),
fallback: completeText,
fields: [
{
short: false,
title: 'Initiator',
value:
event.detail['additional-information'].initiator || 'unknown',
},
{
short: false,
title: 'Git revision',
value: gitRevision(event),
},
...(event.detail['additional-information'].phases || [])
.filter(
phase =>
phase['phase-status'] != null &&
phase['phase-status'] !== 'SUCCEEDED',
)
.map(phase => ({
short: false,
title: `Phase ${phase[
'phase-type'
].toLowerCase()} ${buildStatusToText(
event.detail['build-status'],
)}`,
value: (phase['phase-context'] || []).join('\n'),
})),
],
footer: buildId(event),
text: completeText,
},
buildPhaseAttachment(event),
];
}
const text = `<${buildUrl}|Build> of ${projectLink(
event,
)} ${buildStatusToText(event.detail['build-status'])}`;
return [
{
text,
color: buildStatusToColor(event.detail['build-status']),
fallback: text,
fields: [
{
short: false,
title: 'Initiator',
value: event.detail['additional-information'].initiator || 'unknown',
},
{
short: true,
title: 'Git revision',
value: gitRevision(event),
},
],
footer: buildId(event),
},
buildPhaseAttachment(event),
];
};
// Handle the event for one channel
export const handleCodeBuildEvent = async (
event: CodeBuildEvent,
slack: WebClient,
channel: Channel,
): Promise<MessageResult | void> => {
// State change event
if (event['detail-type'] === 'CodeBuild Build State Change') {
if (event.detail['additional-information']['build-complete']) {
const stateMessage = await findMessageForId(
slack,
channel.id,
buildId(event),
);
if (stateMessage) {
return slack.chat.update({
attachments: buildEventToMessage(event),
channel: channel.id,
text: '',
ts: stateMessage.ts,
}) as Promise<MessageResult>;
}
}
return slack.chat.postMessage({
attachments: buildEventToMessage(event),
channel: channel.id,
text: '',
}) as Promise<MessageResult>;
}
// Phase change event
const message = await findMessageForId(slack, channel.id, buildId(event));
if (message) {
return slack.chat.update({
attachments: updateOrAddAttachment(
message.attachments,
attachment => attachment.title === 'Build Phases',
buildPhaseAttachment(event),
),
channel: channel.id,
text: '',
ts: message.ts,
}) as Promise<MessageResult>;
}
};