forked from wbeuil/wait-for-deployment
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (68 loc) · 1.98 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
const core = require('@actions/core');
const github = require('@actions/github');
const sleep = (seconds) =>
new Promise((resolve) => setTimeout(resolve, seconds * 1000));
async function waitForDeployment() {
const { eventName, payload, repo } = github.context;
const token = core.getInput('token');
const timeout = parseInt(core.getInput('timeout'), 10) * 1000;
const endTime = new Date().getTime() + timeout;
let params = {
...repo,
};
core.debug(`eventName? ${eventName}`);
if (eventName === 'pull_request') {
params = {
...params,
sha: payload.pull_request.head.sha,
environment: 'Preview',
};
} else if (eventName === 'push') {
params = {
...params,
sha: payload.head_commit.id,
environment: 'Production',
};
} else {
throw new Error(`Unhandled event: ${eventName}`);
}
let attempt = 1;
const octokit = github.getOctokit(token);
while (new Date().getTime() < endTime) {
try {
const { data: deployments } = await octokit.repos.listDeployments(params);
if (deployments.length > 1) {
throw new Error(
`There should be only one deployment for ${params.sha} but found ${deployments.length} instead.`,
);
}
for (const deployment of deployments) {
const { data: statuses } = await octokit.repos.listDeploymentStatuses({
...repo,
deployment_id: deployment.id,
});
const [success] = statuses.filter(
(status) => status.state === 'success',
);
if (success) {
return success.target_url;
}
}
} catch (error) {
throw error;
}
console.log(`Url unavailable. Attempt ${attempt++}.`);
await sleep(2);
}
throw new Error(
`Timeout reached before deployment for ${params.sha} was found.`,
);
}
(async () => {
try {
const url = await waitForDeployment();
core.setOutput('url', url);
} catch (err) {
core.setFailed(err.message);
}
})();