Last active
June 2, 2020 22:14
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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