-
-
Save Conduitry/059e153069fe1537dc2143dae3810a06 to your computer and use it in GitHub Desktop.
| #!/bin/sh | |
| set -o errexit | |
| [ $# != 1 ] && { >&2 echo 'Argument: <pull request id>'; exit 1; } | |
| # Get origin remote | |
| origin=$(git remote get-url origin) | |
| # Find target ("owner/repo") of PR | |
| temp=${origin#*github.com?} | |
| [ $origin = $temp ] && { >&2 echo Unrecognized origin.; exit 1; } | |
| target=${temp%.git} | |
| # Find source ("owner/repo") of PR and remote name and branch name | |
| temp=$(curl --silent https://api.github.com/repos/$target/pulls/$1 | perl -MJSON::PP -0777 -E '$head=decode_json(<>)->{head}; say $head->{repo}->{full_name} . ":" . $head->{ref}') | |
| source=${temp%%:*} | |
| remote=$(echo $origin | sed "s $target $source ") | |
| branch=${temp#*:} | |
| # Set up branch and checkout | |
| git fetch --no-tags $remote $branch:pr/$1 | |
| git config branch.pr/$1.remote $remote | |
| git config branch.pr/$1.merge refs/heads/$branch | |
| git checkout pr/$1 |
I needed to make the following change to make this work on MacOS:
-temp=$(curl --silent https://github.com/$target/pull/$1 | grep --max-count=1 head-ref | cut --delimiter=\" --fields=2)
+temp=$(curl --silent https://github.com/$target/pull/$1 | grep --max-count=1 head-ref | cut -d\" -f2)ChatGPT promises me that this should work cross-platform.
Interesting. I've gotten into a habit of using long GNU-style command line options in all my scripts because it's generally a little more clear about what it's actually doing. I did know there were some situations/environments that only support short/POSIX-style switches, and apparently we've run into one here. If I'm going to publish this as a standalone thing, it might make sense to switch everything over to POSIX switches. I'm not sure.
At some point recently, GitHub changed the HTML structure of the page for PRs, and the previous scraping mechanism stopped working. Rather than switch it to something else just as brittle, I've switched over to using the actual GitHub API. I am, however, still hackily parsing the JSON. Because of limitations in sed (in particular, the lack of non-greedy wildcards), I've switched to using Perl, which still should be plenty portable and available. A potential further improvement (while still avoiding requiring that users have jq installed) would be to use proper JSON parsing, if I can figure out a nice one-liner way to do that on the fly in Perl, similar to how one would with jq.
Updated again to use JSON::PP to actually parse the JSON.
Here's a hacky way of using the REST API without
jq(which is probably not much better than scraping the HTML like I'm doing now), but which I wanted to stick somewhere for posterity, in case it can become the basis for something useful later: