-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathgit-pull-request
More file actions
executable file
·279 lines (223 loc) · 9 KB
/
git-pull-request
File metadata and controls
executable file
·279 lines (223 loc) · 9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/env python2
"""git pull-request
Automatically check out github pull requests into their own branch.
Usage:
git pull-request <OPTIONS> <pull request number>
When a PR# is specified, it will be fetched, otherwise a list of PRs
in the remote branch will be shown.
Options:
-h, --help
Display this message and exit
-r <remote or full/repo>, --repo <full/repo>, --remote <remote>
Use this github repo instead of the 'remote origin' or 'github.repo'
git config settings. Full form needs to be "user/repository", otherwise
it is assumed to be a short remote alias name
-g, --git
Use git_url instead of http URL for fetching
--copy
List the Copyright details
Copyright (C) 2011 by Andreas Gohr <[email protected]>
"""
copyright = """
Copyright (C) 2011 by Andreas Gohr <[email protected]>
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, None
git_method = 'html_url'
# parse command line options
try:
opts, args = getopt.getopt(sys.argv[1:], "hr:g", ["help", "repo:", "copy","git"])
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)
elif o in ("--copy"):
print copyright
sys.exit(0)
elif o in ("-g", "--git"):
git_method = 'git_url'
elif o in ("-r", "--repo", "--remote"):
if re.search('/', a):
repo = a
else:
remote = a
# attempt to get token from git config
token = os.popen("git config --get github.token").read().rstrip()
# try to get repo name from git config:
if not repo and not remote:
repo = os.popen('git config --get github.repo').read().strip()
if repo and not re.search('/', repo):
# if repo is not a full repo, assume it is remote alias
remote = repo
repo = None
# else try to get remote from git config:
if not repo:
if not remote:
remote = os.popen('git config --get github.remote').read().strip()
if not remote:
remote = 'origin'
if remote:
# get full repo name from remote url
escaped = pipes.quote(remote)
origin = os.popen("git config --get 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 not repo:
print color_text("Failed to determine github repository name", 'red', True)
print "The repository is usually automatically detected from your remote."
print "By default the remote is assumed to be 'origin', but you can override this by"
print "using the -r parameter or specifying the github.remote option in your config"
print ""
print " git config --global github.remote upstream"
print ""
print "If your remote url 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 ""
print " git config github.repo <user>/<repository>"
sys.exit(1)
# process arguments
if len(args):
ret = fetch(repo, token, args[0], git_method)
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
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)
print
url = "https://api.github.com/repos/%s/pulls" % (repo)
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 not data:
print "failed to speak with github."
return 3
data = json.loads(data)
# print json.dumps(data,sort_keys=True, indent=4)
for pr in data:
display(pr)
return 0
def fetch(repo, token, pullreq, git_method):
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 not 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_method], pr['head']['ref'])
url = pipes.quote(pr['head']['repo'][git_method])
ref = pipes.quote(pr['head']['ref'])
print 'git pull %s %s' % (url, ref)
ret = os.system('git pull %s %s' % (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()