name: Detect translation file changes


on:
  pull_request_target:
    paths:
      - lang/po/*.po
      - lang/po/*.pot


jobs:
  detect-translation-file-changes:
    runs-on: ubuntu-latest
    steps:
      - name: "Detect translation file changes"
        uses: actions/github-script@v6
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const skip_phrase = 'Translation file changes are intended';
            if (context.payload.pull_request.body.includes(skip_phrase)) {
              console.log('PR body contains skip phrase.  Exiting.');
              return;
            }
            core.setFailed('Translation file changes detected, but a skip phrase is not found in the PR body.')
            console.log(
              'Fetching comments of pull request %d of repository %s/%s.',
              context.issue.number, context.repo.owner, context.repo.repo
            );
            const comments = await github.paginate(
              github.rest.issues.listComments,
              {
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number
              }
            );
            const body = 'It appears you modified a `.po` or `.pot` file.  '
              + 'These translation files are automatically generated, '
              + 'pushed to, and pulled from Transifex, and should not be '
              + 'modified otherwise.  If these changes are intended, please '
              + 'add `' + skip_phrase + '` to the '
              + 'PR body.';
            const bot_comments = comments.filter(
              comment => comment.user.type === 'Bot'
              && comment.user.login === 'github-actions[bot]'
              && comment.body === body
            );
            if (bot_comments.length > 0) {
              console.log('Comment already exists.  Exiting.');
              return;
            }
            console.log('Posting comment.');
            await github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: body
            });
