Skip to content

Instantly share code, notes, and snippets.

@davidsword
Last active June 2, 2020 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsword/43f3c333c7d5485243a23ec00b48ffa6 to your computer and use it in GitHub Desktop.
Save davidsword/43f3c333c7d5485243a23ec00b48ffa6 to your computer and use it in GitHub Desktop.
Github GraphQL API - Trace a commit back to a PR and get the username of who approved it
GH_TOKEN=""
GH_REPO=""
GH_OWNER=""
GH_SHA=""
# Get the PULL number that's realted to the commit on this build
PULL=$(curl -H "Authorization: bearer ${GH_TOKEN}" -s -d "{ \
\"query\": \"query { \
repository(owner: \\\"$GH_OWNER\\\", name: \\\"$GH_REPO\\\") { \
commit: object(expression: \\\"$GH_SHA\\\") { \
... on Commit { \
associatedPullRequests(first: 5) { \
edges { \
node { \
number \
} \
} \
} \
} \
} \
} \
} \
\"}" https://api.github.com/graphql)
# Verify a Pull # was returned
REGEX_PULL="number\"\:([0-9]*)";
if [[ $PULL =~ $REGEX_PULL ]]; then
GH_PULL_NUM=${BASH_REMATCH[1]}
# Get the last review on the PR that was APPROVED
REVIEW=$(curl -H "Authorization: bearer ${GH_TOKEN}" -s -d "{ \
\"query\": \"query { \
repository(name: \\\"$GH_REPO\\\", owner: \\\"$GH_OWNER\\\") { \
pullRequest(number: $GH_PULL_NUM) { \
id \
reviews(last: 1, states: APPROVED) { \
edges { \
node { \
state \
author { \
login \
} \
createdAt \
} \
} \
} \
} \
} \
}\
\"}" https://api.github.com/graphql)
REGEX_USER="login\"\:\"([a-zA-Z0-9_-]*)\"";
if [[ $REVIEW =~ $REGEX_USER ]]; then
REVIEW_USER=${BASH_REMATCH[1]}
else
REVIEW_USER="<unknown>"
fi
REGEX_TIME="createdAt\"\:\"([0-9A-Z:-]*)\"";
if [[ $REVIEW =~ $REGEX_TIME ]]; then
REVIEW_TIME=${BASH_REMATCH[1]}
else
REVIEW_TIME="<unknown>"
fi
COMMIT_MSG="This commit is from <name of CI>, triggered by a merge of https://github.com/$GH_OWNER/$GH_REPO/pull/$GH_PULL_NUM approved by @$REVIEW_USER at $REVIEW_TIME"
else
COMMIT_MSG="This commit is from <name of CI>, unable to associate $GH_SHA to a PR."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment