|
| 1 | +#!/usr/bin/env bash |
| 2 | + |
| 3 | +# intialize a new worktree from a PR number: |
| 4 | +# |
| 5 | +# - creates a new remote using the fork's clone URL |
| 6 | +# - creates a local branch tracking the remote branch |
| 7 | +# - creates a new worktree in a parent folder, suffixed with "-pr-${PR}" |
| 8 | +# |
| 9 | +# sample usage: |
| 10 | +# ./scripts/pr2wt.sh 12345 |
| 11 | +# ./scripts/pr2wt.sh 12345 opencode |
| 12 | + |
| 13 | +function usage() { |
| 14 | + echo "usage: $0 <pr_number> [cmd]" |
| 15 | + exit 1 |
| 16 | +} |
| 17 | + |
| 18 | +# check we are in the right directory |
| 19 | +if [[ ! -f "scripts/pr2wt.sh" ]]; then |
| 20 | + echo "error: this script must be run from the root of the repository" |
| 21 | + exit 1 |
| 22 | +fi |
| 23 | + |
| 24 | +if [[ $# -lt 1 || $# -gt 2 ]]; then |
| 25 | + usage |
| 26 | +fi |
| 27 | + |
| 28 | +PR=$1 |
| 29 | +[[ "$PR" =~ ^[0-9]+$ ]] || { echo "error: PR number must be numeric"; exit 1; } |
| 30 | + |
| 31 | +url_origin=$(git config --get remote.origin.url) || { |
| 32 | + echo "error: no remote named 'origin' in this repository" |
| 33 | + exit 1 |
| 34 | +} |
| 35 | + |
| 36 | +org_repo=$(echo $url_origin | cut -d/ -f4-) |
| 37 | + |
| 38 | +echo "org/repo: $org_repo" |
| 39 | + |
| 40 | +meta=$(curl -sSf -H "Accept: application/vnd.github+json" "https://api.github.com/repos/${org_repo}/pulls/${PR}") |
| 41 | + |
| 42 | +url_remote=$(echo "$meta" | jq -r '.head.repo.clone_url') |
| 43 | +head_ref=$(echo "$meta" | jq -r '.head.ref') |
| 44 | + |
| 45 | +echo "url: $url_remote" |
| 46 | +echo "head_ref: $head_ref" |
| 47 | + |
| 48 | +git remote rm pr/${PR} |
| 49 | +git remote add pr/${PR} $url_remote |
| 50 | +git fetch pr/${PR} $head_ref |
| 51 | + |
| 52 | +dir=$(basename $(pwd)) |
| 53 | + |
| 54 | +git branch -D pr/$PR 2> /dev/null |
| 55 | +git worktree add -b pr/$PR ../$dir-pr-$PR pr/$PR/${head_ref} 2> /dev/null |
| 56 | + |
| 57 | +wt_path=$(cd ../$dir-pr-$PR && pwd) |
| 58 | + |
| 59 | +echo "git worktree created in $wt_path" |
| 60 | + |
| 61 | +# if a command was provided, execute it |
| 62 | +if [[ $# -eq 2 ]]; then |
| 63 | + cd ../$dir-pr-$PR |
| 64 | + exec $2 |
| 65 | +fi |
0 commit comments