Skip to content

Instantly share code, notes, and snippets.

@vgarvardt
Created December 9, 2014 09:33
Show Gist options
  • Save vgarvardt/33d03e2c6b1f0a12aa0c to your computer and use it in GitHub Desktop.
Save vgarvardt/33d03e2c6b1f0a12aa0c to your computer and use it in GitHub Desktop.
List all PRs
#!/usr/bin/env python
"""git pull-request
Automatically check out github pull requests into their own branch.
Usage:
git pull-request <OPTIONS> [<pull request number>]
Options:
-h, --help
Display this message and exit
-r <repo>, --repo <repo>
Use this github repo instead of the 'remote origin' or 'github.repo'
git config settings. Needs to be in "user/repository" form
Copyright (C) 2011 by Andreas Gohr <andi@splitbrain.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import sys
import getopt
import json
import urllib2
import os
import re
import pipes
def main():
repo, remote = '', None
# parse command line options
try:
opts, args = getopt.getopt(sys.argv[1:], "hr:", ["help", "repo:"])
except getopt.error, msg:
print msg
print "for help use --help"
sys.exit(2)
# process options
for o, a in opts:
if o in ("-h", "--help"):
print __doc__
sys.exit(0)
if o in ("-r", "--repo"):
if re.search('/', a):
repo = a
else:
remote = a
if remote is None and repo == '':
remote = 'origin'
# attempt to get token from git config
token = os.popen("git config --get github.token").read().rstrip()
# get repo name from git config:
if(repo == ''):
repo = os.popen('git config github.repo').read().strip()
# get repo name from origin
if(repo == '' or remote is not None):
escaped = pipes.quote(remote)
origin = os.popen("git config remote.%s.url" % escaped).read()
origin = re.sub("(\.git)?\s*$", "", origin)
m = re.search(r"\bgithub\.com[:/]([^/]+/[^/]+)$", origin)
if(m is not None):
repo = m.group(1)
if(repo == ''):
print color_text("Failed to determine github repository name", 'red', True)
print "The repository is usually automatically detected from your remote origin."
print "If your origin doesn't point to github, you can specify the repository on"
print "the command line using the -r parameter, by specifying either a remote or"
print "the full repository name (user/repo), or configure it using"
print "git config github.repo <user>/<repository>"
sys.exit(1)
# process arguments
if len(args):
ret = fetch(repo, token, args[0])
else:
ret = show(repo, token)
sys.exit(ret)
def display(pr):
"""Nicely display info about a given pull request
"""
#print "%s - %s" % (color_text('REQUEST %s' % pr.get('number'), 'green'), pr.get('title'))
#print " %s" % (color_text(pr['head']['label'], 'yellow'))
#print " by %s %s" % (pr['user'].get('login'), color_text(pr.get('created_at')[:10], 'red'))
#print " %s" % (color_text(pr.get('html_url'), 'blue'))
#print
print '"%s";"%s";"%s";"%s";"%s";"%s"' % (pr.get('number'), pr.get('created_at')[:10], pr['user'].get('login'), pr.get('title'), pr['head']['label'], pr.get('html_url'))
def show(repo, token):
"""List open pull requests
Queries the github API for open pull requests in the current repo
"""
print "loading open pull requests for %s..." % (repo)
if len(token):
headers = {'User-Agent': 'git-pull-request', 'Authorization': 'token %s' % token}
else:
headers = {'User-Agent': 'git-pull-request'}
page = 0
prs = []
while True:
print "fetching page %d..." % page
req = urllib2.Request("https://api.github.com/repos/%s/pulls?page=%d" % (repo, page,), headers=headers)
try:
response = urllib2.urlopen(req)
except urllib2.HTTPError, msg:
print "error loading pull requests for repo %s: %s" % (repo, msg)
if msg.code == 404:
# GH replies with 404 when a repo is not found or private and we request without OAUTH
print "if this is a private repo, please set github.token to a valid GH oauth token"
exit(1)
data = response.read()
if (data == ''):
print "failed to speak with github."
return 3
data = json.loads(data)
# print json.dumps(prs, sort_keys=True, indent=4)
if not len(data):
break
prs.extend(data)
page += 1
print ""
for pr in prs:
display(pr)
return 0
def fetch(repo, token, pullreq):
print "loading pull request info for request %s..." % (pullreq)
print
url = "https://api.github.com/repos/%s/pulls/%s" % (repo, pullreq)
if len(token):
headers = {'User-Agent': 'git-pull-request', 'Authorization': 'token %s' % token}
else:
headers = {'User-Agent': 'git-pull-request'}
req = urllib2.Request(
url, headers=headers)
try:
response = urllib2.urlopen(req)
except urllib2.HTTPError, msg:
print "error loading pull requests for repo %s: %s" % (repo, msg)
if msg.code == 404:
# GH replies with 404 when a repo is not found or private and we request without OAUTH
print "if this is a private repo, please set github.token to a valid GH oauth token"
exit(1)
data = response.read()
if (data == ''):
print "failed to speak with github."
return 3
data = json.loads(data)
pr = data
print json.dumps(pr, sort_keys=True, indent=4, separators=(',', ': '))
if pr['head']['repo'] is None:
print("remote repository for this pull request "
"does not exist anymore.")
return 6
display(pr)
local = pipes.quote('pull-request-%s' % (pullreq))
branch = os.popen("git branch|grep '^*'|awk '{print $2}'").read().strip()
if(branch != pr['base']['ref'] and branch != local):
print color_text("The pull request is based on branch '%s' but you're on '%s' currently" % (pr['base']['ref'], branch), 'red', True)
return 4
ret = os.system('git branch %s' % (local))
ret = os.system('git checkout %s' % (local))
if(ret != 0):
print "Failed to create/switch branch"
return 5
print "pulling from %s (%s)" % (pr['head']['repo']['git_url'], pr['head']['ref'])
git_url = pipes.quote(pr['head']['repo']['git_url'])
ref = pipes.quote(pr['head']['ref'])
print 'git pull %s %s' % (git_url, ref)
ret = os.system('git pull %s %s' % (git_url, ref))
if(ret != 0):
print color_text("branch %s no longer exists." % ref, 'red')
os.system('git checkout %s' % branch)
os.system('git branch -D %s' % local)
exit(1)
print
print color_text("done. examine changes and merge into master if good", 'green')
return 0
def color_text(text, color_name, bold=False):
"""Return the given text in ANSI colors
From http://travelingfrontiers.wordpress.com/2010/08/22/how-to-add-colors-to-linux-command-line-output/
"""
colors = (
'black', 'red', 'green', 'yellow',
'blue', 'magenta', 'cyan', 'white'
)
if not sys.stdout.isatty():
return text
if color_name in colors:
return '\033[{0};{1}m{2}\033[0m'.format(
int(bold),
colors.index(color_name) + 30,
text)
else:
return text
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment