|
| 1 | +import * as core from "@actions/core"; |
| 2 | +import * as github from "@actions/github"; |
| 3 | + |
| 4 | +type Octokit = ReturnType<typeof github.getOctokit>; |
| 5 | +type CreateCommentParams = NonNullable< |
| 6 | + Parameters<Octokit["rest"]["issues"]["createComment"]>[0] |
| 7 | +>; |
| 8 | +type UpdateCommentParams = NonNullable< |
| 9 | + Parameters<Octokit["rest"]["issues"]["updateComment"]>[0] |
| 10 | +>; |
| 11 | + |
| 12 | +try { |
| 13 | + await main(); |
| 14 | +} catch (err) { |
| 15 | + core.setFailed((err as Error).message); |
| 16 | +} |
| 17 | + |
| 18 | +async function main() { |
| 19 | + const context = github.context.payload.pull_request; |
| 20 | + if (!context) { |
| 21 | + throw new Error( |
| 22 | + "This action should only be run on `pull_request_target` or `pull_request` events", |
| 23 | + ); |
| 24 | + } |
| 25 | + |
| 26 | + const githubToken = core.getInput("github-token", { required: true }); |
| 27 | + const body = core.getInput("body", { required: true }); |
| 28 | + const updateId = core.getInput("update-id"); |
| 29 | + |
| 30 | + const commentMarker = updateId ? getCommentMarker(updateId) : null; |
| 31 | + const commentBody = commentMarker ? `${commentMarker}\n\n${body}` : body; |
| 32 | + const commentParam: CreateCommentParams | UpdateCommentParams = { |
| 33 | + repo: context.base.repo.name, |
| 34 | + owner: context.base.repo.owner.login, |
| 35 | + issue_number: context.number, |
| 36 | + body: commentBody, |
| 37 | + }; |
| 38 | + |
| 39 | + const octokit = github.getOctokit(githubToken); |
| 40 | + |
| 41 | + let existingCommentId: number | undefined; |
| 42 | + if (commentMarker) { |
| 43 | + core.info("Checking for existing comment..."); |
| 44 | + existingCommentId = await octokit.rest.issues |
| 45 | + .listComments({ |
| 46 | + repo: context.base.repo.name, |
| 47 | + owner: context.base.repo.owner.login, |
| 48 | + issue_number: context.number, |
| 49 | + }) |
| 50 | + .then((res) => { |
| 51 | + const comment = res.data.find((c) => c.body?.includes(commentMarker)); |
| 52 | + return comment?.id; |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + if (existingCommentId) { |
| 57 | + core.info(`Updating existing comment (id: ${existingCommentId})...`); |
| 58 | + await octokit.rest.issues.updateComment({ |
| 59 | + ...commentParam, |
| 60 | + comment_id: existingCommentId, |
| 61 | + }); |
| 62 | + core.setOutput("comment-id", existingCommentId); |
| 63 | + } else { |
| 64 | + core.info("Creating new comment..."); |
| 65 | + const result = await octokit.rest.issues.createComment(commentParam); |
| 66 | + core.setOutput("comment-id", result.data.id); |
| 67 | + } |
| 68 | + |
| 69 | + core.info("Done!"); |
| 70 | +} |
| 71 | + |
| 72 | +function getCommentMarker(updateId: string) { |
| 73 | + const prefix = "changesets-action-pr-comment"; |
| 74 | + return prefix === updateId |
| 75 | + ? `<!-- ${prefix} -->` |
| 76 | + : `<!-- ${prefix}:${updateId} -->`; |
| 77 | +} |
0 commit comments