Skip to content

Post Coverage Comment #2437

Post Coverage Comment

Post Coverage Comment #2437

name: Post Coverage Comment
# This workflow handles posting coverage comments for FORKED PRs.
#
# Why a separate workflow?
# - Forked PRs have restricted GITHUB_TOKEN permissions for security
# - They cannot write comments directly to the base repository's PRs
# - workflow_run triggers run in the BASE repository context with full permissions
# - This allows us to safely post comments on forked PRs
#
# How it works:
# 1. PR Code Coverage workflow uploads coverage data as an artifact (forked PRs only)
# 2. This workflow triggers when PR Code Coverage completes successfully
# 3. Downloads the artifact and posts the comment with full write permissions
#
# Same-repo PRs post comments directly in pr-code-coverage.yml (faster)
# Forked PRs use this workflow (required for permissions)
on:
workflow_run:
workflows: ["PR Code Coverage"]
types:
- completed
permissions:
contents: read
jobs:
post-comment:
runs-on: ubuntu-latest
if: >
github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.head_repository.full_name != github.repository
permissions:
actions: read
pull-requests: write
contents: read
steps:
- name: Checkout repo
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
persist-credentials: false
- name: Validate coverage data and post comment
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RUN_ID: ${{ github.event.workflow_run.id }}
run: |
set -euo pipefail
ARTIFACT_DIR="$(mktemp -d "${RUNNER_TEMP}/coverage-comment-data.XXXXXX")"
PULLS_FILE="${RUNNER_TEMP}/associated-pulls.json"
COMMENT_FILE="${RUNNER_TEMP}/coverage-comment.json"
PR_NUMBER_FILE="${RUNNER_TEMP}/coverage-pr-number"
gh run download "$RUN_ID" \
--repo ${{ github.repository }} \
--name coverage-comment-data \
--dir "$ARTIFACT_DIR"
gh api --paginate --slurp \
-H "Accept: application/vnd.github+json" \
"repos/${GITHUB_REPOSITORY}/pulls?state=open&per_page=100" \
| jq 'add' > "$PULLS_FILE"
python .github/scripts/prepare_fork_coverage_comment.py \
--artifact-directory "$ARTIFACT_DIR" \
--event "$GITHUB_EVENT_PATH" \
--associated-pulls "$PULLS_FILE" \
--comment-output "$COMMENT_FILE" \
--pr-number-output "$PR_NUMBER_FILE"
PR_NUMBER="$(cat "$PR_NUMBER_FILE")"
COMMENT_ID="$(
gh api --paginate --slurp \
"repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" \
| jq -r 'add | map(select(
.user.login == "github-actions[bot]" and
(.body | contains("<!-- mssql-python-code-coverage -->"))
)) | .[0].id // empty'
)"
if [[ -n "$COMMENT_ID" ]]; then
gh api --method PATCH \
"repos/${GITHUB_REPOSITORY}/issues/comments/${COMMENT_ID}" \
--input "$COMMENT_FILE" > /dev/null
else
gh api --method POST \
"repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" \
--input "$COMMENT_FILE" > /dev/null
fi