UNPKG

2.43 kBJavaScriptView Raw
1const validate = require('./validate');
2const getLogger = require('./get-logger');
3const getToken = require('./get-token');
4const getJobs = require('./get-jobs');
5const electBuildLeader = require('./elect-build-leader');
6const waitForOtherJobs = require('./wait-for-other-jobs');
7
8/**
9 * Determine if the current job is the build leader (highest node version, smallest version in case multiple identical versions) and if it is wait for all other job to be successful or for one to fails.
10 *
11 * @param {Object} options Options.
12 * @return {Promise<Boolean>} Promise that resolves to `true` if all the other jobs are successful, `false` if at least one job in the build has failed, `null` if this job is not the build leader.
13 * @throws {Error} if doesn't run on Travis
14 * @throws {Error} if the Github authentication token is missing
15 * @throws {Error} if the Github authentication token is not authorized with Travis
16 * @throws {Error} if this job doesn't run on after_success step (TRAVIS_TEST_RESULT is set)
17 */
18module.exports = async ({
19 travisOpts = {},
20 buildLeaderId = process.env.BUILD_LEADER_ID,
21 githubToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN,
22} = {}) => {
23 const logger = getLogger('Travis Deploy Once');
24
25 validate(githubToken);
26
27 const buildId = parseInt(process.env.TRAVIS_BUILD_ID, 10);
28 const travisToken = await getToken(travisOpts, githubToken);
29 const jobs = await getJobs(travisOpts, travisToken, buildId);
30 if (jobs.length === 1) {
31 logger.log('There is only one job for this build.');
32 return true;
33 }
34
35 const versions = jobs.map(job => job.config.node_js);
36 if (versions.filter(job => Boolean(job)).length === 0 && !buildLeaderId) {
37 logger.log(`There is no job in this build defining a node version. Electing job (${jobs.length}) as build leader.`);
38 buildLeaderId = jobs.length;
39 }
40
41 if (!process.env.TRAVIS_JOB_NUMBER.endsWith(`.${buildLeaderId || electBuildLeader(versions, logger)}`)) {
42 logger.log(`The current job (${process.env.TRAVIS_JOB_NUMBER}) is not the build leader.`);
43 return null;
44 }
45
46 const currentJobId = parseInt(process.env.TRAVIS_JOB_ID, 10);
47 const result = await waitForOtherJobs({travisOpts, travisToken, buildId, currentJobId, initialJobs: jobs, logger});
48 if (result) {
49 logger.log('All jobs are successful for this build!');
50 } else {
51 logger.error('At least one job has failed for this build.');
52 }
53 return result;
54};