bin/gh-pr

#!/usr/bin/env bash
# bin/gh-pr — open the current branch's PR in the browser.
# Falls back to listing open PRs for the repo if none exists for HEAD.

set -euo pipefail

if ! command -v gh >/dev/null 2>&1; then
  printf 'gh-pr: gh CLI is not installed\n' >&2
  exit 127
fi

if ! git rev-parse --git-dir >/dev/null 2>&1; then
  printf 'gh-pr: not a git repo\n' >&2
  exit 1
fi

branch=$(git rev-parse --abbrev-ref HEAD)
if [[ "$branch" == "HEAD" ]]; then
  printf 'gh-pr: detached HEAD\n' >&2
  exit 1
fi

# Was a PR number given explicitly?
if [[ "${1-}" =~ ^[0-9]+$ ]]; then
  exec gh pr view --web "$1"
fi

# Try a PR for the current branch.
if gh pr view --head "$branch" --json url -q .url >/dev/null 2>&1; then
  exec gh pr view --head "$branch" --web
fi

printf 'gh-pr: no PR for %s\n' "$branch"
printf 'open PRs:\n'
gh pr list --state open --limit 20
printf '\n(pass a PR number to open it: gh-pr 123)\n'