pr2wt.sh 1.6 KB

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