Skip to content

Instantly share code, notes, and snippets.

@MarkusH
Created April 2, 2016 14:05
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 MarkusH/14d538fecd79367349c8ded0a03e4ec3 to your computer and use it in GitHub Desktop.
Save MarkusH/14d538fecd79367349c8ded0a03e4ec3 to your computer and use it in GitHub Desktop.
git command to checkout a github pull-request from a remote repository and optionally rebase it onto a base branch
#!/usr/bin/env python
# Put this file somewhere in $PATH and name it git-pr
# Also, add the following or simialar lines to .git/config
#
# [pr]
# base = master
# remote = upstream
import subprocess
import click
def get_all_branches():
proc = subprocess.Popen(['git', 'branch'], stdout=subprocess.PIPE)
stdout, _ = proc.communicate()
return sorted(v.strip(' *') for v in stdout.decode('utf-8').split('\n') if v)
def get_all_remotes():
proc = subprocess.Popen(['git', 'remote'], stdout=subprocess.PIPE)
stdout, _ = proc.communicate()
return sorted(stdout.decode('utf-8').split())
def get_default_base():
proc = subprocess.Popen(['git', 'config', 'pr.base'], stdout=subprocess.PIPE)
stdout, _ = proc.communicate()
return stdout.decode('utf-8').strip()
def get_default_remote():
proc = subprocess.Popen(['git', 'config', 'pr.remote'], stdout=subprocess.PIPE)
stdout, _ = proc.communicate()
return stdout.decode('utf-8').strip()
@click.command()
@click.option('--base',
default=get_default_base(),
type=click.Choice(get_all_branches()),
help='The base branch.')
@click.option('--remote',
default=get_default_remote(),
type=click.Choice(get_all_remotes()),
help='Where to fetch the PR from')
@click.option('--rebase/--no-rebase',
default=False,
help='Rebase PR on base')
@click.argument('pr')
def git_pr(base, remote, rebase, pr):
subprocess.call(['git', 'checkout', '-f', base])
subprocess.call(['git', 'pull', remote, base])
subprocess.call(['git', 'branch', '-Df', 'pr/%s' % pr])
subprocess.call(['git', 'fetch', remote, 'pull/%s/head:pr/%s' % (pr, pr)])
subprocess.call(['git', 'checkout', 'pr/%s' % pr])
if rebase:
subprocess.call(['git', 'rebase', base])
if __name__ == '__main__':
git_pr()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment