forked from trentm/googlecode2github
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathshadowissues.py
More file actions
Latest commit
333 lines (269 loc) · 11.2 KB
/
Copy pathshadowissues.py
File metadata and controls
333 lines (269 loc) · 11.2 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#!/usr/bin/env python
"""
Usage:
python googlecode2github/shadowissues.py GCPROJ GHPROJ
where "GCPROJ" is the Google Code project name, e.g. "python-markdown2"; and
"GHPROJ" is the github project id, e.g. "trentm/python-markdown2".
Limitations:
- Only supports public issues in a Google Code project. This *could* get into
google code auth to access protected issues. Patches welcome. :)
To obtain an OAuth access token:
curl -u 'USERNAME' -d '{"scopes":["public_repo"],"note":"shadowissues"}' https://api.github.com/authorizations
curl -H "Authorization: bearer TOKEN" https://api.github.com/users/USERNAME -I
This token will show up in the Authorized applications
(https://github.com/settings/applications) and can be revoked at any time.
"""
__version__="1.0.0"
importre
importsys
importos
fromos.pathimport*
fromglobimportglob
frompprintimportpprint
importcodecs
importjson
importoperator
importdatetime
fromhashlibimportmd5
fromxml.sax.saxutilsimportunescapeashtml_unescape
fromxml.etreeimportElementTreeasET
sys.path.insert(0, join(dirname(abspath(__file__)), "externals/lib"))
importhttplib2
importappdirs
#---- globals
dirs=appdirs.AppDirs("googlecode2github", "TrentMick")
#---- primary functionality
defshadow_issues(gc_proj, gh_proj):
print"# Gathering code.google.com/p/%s issues."%gc_proj
gc_issues=_get_gc_issues(gc_proj)
ifnotgc_issues:
print"No code.google.com/p/%s issues found. Nothing to do."%gc_proj
#pprint(gc_issues)
print"# Gathering any github.com/%s issues."%gh_proj
gh_issues=_get_gh_issues(gh_proj)
# For testing, migrate just a particular issue.
#shadow_issue(gc_proj, gc_issues[6], gh_proj, gh_issues, force=True)
#return
# Create a GH shadow issue for each GC issue that we haven't done already.
# - Warn (and offer to abort) if there are already issues in the GH project
# that are in the way.
fori, gc_issueinenumerate(gc_issues):
try:
shadow_issue(gc_proj, gc_issue, gh_proj, gh_issues)
exceptRuntimeErrorase:
printe
defshadow_issue(gc_proj, gc_issue, gh_proj, gh_issues, force=False):
"""
Side-effect: this extends `gh_issues` if an issue is successfully added.
@param force {bool} If true, this will create a shadow issue even if the
Google Code and Github issue numbers don't match.
"""
id=int(gc_issue["id"])
gh_issue= [iforiingh_issuesifi["number"] ==id] ifgh_issueselseNone
gh_new_id= ((gh_issues[-1]["number"] +1) ifgh_issueselse1)
print"Migrating issue %s."%id
print" from: http://code.google.com/p/%s/issues/detail?id=%s"% (gc_proj, id)
print" to: https://github.com/%s/issues/%s"% (gh_proj, gh_new_id)
#TODO: make this guard skip if title.startswith("[shadow]"), ie a previous
# run, but error out otherwise.
ifnotforceandid!=gh_new_id:
print" WARNING: github issue id would not match, skipping"
return
#pprint(gc_issue)
title="%s [moved]"%gc_issue["title"]
extra=""
ifgc_issue["state"] =="closed":
extra+=" Closed (%s)."%gc_issue["status"]
if"labels"ingc_issue:
extra+="\n\nOriginal labels: %s"%", ".join(gc_issue["labels"])
body=u"""\
This is [Issue %s](%s) moved from a Google Code project.
Added by %s by [%s](http://code.google.com%s).
Please review that bug for more context and additional comments, but update this bug.
%s
### Original description
%s
"""% (gc_issue["id"], gc_issue["url"],
gc_issue["published"], gc_issue["author"]["name"], gc_issue["author"]["uri"], extra,
# Indent to put as Markdown pre block (because Google Code issue content
# just isn't Markdown in general).
_indent(gc_issue["content"]))
#print "--"
#print title
#print
#print body
response, content=_github_api_post('/repos/%s/issues'%gh_proj,
{"title": title.encode('utf-8'), "body": body.encode('utf-8')})
ifresponse.statusnotin (201,):
raiseRuntimeError("unexpected response status from Github post "
"to create issue: %s\n%s\n%s"
% (response.status, response, content))
new_issue=json.loads(content)
assertnew_issue["number"] ==gh_new_id, (
"unexpected id for newly added github issue: expected %d, "
"got %d\n--\n%s"% (gh_new_id, new_issue["number"], new_issue))
ifgc_issue["state"] =="closed":
response, content=_github_api_patch(
"/repos/%s/issues/%s"% (gh_proj, new_issue["number"]),
{"state": "closed"})
ifresponse.statusnotin (200,):
raiseRuntimeError("unexpected response status from Github post "
"to close issue: %s\n%s\n%s"
% (response.status, response, content))
new_issue=json.loads(content)
gh_issues.append(new_issue)
returnnew_issue
#---- internal support stuff
def_get_http():
cache_dir=os.path.join(dirs.user_cache_dir, "httplib2")
ifnotos.path.exists(os.path.dirname(cache_dir)):
os.makedirs(os.path.dirname(cache_dir))
returnhttplib2.Http(cache_dir)
def_load_gitconfig(path):
fromConfigParserimportConfigParser
importtempfile
# Hack so ConfigParser can read a .gitconfig file (looser definition).
fd_path_hack, path_hack=tempfile.mkstemp()
content=open(path).read()
content=re.compile(r"^\s+", re.M).sub("", content)
f=os.fdopen(fd_path_hack, 'w')
f.write(content)
f.close()
config=ConfigParser()
config.read([path_hack])
os.remove(path_hack)
returnconfig
_github_auth_cache=None
def_get_github_auth():
fromos.pathimportexpanduser, exists
fromgetpassimportgetpass
global_github_auth_cache
if_github_auth_cacheisNone:
login=None
token=None
# If have them in .gitconfig (as per ngist), use that:
# git config --add github.user [github_username]
# git config --add github.token [github_api_token]
path=expanduser("~/.gitconfig")
ifexists(path):
config=_load_gitconfig(path)
ifconfig.has_option("github", "user"):
login=config.get("github", "user")
ifconfig.has_option("github", "token"):
token=config.get("github", "token")
ifnotlogin:
login=raw_input("Github username: ")
ifnottoken:
token=getpass("Github OAuth access token (see http://developer.github.com/v3/oauth/#create-a-new-authorization>): ")
ifnotloginornottoken:
raiseRuntimeError("couldn't get github auth info")
_github_auth_cache= (login, token)
return_github_auth_cache
def_github_api_post(path, params=None):
fromurllibimporturlencode
importtime
# Hack wait to avoid hitting Github's 60 req/minute rate limiting.
time.sleep(1)
http=_get_http()
url='https://api.github.com'+path
login, token=_get_github_auth()
ifparamsisNone:
params= {}
returnhttp.request(url+'?access_token='+token, "POST", json.dumps(params))
def_github_api_patch(path, params=None):
fromurllibimporturlencode
importtime
# Hack wait to avoid hitting Github's 60 req/minute rate limiting.
time.sleep(1)
http=_get_http()
url='https://api.github.com'+path
login, token=_get_github_auth()
ifparamsisNone:
params= {}
returnhttp.request(url+'?access_token='+token, "PATCH", json.dumps(params))
def_get_gh_issues(gh_proj):
"""Get the issues for the given github project (only support public
projects).
<http://develop.github.com/p/issues.html>
"""
issues= []
forstatein ("open", "closed"):
http=_get_http()
url='https://api.github.com/repos/%s/issues?state=%s'% (gh_proj, state)
response, content=http.request(url)
ifresponse["status"] notin ("200", "304"):
raiseRuntimeError("error GET'ing %s: %s"% (url, response["status"]))
issues+=json.loads(content)
issues.sort(key=operator.itemgetter("number"))
returnissues
def_get_gc_issues(gc_proj):
"""Get the Google Code issues XML for the given project.
<http://code.google.com/p/support/wiki/IssueTrackerAPI>
"""
http=_get_http()
max_results=1000
url= ("https://code.google.com/feeds/issues/p/%s/"
"issues/full?max-results=%d"% (gc_proj, max_results))
response, content=http.request(url)
ifresponse["status"] notin ("200", "304"):
raiseRuntimeError("error GET'ing %s: %s"% (url, response["status"]))
feed=ET.fromstring(content)
ns='{http://www.w3.org/2005/Atom}'
ns_issues='{http://schemas.google.com/projecthosting/issues/2009}'
issues= []
forentryinfeed.findall(ns+"entry"):
alt_link= [linkforlinkinentry.findall(ns+"link") iflink.get("rel") =="alternate"][0]
issue= {
"title": html_unescape(entry.findtext(ns+"title")),
"published": entry.findtext(ns+"published"),
"updated": entry.findtext(ns+"updated"),
"content": html_unescape(entry.findtext(ns+"content")),
"id": entry.findtext(ns_issues+"id"),
"url": alt_link.get("href"),
"stars": entry.findtext(ns_issues+"stars"),
"state": entry.findtext(ns_issues+"state"),
"status": entry.findtext(ns_issues+"status"),
"labels": [label.textforlabelinentry.findall(ns_issues+"label")],
"author": {
"name": entry.find(ns+"author").findtext(ns+"name"),
"uri": entry.find(ns+"author").findtext(ns+"uri"),
},
#TODO: closedDate if exists
# <issues:closedDate>2007-11-09T05:15:25.000Z</issues:closedDate>
}
#pprint(issue)
owner=entry.find(ns_issues+"owner")
ifownerisnotNone:
issue["owner"] = {
"username": entry.find(ns_issues+"owner").findtext(ns_issues+"username"),
"uri": entry.find(ns_issues+"owner").findtext(ns_issues+"uri"),
}
issue["published_datetime"] =datetime.datetime.strptime(
issue["published"], "%Y-%m-%dT%H:%M:%S.000Z")
issue["updated_datetime"] =datetime.datetime.strptime(
issue["updated"], "%Y-%m-%dT%H:%M:%S.000Z")
# Only care about open issues.
issues.append(issue)
#pprint(issues)
iflen(issues) ==max_results:
raiseRuntimeError("This project might have more than %d issues and "
"this script isn't equipped to deal with that. Aborting."
%max_results)
returnissues
deflog(s):
sys.stderr.write(s+"\n")
def_indent(text):
return' '+'\n '.join(text.splitlines(False))
def_gh_page_name_from_gc_page_name(gc):
"""Github (gh) Wiki page name from Google Code (gc) Wiki page name."""
gh=re.sub(r'([A-Z][a-z]+)', r'-\1', gc)[1:]
returngh
#---- mainline
defmain(argv=sys.argv):
iflen(argv) !=3:
log("error: incorrect usage")
log(__doc__)
return1
shadow_issues(argv[1], argv[2])
if__name__=='__main__':
sys.exit(main(sys.argv))