I wanted something similar to find a PR for a given commit, then comment on the PR with Jenkins build info. Here's how that works using GH API:
# for a given SHA and repo
SHA=58d8b4407ab5d2b9a696236202308d92d3e25340
ownerRepo=redhat-developer/devspaces
# a. use gh to query a given repo for closed pulls for a given commitSHA; return the PR URL
PR_COMMENTS_URL=$(curl -sSL -H "Authorization: token ${GITHUB_TOKEN}" -H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${ownerRepo}/pulls?state=closed" | \
yq -r --arg SHA "$SHA" '.[]|select(.head.sha == $SHA)|.comments_url')
# b. comment on the PR by URL: https://api.github.com/repos/redhat-developer/devspaces/issues/848/comments
if [[ $PR_COMMENTS_URL ]]; then
curl -sSL -H "Authorization: token ${GITHUB_TOKEN}" -H "Accept: application/vnd.github.v3+json" \
-X POST -d '{"body": "Building in currentBuild.absoluteUrl (GH API TEST)"}' "${PR_COMMENTS_URL}" | yq -r '.html_url'
fi
Then you can wrap this script inside a Jenkins groovy/bash block, and pass in currentBuild.absoluteUrl
from the running build to the GH pull request.
Equivalent code using gh cli:
# 0. install gh CLI
sudo yum -y -q install https://github.com/cli/cli/releases/download/v2.20.2/gh_2.20.2_linux_amd64.rpm
# a. use gh to query a given repo for merged PRs for a given commitSHA; return the PR URL
PR_HTML_URL=$(gh pr list --repo ${ownerRepo} --state merged --json url --jq '.[].url' \
--search $SHA)
# b. comment on the PR by URL: https://github.com/redhat-developer/devspaces/pull/848
if [[ $PR_HTML_URL ]]; then
gh pr comment $PR_HTML_URL -b "Building in currentBuild.absoluteUrl (GH CLI TEST)"
fi
For a sample of Jenkins pipeline code:
https://gist.github.com/nickboldt/efb8d1b3a60c079e46b5b7aab4412e22#file-commentonpr-fragment-jenkinsfile