Skip to content

Instantly share code, notes, and snippets.

@webpro
Created November 18, 2025 08:44
Show Gist options
  • Select an option

  • Save webpro/7d49ef6c3f2d792cf63f9006a7237fbf to your computer and use it in GitHub Desktop.

Select an option

Save webpro/7d49ef6c3f2d792cf63f9006a7237fbf to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -ne 1 ]] || [[ "$1" =~ ^-h|--help$ ]]; then
echo "Usage: gh-co-pr <pr-number>" >&2
exit 0
fi
pr="$1"
remote="pr$pr"
command -v gh >/dev/null 2>&1 || { echo "GitHub CLI (gh) is required" >&2; exit 1; }
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || {
echo "Run this inside a git repository" >&2
exit 1
}
gh pr checkout "$pr" >/dev/null
branch=$(git branch --show-current)
read owner repo head <<<"$(gh pr view "$pr" \
--json headRepositoryOwner,headRepository,headRefName \
--jq '[(.headRepositoryOwner?.login // ""), (.headRepository?.name // ""), .headRefName] | @tsv')"
[[ -n "$head" ]] || { echo "Could not determine head branch for PR #$pr" >&2; exit 1; }
if [[ -n "$owner" && -n "$repo" ]]; then
url="[email protected]:$owner/$repo.git"
else
url="$(git remote get-url origin)"
fi
if git remote get-url "$remote" >/dev/null 2>&1; then
current="$(git remote get-url "$remote")"
[[ "$current" == "$url" ]] || { echo "Remote $remote points to $current" >&2; exit 1; }
else
git remote add "$remote" "$url"
fi
git config "branch.$branch.remote" "$remote"
git config "branch.$branch.merge" "refs/heads/$head"
echo "Checked out PR #$pr on $branch" >&2
echo "Remote: $remote -> $url" >&2
echo "Push with: git push $remote --no-follow-tags" >&2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment