This repository has been archived by the owner on Aug 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
364 lines (334 loc) · 12.6 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
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
const TeamcityClient = require("teamcity-client");
const SlackClient = require("@slack/client").WebClient;
const prettyMs = require("pretty-ms");
const filesize = require("filesize");
const lastFinishedBuilds = async (client, whitelist) => {
const project = await client.project.detail({
id: process.env.TC_PROJECT
});
const lastBuilds = {};
if (project.buildTypes.count) {
project.buildTypes.buildType
.filter(buidType => !whitelist.length || whitelist.includes(buidType.id))
.forEach((buildType) => {
lastBuilds[buildType.id] = 0;
});
}
await Promise.all(
Object.keys(lastBuilds).map(async (buildTypeID) => {
const {id} = await lastBuild(client, buildTypeID);
if (typeof id !== "undefined") {
lastBuilds[buildTypeID] = id;
}
})
);
return lastBuilds;
};
const lastBuild = async (client, typeID) => {
const {build} = await client.build.list({
project: process.env.TC_PROJECT,
state: "finished",
canceled: false,
failedToStart: 'any',
lookupLimit: 1,
buildType: typeID
});
if (typeof build === "undefined") {
return null;
}
return build[0];
};
const listBuilds = async (client, beginWithID, whitelist) => {
const {build: unsorted} = await client.build.list({
project: process.env.TC_PROJECT,
state: 'finished',
canceled: false,
failedToStart: 'any',
lookupLimit: 10,
});
if (typeof unsorted === "undefined") {
return [];
}
return unsorted
.sort((build1, build2) => build2.id - build1.id)
.filter(build => build.id > beginWithID)
.filter(build => !whitelist.length || whitelist.includes(build.buildTypeId));
};
const slackSend = async (slack, tc, id, channel) => {
const build = await detailsOfBuild(tc, id);
const fields = [];
if (!build.failedToStart) {
fields.push({
title: "Duration",
value: await durationOfBuild(tc, id),
short: true
});
}
fields.push(
{
title: "Agent",
value: await agent(tc, build),
short: true
},
{
title: "Status",
value: build.statusText,
short: true
}
);
if (!build.failedToStart) {
if (process.env.RELEASE_ARTIFACT) {
fields.push({
title: "Download",
value: await releaseLink(tc, build),
short: true
});
}
if (
!process.env.OMIT_TESTS_IF_PASSED ||
(process.env.OMIT_TESTS_IF_PASSED && build.status !== "SUCCESS")
) {
const tests = await testStatus(tc, build);
fields.push({
title: "Tests",
value: tests.split("\n").slice(0, 4).join("\n")
});
}
}
const changes = await commits(tc, build);
if (
!process.env.OMIT_COMMITS_IF_NONE ||
(process.env.OMIT_COMMITS_IF_NONE && changes !== "Nothing changed")
) {
fields.push({
title: "Commits",
value: changes
});
}
return await slack.chat.postMessage(channel, null, {
attachments: [{
pretext: pretext(build),
color: color(build),
title: title(build),
title_link: build.webUrl,
fields,
mrkdwn_in: ["pretext", "fields"]
}],
});
};
const agent = async (client, build) => {
let emoji = ":linux:";
try {
const agent = await client.httpClient.readJSON(`agents/id:${build.agent.id}`);
let {value: os} = agent.properties.property
.find(property => property.name === "teamcity.agent.jvm.os.name");
os = os.toLowerCase();
if (os.indexOf("mac") > -1) {
emoji = ":osx:";
} else if (os.indexOf("win") > -1) {
emoji = ":windows:"
}
} catch (err) {
console.log("AGENT ERROR:", err);
}
return `${emoji} ${build.agent.name}`;
};
const releaseLink = async (client, build) => {
const {file: files} = await client.artifact.children({id: build.id}, "");
const release = files.find(({name}) => name === process.env.RELEASE_ARTIFACT);
if (!release) {
return "Release not available";
}
return link(
`https://${process.env.TC_HOST}/repository/download/${build.buildTypeId}/${build.id}:id/${release.name}`,
`${release.name} (${filesize(release.size)})`
);
};
const durationOfBuild = async (client, id) => {
const stats = await client.httpClient.readJSON(`builds/id:${id}/statistics`);
return prettyMs(parseInt(stats.property.find(property => property.name === "BuildDuration").value));
};
const detailsOfBuild = async (client, id) => await client.build.detail({id});
const listTests = async (client, build) => await client.httpClient.readJSON(`testOccurrences?locator=build:${build.id}`);
const detailsOfTest = async (client, id) => await client.httpClient.readJSON(`testOccurrences/${id}`);
const testEmoji = test => test.ignored ? ":okay:" : ":goberserk:";
const formatTestName = name => name.slice(process.env.TEST_PACKAGE ? process.env.TEST_PACKAGE.length + 1 : 0);
const failedTestLink = async (client, build, test) => {
const testLink = link(
`${build.webUrl}&tab=buildResultsDiv#testNameId${test.test.id}`,
`${testEmoji(test)} \`${formatTestName(test.name)}\``
);
if (test.status !== "FAILURE" || !process.env.TEST_REPORT_ARTIFACT) {
return testLink;
}
const expr = new RegExp('Screenshot: file:(?:.+)\/tests\/com\/(.+)\.png');
const match = expr.exec(test.details);
// if screenshot found in logs
if (match !== null && typeof match[1] !== "undefined") {
const screenshot = `${process.env.TEST_REPORT_ARTIFACT}%21/tests/com/${match[1]}.png`;
const screenshotLink = link(
`https://${process.env.TC_HOST}/repository/download/${build.buildTypeId}/${build.id}:id/${screenshot}`,
":frame_with_picture:"
);
return `${testLink} ${screenshotLink}`;
}
// trying to find in attachments
const testPath = test.name.replace(/\./g, "/");
const {file: testAttachments} = await client.artifact.children(
{id: build.id},
`${process.env.TEST_REPORT_ARTIFACT}%21/tests/${testPath}/`
);
const {name: foundName} = testAttachments.find(({name}) => name.endsWith(".png"));
if (foundName) {
const screenshot = `${process.env.TEST_REPORT_ARTIFACT}%21/tests/${testPath}/${foundName}`;
const screenshotLink = link(
`https://${process.env.TC_HOST}/repository/download/${build.buildTypeId}/${build.id}:id/${screenshot}`,
":frame_with_picture:"
);
return `${testLink} ${screenshotLink}`;
}
// no luck finding screenshot
return `${testLink}`;
};
const testStatus = async (client, build) => {
let testStatus = ":rollsafe: There were no tests";
if (typeof build.testOccurrences === "undefined" || !build.testOccurrences.count) {
return testStatus;
}
try {
const {testOccurrence: tests} = await listTests(client, build);
const failing = tests
.filter(test => test.status !== "SUCCESS")
.filter(test => process.env.DISPLAY_IGNORED_TESTS !== "false" || test.status !== "UNKNOWN");
if (!failing.length) {
testStatus = `:awesome: All ${tests.length} tests passed!`;
} else {
testStatus = (await Promise.all(
failing.map(async test => await failedTestLink(
client,
build,
await detailsOfTest(client, test.id)
))
)).join("\n");
}
} catch (err) {
console.log("ERROR:", err);
}
return testStatus;
};
const pretext = build => `*${build.buildType.projectName}* build results:`;
const color = build => build.status === "SUCCESS" ? "good" : "danger";
const title = build => `Build "${build.buildType.name}" #${build.number} ${build.status === "SUCCESS" ? "SUCCEEDED" : "FAILED"}`;
const link = (href, text) => `<${href}|${text}>`;
const commitLink = (revision, version) => {
let url = `https://github.com/${revision["vcs-root-instance"].name}/commit/${version}`;
if (process.env.GIT_PLATFORM === "bitbucket") {
url = `https://bitbucket.org/${revision["vcs-root-instance"].name}/commits/${version}`;
}
return link(url, `\`${version.substring(0, 8)}\``);
};
const commitMessage = async (client, changeId) => {
const {comment} = await client.changes.detail(changeId);
return comment.split("\n")[0];
};
const commits = async (client, build) => {
const placeholder = "Nothing changed";
let revision = null;
if (
typeof build.revisions.revision === "undefined" &&
build["snapshot-dependencies"].count
) {
try {
const snapshot = await detailsOfBuild(client, build["snapshot-dependencies"].build[0].id);
revision = snapshot.revisions.revision[0];
build.lastChanges = snapshot.lastChanges;
} catch (err) {
return placeholder;
}
} else {
revision = build.revisions.revision[0];
}
if (typeof build.lastChanges === "undefined") {
return placeholder;
}
const commits = await Promise.all(
build.lastChanges.change
.map(async (change) => {
const link = commitLink(revision, change.version);
const message = await commitMessage(client, change.id);
return `${link} ${message} - _${change.username}_`;
})
);
return commits.join("\n");
};
const main = async () => {
console.log("INITIALIZING..");
const tc = new TeamcityClient({
protocol: "https://",
host: process.env.TC_HOST,
user: process.env.TC_USER,
password: process.env.TC_PASSWORD
});
const slack = new SlackClient(process.env.SLACK_TOKEN);
const channel = process.env.SLACK_CHANNEL;
const timeout = 10000;
let whitelist = [];
if (process.env.BUILD_WHITELIST) {
whitelist = process.env.BUILD_WHITELIST
.split(",")
.map(type => `${process.env.TC_PROJECT}_${type}`);
}
let running = false;
const sentBuilds = [];
const loop = async () => {
if (running) {
return;
}
running = true;
try {
//force finished builds check to catch slower builds
const lastBuilds = await lastFinishedBuilds(tc, whitelist);
console.log("initial state:", lastBuilds);
const lastIDs = Object.values(lastBuilds);
if (process.env.NODE_ENV !== "development" && !sentBuilds.length) {
lastIDs.forEach(id => sentBuilds.push(id));
}
let beginWithID = 0;
if (lastIDs.length) {
beginWithID = Math.min(...lastIDs);
}
console.log(`searching builds newer than ${beginWithID}`);
const builds = await listBuilds(tc, beginWithID, whitelist);
console.log(`found ${builds.length} builds`);
await Promise.all(
builds.reverse().map(async (build) => {
if (
typeof lastBuilds[build.buildTypeId] === 'undefined' ||
lastBuilds[build.buildTypeId] < build.id ||
!sentBuilds.includes(build.id)
) {
console.log(`sending notification for ${build.buildTypeId}#${build.number} (id:${build.id})`);
try {
await slackSend(slack, tc, build.id, channel);
//update finished builds to avoid duplicates within same iteration
if (lastBuilds[build.buildTypeId] < build.id) {
lastBuilds[build.buildTypeId] = build.id;
}
sentBuilds.push(build.id);
console.log('done', lastBuilds);
} catch (err) {
console.log("SEND ERROR:", err);
}
} else {
console.log("SKIPPING", build.buildTypeId, build.id);
}
})
);
} catch (err) {
console.log("ERROR:", err);
}
running = false;
};
setInterval(async () => await loop(), timeout);
};
main();