aboutsummaryrefslogtreecommitdiff
path: root/.github/workflows/commentCodeGeneration.ts
blob: 2e8a115cd18c3c7af71e0f6a932489c9b699c64c (plain)
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
import type { context as ctx, GitHub } from '@actions/github/lib/utils';

/**
 * Notifies the PR about uncommitted changes generated by the `generate:*` commands.
 *
 * This script is used by github-script
 * https://github.com/actions/github-script
 *
 * @param github A pre-authenticated octokit/rest.js client with pagination plugins
 * @param context An object containing the context of the workflow run.
 */
export async function script(
  github: InstanceType<typeof GitHub>,
  context: typeof ctx
): Promise<void> {
  const repoArgs = { owner: context.repo.owner, repo: context.repo.repo };

  // Identify the PR that triggered the workflow
  const head_branch: string = context.payload.workflow_run.head_branch;
  const { data: prs } = await github.rest.pulls.list({
    ...repoArgs,
    state: 'open',
    head: head_branch,
  });

  if (prs.length === 0) {
    console.log(`No PRs found for branch ${head_branch}`);
    return;
  }

  const pr_number = prs[0].number;

  // Check if the PR already has a comment from the bot

  const { data: comments } = await github.rest.issues.listComments({
    ...repoArgs,
    issue_number: pr_number,
  });

  const body = `GitHub Actions has found some problems running the preflight checks.

Please make sure to:

- run \`pnpm run preflight\` locally
- fix all issues until the command completes without errors
- commit and push the changes
`;

  const botComment = comments.find(
    (comment) => comment.user?.type === 'Bot' && comment.body?.includes(body)
  );

  const isSuccess = context.payload.workflow_run.conclusion === 'success';

  if (isSuccess) {
    // Delete the bot comment if present
    if (botComment != null) {
      await github.rest.issues.deleteComment({
        ...repoArgs,
        comment_id: botComment.id,
      });
    }
  } else {
    // Create the comment if missing
    if (botComment == null) {
      await github.rest.issues.createComment({
        ...repoArgs,
        issue_number: pr_number,
        body,
      });
    }
  }
}