Repository navigation
Expand file tree
/
Copy pathpreview-panel.cjs
More file actions
52 lines (45 loc) · 2.29 KB
/
Copy pathpreview-panel.cjs
File metadata and controls
52 lines (45 loc) · 2.29 KB
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
// Preview panel in the PR description, kept between two markers.
const START = '<!-- cloudflare-preview:start -->';
const END = '<!-- cloudflare-preview:end -->';
const SECTION = new RegExp(`${START}[\\s\\S]*?${END}`);
function alert(kind, heading, lines = []) {
return [`> [!${kind}]`, `> **${heading}**`, ...(lines.length ? ['>', ...lines.map((l) => `> ${l}`)] : [])];
}
function pending(sha) {
return alert('NOTE', `Preview deployment pending for \`${sha.substring(0, 7)}\``, [
'This panel updates automatically when the Cloudflare previews finish building.',
]);
}
function result(previews, { sha, logs, commitUrl }) {
const short = sha.substring(0, 7);
const failed = previews.filter((p) => p.status !== 'success');
const head = failed.length
? alert('CAUTION', `Preview deployment failed for ${failed.map((p) => p.site).join(', ')}`, [
`[View workflow logs](${logs})`,
])
: alert('IMPORTANT', 'Preview ready', [`[View workflow logs](${logs})`]);
const rows = previews.map((p) =>
p.status === 'success'
? `| ${p.site} | [Latest on branch](${p.branch}) | [\`${short}\`](${p.commit}) | ✅ Deployed |`
: `| ${p.site} | | | ❌ Failed |`,
);
return [...head, '', `Commit [\`${short}\`](${commitUrl})`, '', '| Site | Branch | Commit | Status |', '| --- | --- | --- | --- |', ...rows];
}
// The open PR for this branch, if any.
async function findPull({ github, context }, branch) {
if (context.payload.pull_request) return context.payload.pull_request.number;
const { owner, repo } = context.repo;
const { data } = await github.rest.pulls.list({ owner, repo, state: 'open', head: `${owner}:${branch}` });
return data[0]?.number ?? null;
}
async function update({ github, context }, pull_number, lines) {
const block = [START, ...lines, END].join('\n');
const { owner, repo } = context.repo;
// Re-read so edits made during the build are kept.
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number });
const current = pr.body || '';
const body = SECTION.test(current) ? current.replace(SECTION, block) : `${block}\n\n${current}`;
if (body.replace(/\r\n/g, '\n') === current.replace(/\r\n/g, '\n')) return;
await github.rest.pulls.update({ owner, repo, pull_number, body });
}
module.exports = { pending, result, findPull, update };