Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
get_deployment_url.sh
#!/bin/bash
# Output the current deployment URL for a PR.
# - Automatically determines the PR for your current branch if possible.
# Dependencies: `gh` and `jq`
ME=`basename $0`
# helpFunction([error message])
helpFunction()
{
[[ $@ ]] && >&2 echo -e "ERROR: $@\n"
>&2 echo "Usage: ${ME} [PR_NUMBER]"
>&2 echo "Output is the current deployment url if found or empty string if not found."
>&2 echo "Examples:"
>&2 echo "${ME}"
>&2 echo "${ME} 4173"
exit 1 # Exit script after printing help
}
# Check dependencies and exit with an error if they are not found.
# Display some instructions on how to install them.
command -v gh >/dev/null ||
helpFunction "Github CLI not found.\nInstall using 'brew install gh' then 'gh auth login'\nhttps://cli.github.com/manual/"
command -v jq >/dev/null ||
helpFunction "jq command not found.\nInstall using 'brew install jq'\nhttps://stedolan.github.io/jq/"
# Get the PR number from the command line (if specified)
NUMBER=$1
# Otherwise get the PR for the current branch (if possible)
if [ -z "$NUMBER" ]; then
NUMBER=$(gh pr status |
sed -n '/Current branch/ {n;p;}' | # Print line after "Current branch"
grep -Eo '\d+' | # Grab the numbers from the line
head -n1 # Only the first number
)
# Stop if there is no PR.
[[ "$NUMBER" ]] || exit 0
fi
QUERY='query($name: String!, $owner:String!, $number:Int!) {
repository(name: $name, owner:$owner) {
pullRequest(number: $number) {
commits(last: 1) {
nodes {
commit {
deployments(last:1 ) {
nodes {
latestStatus {
environmentUrl
}
}
}
}
}
}
}
}
}'
gh api graphql \
-F owner=':owner' \
-F name=':repo' \
-F number="$NUMBER" \
-f query="$QUERY" |
jq -r '
try .data.repository.pullRequest.commits.nodes[0].commit.deployments.nodes[0].latestStatus.environmentUrl
catch "Could not find RE url. Please try again in a bit." |
select (.!=null)
'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment