Skip to content

Instantly share code, notes, and snippets.

@djmitche
Created October 29, 2019 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djmitche/b6a5abde37298437bb2a5d30812743a2 to your computer and use it in GitHub Desktop.
Save djmitche/b6a5abde37298437bb2a5d30812743a2 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python3
import re
import sys
import json
import urllib.request
import argparse
import subprocess
# get config
try:
repo_url = subprocess.check_output(['git', 'remote', 'get-url', 'upstream']).strip().decode('utf-8')
if not repo_url.startswith('https://'):
print("`upstream` remote must be an https URL")
sys.exit(1)
repo_url = repo_url.split('/')
owner = repo_url[3]
repo = re.sub(r'\.git$', '', repo_url[4])
except subprocess.CalledProcessError:
print("`upstream` remote must exist")
sys.exit(1)
def main():
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('pullreq', metavar='PR', type=int,
help='pull request to pull')
parser.add_argument('-f', '--force', dest='force', action='store_true',
default=False,
help='overwrite an existing branch with this name')
parser.add_argument('-p', '--pr-branch', dest='prbranch', action='store_true',
default=False,
help='use branch name `pr<PULLREQ>`')
args = parser.parse_args()
url = 'https://api.github.com/repos/%s/%s/pulls/%s' % (owner, repo, args.pullreq)
res = urllib.request.urlopen(url)
data = json.load(res)
remote = data['head']['repo']['owner']['login']
remote_url = data['head']['repo']['clone_url']
source_ref = data['head']['ref']
# add the remote if necessary
try:
subprocess.check_call(['git', 'remote', 'add', remote, remote_url], stderr=subprocess.DEVNULL)
except subprocess.CalledProcessError:
pass
# fetch its refs
subprocess.check_call(['git', 'fetch', remote])
# set up a new branch tracking it
branch = 'pr{}'.format(args.pullreq) if args.prbranch else source_ref
try:
subprocess.check_call(['git', 'checkout', '-B' if args.force else '-b', branch, '--track', '{}/{}'.format(remote, source_ref)])
except subprocess.CalledProcessError:
sys.exit(1)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment