Skip to content

Commit

Permalink
chore: update deploy branch
Browse files Browse the repository at this point in the history
  • Loading branch information
hunghg255 committed Nov 9, 2023
1 parent 9a1b90a commit 404c1db
Show file tree
Hide file tree
Showing 6 changed files with 297 additions and 189 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ jobs:
- `dist`: dist folder deployed to [surge.sh](https://surge.sh/).
- `failOnError`: Set `failed` if a deployment throws error, defaults to `false`.
- `teardown`: Determines if the preview instance will be torn down on PR close, defaults to `false`.
- `preview_branch`: deploy to a branch, defaults to `false`.

### Outputs

Expand Down
5 changes: 5 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ inputs:
description: 'Determines if the preview instance will be torn down on PR close'
default: 'false'
required: false
preview_branch:
description: 'Determines if the current branch is a preview branch'
default: 'false'
required: false

outputs:
preview_url:
description: 'The url for the related PR preview'
2 changes: 1 addition & 1 deletion lib/index.js

Large diffs are not rendered by default.

62 changes: 62 additions & 0 deletions src/deploy/branch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/* eslint-disable indent */
/* eslint-disable unicorn/consistent-destructuring */
/* eslint-disable unicorn/no-null */

import * as core from '@actions/core';
import { exec } from '@actions/exec';
import * as github from '@actions/github';

import { execSurgeCommand } from '../helpers';

let failOnErrorGlobal = false;
let fail: (err: Error) => void;

export const deployBranch = async ({ surgeToken, dist, failOnError }: any) => {
failOnErrorGlobal = failOnError;
core.debug(`failOnErrorGlobal: ${typeof failOnErrorGlobal} + ${failOnErrorGlobal.toString()}`);

core.debug('github.context');
core.debug(JSON.stringify(github.context, null, 2));

// @ts-ignore
const repoOwner = github.context.repo.owner.replaceAll('.', '-');
// @ts-ignore
const repoName = github.context.repo.repo.replaceAll('.', '-');

const currentBranch = github.context.ref.replace('refs/heads/', '');

const url = `${repoOwner}-${repoName}-${currentBranch}.surge.sh`;

core.setOutput('preview_url', url);

const startTime = Date.now();
try {
if (core.getInput('build')) {
const buildCommands = core.getInput('build').split('\n');
for (const command of buildCommands) {
core.info(`RUN: ${command}`);
await exec(command);
}
} else {
await exec('npm install');
await exec('npm run build');
}

await exec('cp', [`${dist}/index.html`, `${dist}/200.html`]);

const duration = (Date.now() - startTime) / 1000;
core.info(`Build time: ${duration} seconds`);
core.info(`Deploy to ${url}`);
core.setSecret(surgeToken);

await execSurgeCommand({
command: ['surge', `./${dist}`, '--token', surgeToken, '--cleanup'],
});

await execSurgeCommand({
command: ['surge', `./${dist}`, url, '--token', surgeToken],
});
} catch (error: any) {
fail?.(error);
}
};
210 changes: 210 additions & 0 deletions src/deploy/pull-request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
/* eslint-disable indent */
/* eslint-disable unicorn/consistent-destructuring */
/* eslint-disable unicorn/no-null */

import * as core from '@actions/core';
import { exec } from '@actions/exec';
import * as github from '@actions/github';

import { comment } from '../commentToPullRequest';
import { execSurgeCommand, formatImage, getCommentFooter } from '../helpers';

let failOnErrorGlobal = false;
let fail: (err: Error) => void;

export const deployPullRequest = async ({
surgeToken,
octokit,
dist,
teardown,
failOnError,
}: any) => {
failOnErrorGlobal = failOnError;
core.debug(`failOnErrorGlobal: ${typeof failOnErrorGlobal} + ${failOnErrorGlobal.toString()}`);
let prNumber: number | undefined;

core.debug('github.context');
core.debug(JSON.stringify(github.context, null, 2));
const { job, payload } = github.context;
core.debug(`payload.after: ${payload.after}`);
core.debug(`payload.pull_request: ${payload.pull_request}`);
const gitCommitSha =
payload.after || payload?.pull_request?.head?.sha || payload?.workflow_run?.head_sha;
core.debug(JSON.stringify(github.context.repo, null, 2));

core.debug(`payload.pull_request?.head: ${payload.pull_request?.head}`);
const fromForkedRepo = payload.pull_request?.head.repo.fork;

if (payload.number && payload.pull_request) {
prNumber = payload.number;
} else {
const result = await octokit.rest.repos.listPullRequestsAssociatedWithCommit({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
commit_sha: gitCommitSha,
});
const pr = result.data.length > 0 && result.data[0];
core.debug('listPullRequestsAssociatedWithCommit');
core.debug(JSON.stringify(pr, null, 2));
prNumber = pr ? pr.number : undefined;
}

if (!prNumber) {
core.info('😢 No related PR found, skip it.');
return;
}

core.info(`Find PR number: ${prNumber}`);

const commentIfNotForkedRepo = (message: string) => {
// if it is forked repo, don't comment
if (fromForkedRepo) {
core.info('PR created from a forked repository, so skip PR comment');
return;
}
comment({
repo: github.context.repo,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
number: prNumber!,
message,
octokit,
header: job,
});
};

fail = (err: Error) => {
core.info('error message:');
core.info(JSON.stringify(err, null, 2));
commentIfNotForkedRepo(`
😭 Deploy PR Preview ${gitCommitSha} failed. [Build logs](https://github.com/${
github.context.repo.owner
}/${github.context.repo.repo}/actions/runs/${github.context.runId})
${formatImage({
buildingLogUrl,
imageUrl:
'https://user-images.githubusercontent.com/507615/90250824-4e066700-de6f-11ea-8230-600ecc3d6a6b.png',
})}
${getCommentFooter()}
`);
if (failOnError) {
core.setFailed(err.message);
}
};

// @ts-ignore
const repoOwner = github.context.repo.owner.replaceAll('.', '-');
// @ts-ignore
const repoName = github.context.repo.repo.replaceAll('.', '-');
const url = `${repoOwner}-${repoName}-${job}-pr-${prNumber}.surge.sh`;

core.setOutput('preview_url', url);

let data;

try {
const result = await octokit.rest.checks.listForRef({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
ref: gitCommitSha,
});
data = result.data;
} catch (error: any) {
fail(error);
return;
}

core.debug(JSON.stringify(data?.check_runs, null, 2));

// 尝试获取 check_run_id,逻辑不是很严谨
let checkRunId;
if (data?.check_runs?.length >= 0) {
const checkRun = data?.check_runs?.find((item: any) => item.name === job);
checkRunId = checkRun?.id;
}

const buildingLogUrl = checkRunId
? `https://github.com/${github.context.repo.owner}/${github.context.repo.repo}/runs/${checkRunId}`
: `https://github.com/${github.context.repo.owner}/${github.context.repo.repo}/actions/runs/${github.context.runId}`;

core.debug(`teardown enabled?: ${teardown}`);
core.debug(`event action?: ${payload.action}`);

if (teardown && payload.action === 'closed') {
try {
core.info(`Teardown: ${url}`);
core.setSecret(surgeToken);
await execSurgeCommand({
command: ['surge', 'teardown', url, '--token', surgeToken],
});

return commentIfNotForkedRepo(`
:recycle: [PR Preview](https://${url}) ${gitCommitSha} has been successfully destroyed since this PR has been closed.
${formatImage({
buildingLogUrl,
imageUrl:
'https://user-images.githubusercontent.com/507615/98094112-d838f700-1ec3-11eb-8530-381c2276b80e.png',
})}
${getCommentFooter()}
`);
} catch (error: any) {
return fail?.(error);
}
}

commentIfNotForkedRepo(`
⚡️ Deploying PR Preview ${gitCommitSha} to [surge.sh](https://${url}) ... [Build logs](${buildingLogUrl})
${formatImage({
buildingLogUrl,
imageUrl:
'https://user-images.githubusercontent.com/507615/90240294-8d2abd00-de5b-11ea-8140-4840a0b2d571.gif',
})}
${getCommentFooter()}
`);

const startTime = Date.now();
try {
if (core.getInput('build')) {
const buildCommands = core.getInput('build').split('\n');
for (const command of buildCommands) {
core.info(`RUN: ${command}`);
await exec(command);
}
} else {
await exec('npm install');
await exec('npm run build');
}

await exec('cp', [`${dist}/index.html`, `${dist}/200.html`]);

const duration = (Date.now() - startTime) / 1000;
core.info(`Build time: ${duration} seconds`);
core.info(`Deploy to ${url}`);
core.setSecret(surgeToken);

await execSurgeCommand({
command: ['surge', `./${dist}`, url, '--token', surgeToken],
});

commentIfNotForkedRepo(`
🎊 PR Preview ${gitCommitSha} has been successfully built and deployed to https://${url}
:clock1: Build time: **${duration}s**
${formatImage({
buildingLogUrl,
imageUrl:
'https://user-images.githubusercontent.com/507615/90250366-88233900-de6e-11ea-95a5-84f0762ffd39.png',
})}
${getCommentFooter()}
`);
} catch (error: any) {
fail?.(error);
}
};
Loading

0 comments on commit 404c1db

Please sign in to comment.