pr2wt.sh 1.7 KB

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