-
Notifications
You must be signed in to change notification settings - Fork 169
/
Tfs.js
432 lines (387 loc) · 13.8 KB
/
Tfs.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
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
const request = require('../requests');
const async = require('async');
/**
* The service which provides build information by using the VSTS REST API
* v2.0. Although the naming of the variables suggest usage with VSTS, the
* code is compatible with both VSTS and TFS. The naming is simply the
* artifact of making the code generalised for both after initial usage
* with VSTS.
* @public
* @constructor
* @see https://www.visualstudio.com/en-us/docs/integrate/api/build/overview
*/
function VSTSRestBuilds() {
let basicAuth = null;
let url = null;
let project = null;
let collection = null;
let params = null;
let includeQueued = null;
let previousBuildsToGet = [];
let apiVersion = null;
let showBuildStep = null;
/**
* This object is the representation of resultFilter mentioned in the docs
* @private
* @see https://www.visualstudio.com/en-us/docs/integrate/api/build/builds
*/
const resultFilter = Object.freeze({
succeeded: 'succeeded',
partiallySucceeded: 'partiallySucceeded',
failed: 'failed',
canceled: 'canceled'
});
/** This object is the representation of statusFilter mentioned in the docs
* @private
* @see https://www.visualstudio.com/en-us/docs/integrate/api/build/builds
*/
const statusFilter = Object.freeze({
inProgress: 'inProgress',
completed: 'completed',
cancelling: 'cancelling',
postponed: 'postponed',
notStarted: 'notStarted',
all: 'all',
});
const timelineRecordState = Object.freeze({
completed: 'completed',
inProgress: 'inProgress',
pending: 'pending'
});
/**
* This object defines the color scheme used.
* @private
*/
const colorScheme = Object.freeze({
succeeded: 'Green',
partiallySucceeded: '#F8A800',
failed: 'Red',
canceled: 'Gray',
inProgress: '#0078D7',
completed: 'Green',
cancelling: '#0078D7',
postponed: 'Gray',
notStarted: 'Gray',
all: 'Gray'
});
/**
* This object defines the compatable api versions that we are allowed to use
* @private
*/
const allowedAPIVersions = Object.freeze({
'2.0': '2.0',
'4.1': '4.1',
undefined: '2.0'
});
/**
* @typedef {Object} Build
* @property {string} definition Build definition id
* @property {Date} startedAt Build start time
* @property {Date} finishedAt Build finish time
* @property {boolean} hasErrors Does the resulting build have errors?
* @property {boolean} hasWarnings Did the build give some warnings?
* @property {boolean} isRunning Is the build currently running?
* @property {boolean} isQueued Is the build currently waiting in the queue?
* @property {string} id Unique ID of the build
* @property {string} number Build number
* @property {string} project Name of the project
* @property {string} reason Reason for building the project
* @property {string} requestedFor Name of the Requester
* @property {string} status The color to be used for displaying
* @property {string} statusText The status of the build
* @property {string} url URL of the project
*/
/**
* It is a node-style callback.
* @callback buildsInfoRequestCallback
* @param {Error|null} err It is an instance of Error
* @param {Array<Build>} listOfBuilds It is an array of {@link Build}
*/
/**
* It exposes the API needed by the application to check the status of builds.
* @name check
* @function
* @public
* @instance
* @memberOf VSTSRestBuilds
* @param {buildsInfoRequestCallback} cb Callback which handles the
* requested build information
*/
this.check = (callback) => {
if (basicAuth && url && project) {
getListOfBuilds(callback);
return;
}
callback('incomplete configuration');
return;
};
/**
* @typedef {Object} VSTSRestBuildsConfiguration
* @property {string} url VS Team Services account
* ({https://{account.visualstudio.com) or TFS server ({http://server:port}).
* @property {string} project Team project ID or name
* @property {string} queryparams Additional queryparams to filter the data
* and provide additional options
* @property {string} username Username
* @property {string} pat Personal Access Token with access to Builds
* information
* @property {boolean} includeQueued Show queued builds
* @property {string} apiVersion The api version to use
* @property {boolean} showBuildStep Adds the current build step to the statusString of the build variable
*/
/**
* It exposes the API needed by the application to provide
* configuration parameters.
* @name check
* @function
* @public
* @instance
* @memberOf VSTSRestBuilds
* @param {VSTSRestBuildsConfiguration} config Configuration parameters
*/
this.configure = (config) => {
/**
* It exposes the configuration passed to the
* configure instance method.
* @public
* @instance
*/
this.configuration = config;
basicAuth = new Buffer(`${config.username}:${config.pat}`)
.toString('base64');
url = config.url;
params = config.queryparams;
project = config.project;
collection = config.collection || 'DefaultCollection';
includeQueued = config.includeQueued || false;
apiVersion = allowedAPIVersions[config.apiVersion] || '2.0';
showBuildStep = config.showBuildStep || false;
console.log(config,apiVersion);
};
/**
* @private
* @param {buildsInfoRequestCallback} cb Callback which handles the
* requested build information
*/
const getListOfBuilds = (callback) => {
const apiUrl = `${url}/${collection}/${project}/_apis/build/builds?api-version=${apiVersion}${params}`;
let options = {
url : apiUrl,
headers: {
Authorization: `Basic ${basicAuth}`,
},
};
// Set up our dependency tree, similar to angular
// http://caolan.github.io/async/v2/docs.html#autoInject
async.autoInject({
// ### 1. Get the list of builds ###
get_builds: (callback) => {
request.makeRequest(options, (err, body) => {
transformData(err, body, callback);
});
},
// ### 2. Get any previous builds ###
get_previous_builds: (get_builds, callback) => {
// No builds to get ? then nothing to add
if (previousBuildsToGet.length === 0) { callback(null); return; }
getPreviousBuilds(get_builds, callback);
},
// ### 3. Merge our 2 arrays ###
merge_builds: (get_builds, get_previous_builds, callback) => {
let builds = [];
if (get_previous_builds && get_previous_builds.shift()) {
builds = [...new Set([...get_builds.shift(),...get_previous_builds.shift()])]; // Merge arrays, removing duplicates
} else {
builds = get_builds;
}
callback(null, builds);
},
// ### 4. Get the current build steps/stage for each build ###
get_build_steps: (merge_builds, callback) => {
// Only get the build step if we are allowed to
if (!showBuildStep) { callback(null, merge_builds); return; }
// http://caolan.github.io/async/v2/docs.html#map
// async.map( collection, async function(collection), callback)
async.map(merge_builds, getLatestBuildStep, (err, results) => {
callback(null, results);
});
}
}, (err, results) => {
// Pass back to the monitor app
callback(err, results.get_build_steps);
});
/**
* Transforms the data received from the request to VSTS REST API
* @private
* @param {any} err If the value is truthy, it indicates an error has
* occurred.
* @param {object} body It contains the response body from VSTS REST API
* @param {buildsInfoRequestCallback} cb Callback which handles the
* requested build information
* @return {null}
*/
const transformData = (err, body, callback) => {
if (err) {
callback(err);
return;
}
if (!(body && body.value)) {
callback('No values found');
return;
}
// Filter out any dummy empty objects
const transformedData = body.value.map(transformer).filter((val) => { return Object.keys(val).length; });
callback(null, transformedData);
};
/**
* The function transforms the data from VSTS API to
* the accepted by callback
* @name transformer
* @private
* @param {object} build individual build information object returned
* from API
* @returns {Build} the object is in the format accepted by the application
*/
const transformer = (build) => {
let color = colorScheme[
build.result ?
resultFilter[build.result] :
(build.status === statusFilter.notStarted ?
statusFilter[statusFilter.notStarted] :
statusFilter[statusFilter.inProgress]
)
];
let text = build.result ?
build.result :
(build.status === statusFilter.notStarted ?
statusFilter.notStarted :
statusFilter.inProgress
);
let webUrl = build._links ?
(build._links.web ? build._links.web.href : build.url) :
build.url;
let getProjectName = build => {
if (build.definition.project) return build.definition.project.name;
if (build.project) return build.project.name;
return null;
};
let result = {
definition: build.definition.name,
finishedAt: build.finishTime ? new Date(build.finishTime) : '',
hasErrors: build.result === resultFilter.failed,
hasWarnings: build.result === resultFilter.partiallySucceeded,
id: build.id,
isRunning: build.status === statusFilter.inProgress,
isQueued: build.status === statusFilter.notStarted,
number: build.buildNumber,
project: getProjectName(build),
queuedAt: build.queueTime ? new Date(build.queueTime) : new Date(),
reason: build.reason,
requestedFor: build.requestedFor ? build.requestedFor.displayName : '',
startedAt: new Date(build.startTime),
status: color,
statusText: text,
timeline: build._links.timeline ? build._links.timeline.href : '',
url: webUrl
};
// Only show queued builds if we're told to
if (result.isQueued && !includeQueued) {
previousBuildsToGet.push(result);
return {}; // Return a dummy empty object (that we will remove later)
}
return result;
};
};
/**
* This function makes an individual API call for each build we need
* to get the previous version for.
* @private
* @param {buildsInfoRequsetCallback} callback Callback which handles the
* requested build information. Each build *must* be returned in the callback,
* whether its been changed or not.
*/
const getPreviousBuilds = (currentBuilds, callback) => {
async.map(previousBuildsToGet, (build, callback) => {
let def = build.definition;
// If we already have a previous build, then we don't need to get another one
const hasPreviousBuild = (val) => { return (val.definition === build.definition) && (val.project === build.project); };
if (currentBuilds.some(hasPreviousBuild)) {
callback(null);
return;
}
// Get the second to last build instead
const options = {
url: `${url}/${collection}/${project}/_apis/build/builds?api-version=${apiVersion}&definitions=${def}&$top=2`
};
request.makeRequest(options, (err, body) => {
if (err) { callback(err); return; }
if (!(body && body.value)) {
console.log('No previous builds found'); // Don't break the rest of the builds if we can't get a previous one
callback(null);
return;
}
let prevBuild = [body.value[1]];
if (prevBuild) {
const transformedData = prevBuild.map(transformer);
callback(null, transformedData[0]);
return;
}
console.log('Unable to fetch previous build'); // Don't break the rest of the builds if we can't get a previous one
callback(null);
});
}, (err, results) => {
callback(null, results);
previousBuildsToGet = [];
});
};
/**
* This function gets the most recent timeline record (aka step) for a build
* @private
* @param {string} timelineURL the url to the timeline VSTS API
*/
const getLatestBuildStep = (build, callback) => {
const timelineURL = build.timeline;
if (!timelineURL || timelineURL === '') {
console.log('no timeline url');
callback(null, build);
return;
}
if (!build.isRunning) {
// The build is already finished, no need to get the latest step
callback(null, build);
return;
}
const apiUrl = timelineURL;
const options = {
url : apiUrl,
headers: {
Authorization: `Basic ${basicAuth}`,
},
};
request.makeRequest(options, (err, body) => {
if (err) {
console.log('getLatestBuildStep:', err);
callback(null, build);
return;
}
if (!(body && body.records)) {
console.log('getLatestBuildStep invalid Body', body);
callback(null, build);
return;
}
// As of API version 2.0 there is no better way of doing this, we *have* to retrieve everything
let records = body.records.sort( (a, b) => {
return a.order - b.order;
});
for (let key in records) {
let record = records[key];
if (record.state === timelineRecordState.inProgress && record.type === 'Task') {
build.statusText += ' - ' + record.name;
}
}
// Return our modified build
callback(null, build);
});
};
}
module.exports = VSTSRestBuilds;