1- name : Post pull-request comment
1+ # This workflow is the second part of the process described in
2+ # .github/workflows/qhelp-pr-preview.yml
3+ # See that file for more info.
4+
5+ name : Post PR comment
26on :
37 workflow_run :
4- workflows : ["Query help preview" ]
8+ workflows : [Render QHelp changes ]
59 types :
610 - completed
711
812permissions :
913 pull-requests : write
14+ actions : read
1015
1116jobs :
1217 post_comment :
@@ -17,15 +22,53 @@ jobs:
1722 env :
1823 GITHUB_TOKEN : ${{ github.token }}
1924 WORKFLOW_RUN_ID : ${{ github.event.workflow_run.id }}
20- - run : |
21- PR="$(grep -o '^[0-9]\+$' pr.txt)"
25+
26+ - name : Check that PR SHA matches workflow SHA
27+ run : |
28+ PR="$(grep -o '^[0-9]\+$' pr_number.txt)"
2229 PR_HEAD_SHA="$(gh api "/repos/${GITHUB_REPOSITORY}/pulls/${PR}" --jq .head.sha)"
2330 # Check that the pull-request head SHA matches the head SHA of the workflow run
2431 if [ "${WORKFLOW_RUN_HEAD_SHA}" != "${PR_HEAD_SHA}" ]; then
2532 echo "PR head SHA ${PR_HEAD_SHA} does not match workflow_run event SHA ${WORKFLOW_RUN_HEAD_SHA}. Stopping." 1>&2
2633 exit 1
2734 fi
28- gh pr comment "${PR}" --repo "${GITHUB_REPOSITORY}" -F comment.txt
2935 env :
3036 GITHUB_TOKEN : ${{ github.token }}
3137 WORKFLOW_RUN_HEAD_SHA : ${{ github.event.workflow_run.head_commit.id }}
38+
39+ - name : Create or update comment
40+ run : |
41+ COMMENT_PREFIX="QHelp previews"
42+ COMMENT_AUTHOR="github-actions[bot]"
43+ PR_NUMBER="$(grep -o '^[0-9]\+$' pr_number.txt)"
44+
45+ # If there is no existing comment, comment_id.txt will contain just a
46+ # newline (due to jq & gh behaviour). This will cause grep to fail, so
47+ # we catch that.
48+ RAW_COMMENT_ID=$(grep -o '^[0-9]\+$' comment_id.txt || true)
49+
50+ if [ $RAW_COMMENT_ID ]
51+ then
52+ # Fetch existing comment, and validate:
53+ # - comment belongs to the PR with number $PR_NUMBER
54+ # - comment starts with the expected prefix ("QHelp previews")
55+ # - comment author is github-actions[bot]
56+ FILTER='select(.issue_url | endswith($repo+"/issues/"+$pr))
57+ | select(.body | startswith($prefix))
58+ | select(.user.login == $author)
59+ | .id'
60+ COMMENT_ID=$(gh api "repos/${GITHUB_REPOSITORY}/issues/comments/${RAW_COMMENT_ID}" | jq --arg repo "${GITHUB_REPOSITORY}" --arg pr "${PR_NUMBER}" --arg prefix "${COMMENT_PREFIX}" --arg author "${COMMENT_AUTHOR}" "${FILTER}")
61+ if [ $COMMENT_ID ]
62+ then
63+ # Update existing comment
64+ jq --rawfile body comment_body.txt '{"body":$body}' -n | gh api "repos/${GITHUB_REPOSITORY}/issues/comments/${COMMENT_ID}" -X PATCH --input -
65+ else
66+ echo "Comment ${RAW_COMMENT_ID} did not pass validations: not editing." >&2
67+ exit 1
68+ fi
69+ else
70+ # Create new comment
71+ jq --rawfile body comment_body.txt '{"body":$body}' -n | gh api "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" -X POST --input -
72+ fi
73+ env :
74+ GITHUB_TOKEN : ${{ github.token }}
0 commit comments