🤖

忘れがちな robots.txt の確認を GitHub Actions の PR コメントで促す

に公開

robots.txt は更新頻度が高くない分、必要な場面でも見直しを忘れがちです。
そこで今回は、Next.js 前提の話ですが page.tsx が PR に含まれていたら、GitHub Actions で robots.txt の確認を促すコメントを付ける例を紹介します。

やったこと

やったことはシンプルで、PR の差分に page.tsx が含まれていたら、Botが「page.tsx が含まれています」「robots.txt を更新すべきか確認してください」というようなコメントをつけるだけです。
これだけでも確認のきっかけとしては十分機能するかと思います。

page.tsx が含まれていたらコメントする workflow

今回使っている workflow はこんな感じです。

name: Remind robots.txt review on PR

on:
  pull_request_target:
    types:
      - opened
      - synchronize
      - reopened
      - ready_for_review

permissions:
  pull-requests: write

jobs:
  remind-robots-txt:
    runs-on: ubuntu-latest
    steps:
      - name: Comment when page.tsx is included in the PR diff
        uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
        with:
          script: |
            // この workflow が作成したリマインドコメントだけを識別する。
            const marker = '<!-- page-tsx-robots-reminder -->';
            const body = [
              marker,
              '🚧 page.tsxが含まれています。',
              'robots.txtを更新すべきか確認してください。',
            ].join('\n');

            const { owner, repo } = context.repo;
            const issue_number = context.payload.pull_request.number;

            const files = await github.paginate(github.rest.pulls.listFiles, {
              owner,
              repo,
              pull_number: issue_number,
              per_page: 100,
            });

            const hasPageTsx = files.some((file) => file.filename.endsWith('/page.tsx') || file.filename === 'page.tsx');

            const comments = await github.paginate(github.rest.issues.listComments, {
              owner,
              repo,
              issue_number,
              per_page: 100,
            });

            const existingCommentsWithMarker = comments.filter((comment) =>
              comment.user.type === 'Bot' && comment.body.includes(marker)
            );

            if (hasPageTsx) {
              if (existingCommentsWithMarker.length === 0) {
                await github.rest.issues.createComment({
                  owner,
                  repo,
                  issue_number,
                  body,
                });
              }
              return;
            }

            // page.tsx が PR の差分から外れたら、不要になったリマインドを削除する。
            for (const comment of existingCommentsWithMarker) {
              await github.rest.issues.deleteComment({
                owner,
                repo,
                comment_id: comment.id,
              });
            }

そうすると、下記のコメントが PR につくようになります。

page.tsx の変更を検知して robots.txt の確認を促す PR コメント

まとめ

robots.txt の見直しは忘れやすいですが、PR にひとことコメントがつくだけでも確認のきっかけになります。
このような軽いリマインドは、レビューで見落としやすいものを補う仕組みとして便利さを感じています。
robots.txt の確認を忘れにくくする小さな工夫として、参考になればうれしいです。

chot Inc. tech blog

Discussion