UNPKG

2.05 kBJavaScriptView Raw
1const semver = require('semver');
2
3/**
4 * Find the build leader based on the node version of the build's jobs.
5 *
6 * @param {Array<String>} versions List of node versions, one for each job, ordered in order as the jobs
7 * @param {Object} logger To log info and error
8 * @return {Number} the build leader position (correspond to the position in the aray of versions)
9 */
10module.exports = (versions, logger) => {
11 logger.log(
12 `Electing build leader among builds with Node versions: ${
13 Array.isArray(versions) ? versions.join(', ') : versions
14 }.`
15 );
16 // If there is only one candidate, then it's the winner
17 if (!Array.isArray(versions) || versions.length === 1) {
18 logger.log(`Electing job (1) as build leader.`);
19 return 1;
20 }
21
22 // If there is a latest stable/lts node it's the winner
23 // https://docs.travis-ci.com/user/languages/javascript-with-nodejs/#Specifying-Node.js-versions
24 const stable = versions.lastIndexOf('node') + 1;
25 if (stable) {
26 logger.log(`Electing job (${stable}) as build leader as it runs on the latest node stable version.`);
27 return stable;
28 }
29 const lts = versions.lastIndexOf('lts/*') + 1;
30 if (lts) {
31 logger.log(`Electing job (${lts}) as build leader as it runs on the node lts version.`);
32 return lts;
33 }
34
35 // Convert to Strings as it's expected by semver
36 versions = versions.map(version => String(version));
37 // Otherwise we use the lower bound of all valid semver ranges
38 const validRanges = versions.filter(semver.validRange);
39 const lowVersionBoundaries = validRanges.map(semver.Range).map(r => r.set[0][0].semver.version);
40
41 // Then we find the highest of those
42 const highestVersion = semver.sort([...lowVersionBoundaries]).pop();
43 const highestRange = validRanges[lowVersionBoundaries.lastIndexOf(highestVersion)];
44 // And make its build job the winner
45 const buildLeader = versions.lastIndexOf(highestRange) + 1;
46 logger.log(`Electing job (${buildLeader}) as build leader as it runs the highest node version (${highestRange}).`);
47 return buildLeader;
48};