forked from swenson/sagewiki
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmoin2git
executable file
·410 lines (360 loc) · 17.7 KB
/
moin2git
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright 2014 Christopher Swenson ([email protected])
# Copyright 2013 Antoine Beaupré ([email protected])
# Copyright 2012 Josh Triplett ([email protected])
# I'm a Moin, but I can change. If I have to. I guess.
import sys
import re
import os
import os.path
import urllib
import hashlib
import resource
sys.path.append('.')
from time import time as timestamp
from MoinMoin.logfile.editlog import EditLog
from MoinMoin.action import AttachFile
from MoinMoin.user import User
from MoinMoin.Page import Page
from MoinMoin.script import MoinScript
from MoinMoin.script import log
keep_attachments = True
filename_re = """\([0-9a-fA-F]+\)"""
def fix_filename(f):
def replace(x):
chars = x.group(0)[1:-1]
r = ''
for i in xrange(0, len(chars), 2):
r += chr(int(chars[i:i + 2], 16))
return r
return re.sub(filename_re, replace, f).decode('utf-8')
def page_exists(fname):
if os.path.exists(os.path.join("data", "pages", fname, "current")):
current = open(os.path.join("data", "pages", fname, "current")).read().strip()
if os.path.exists(os.path.join("data", "pages", fname, "revisions", current)):
return True
return False
sys.path.insert(0, '.')
commits = {}
class IkiwikiMigScript(MoinScript):
"""\
Purpose: Migrate from Moinmoin to Ikiwiki
=========================================
Usage: moin2git2 [ -p page ] | ( cd repo.git ; git fast-import )
This script works in two passes:
1. inspect every page's history individually and:
* create a git "blob" for every version and attachment
* generate a list of commits for later
2. write the actual commits, in order
This is because the general edit-log is too difficult to parse and
that we cannot know the global order of commits in the page only.
This all means that this script could use a significant amount of
memory, mostly proportionnal on the number of commits and size of
commitlogs, but not on size of pages and attachments.
For a 10 000 pages wiki (1.7GB) and 74 000 changes (9MB of global edit
log), memory usage reached 200M (VSS). The data output was 1.3GB and
produced in about 10 minutes on a Intel 5600 CPU. Most of the time is
spent in I/O.
By default the script pipes git-fast-import(1) format to stdout, but
it can also take an argument to write the dump to a file.
Note that git fast-import can rerun on the same repository, so this
can do incremental imports, although this has not been tested
extensively.
This script does not write to the original MoinMoin wiki."""
hex_escape_re = re.compile(r'\(([0-9A-Fa-f]+)\)')
commits = dict()
renames = dict()
# caches and counters, used to track the import progress
commitcount = 0
totalcommitcount = 0
pagecount = 0
totalpagecount = 0
def __init__(self, argv=None):
MoinScript.__init__(self, argv)
self.parser.remove_option('--page')
self.parser.add_option(
'-p', '--page', dest="page", default=[], action='append',
help="wiki page name, can be used multiple times [default: all pages]"
)
self.parser.add_option('--timezone', dest="timezone", default="+0000",
help="timezone the server time was set at [default: UTC]")
self.parser.add_option(
'-d', '--debug', dest="debug", default=False, action='store_true',
help="enable debugging, can generate a lot of output"
)
self.parser.add_option(
'-u', '--underlay', dest="underlay", default=False, action='store_true',
help="import the MoinMoin underlay too"
)
self.parser.add_option(
'-D', '--deleted', dest="deleted", default=False, action='store_true',
help="include deleted pages [default: no]"
)
self.parser.add_option(
'--authors', dest="authorsfile", default=None,
help="a list of 'username=Author <email>' mappings to convert MoinMoin authors to email addresses")
self.parser.add_option(
'-b', '--branch', dest="branch", default='refs/heads/master',
help="the branch to attach the commits to [default: refs/heads/master]")
def mainloop(self, authorsfile=None):
self.init_request()
self.authors = {}
if len(self.args) < 1 or self.args[0] == '-':
self.output = sys.stdout
else:
self.output = open(self.args[0], 'wb')
if self.options.authorsfile is not None:
for line in file(self.options.authorsfile):
username, author = line.split('=', 1)
name, email = author.rsplit(" ", 1)
self.authors[username] = name, email
if self.options.page:
self.options.page = map(lambda x: x.decode('utf-8'), self.options.page)
else:
log("loading full page list")
self.options.page = self.request.rootpage.getPageList(user='', exists=not self.options.deleted,
include_underlay=self.options.underlay)
log("Loaded %s initial pages" % len(self.options.page))
for fname in os.listdir("data/pages"):
if page_exists(fname):
page = fix_filename(fname)
self.options.page.append(page)
self.options.page = sorted(set(self.options.page))
log("Found %s total pages" % len(self.options.page))
log("MyStartingPage: %s" % ('MyStartingPage' in self.options.page))
# first pass: create the blobs and the self.commits structure
self.totalpagecount = len(self.options.page)
for page in self.options.page:
self.createblobs(page)
log('') # add a newline because the progress indicator won't
# second pass: order the self.commits structure and creates the commits
self.files_present = set()
self.renamed_from = {}
self.totalcommitcount = len(self.commits)
log("generating branch of %d commits" % self.totalcommitcount)
for time in sorted(self.commits.keys()):
self.createcommit(self.commits[time])
log('')
def createcommit(self, commit):
"""
This will write to self.output a fast-import compatible for this commit.
commit is a dictionnary with those fields:
committer: a name, email tuple
comment: the commitlog (optional)
blob: a dict of sha1 -> filename mappings (optional)
rename: a tuple (from -> to) (optional)
delete: a file name to delete (optional)
"""
self.commitcount += 1
sys.stderr.write("\rcommit: %d/%d" % (self.commitcount, self.totalcommitcount))
if self.options.debug: log("\ncommit mark %d: %s" % (self.commitcount, repr(commit)))
time = commit['time']
out = "commit %s\n" % self.options.branch
# commits are marked individually
# eases debugging between the dump and the debugging output
out += "mark :%d\n" % self.commitcount
if 'committer' in commit:
name, email = commit['committer']
else:
name, email = ("moin2git", "moin2git")
out += "committer %s <%s> %d %s\n" % (name, email, time, self.options.timezone)
out += "data <<EOF\n"
if 'comment' in commit:
out += commit['comment']
elif 'blob' in commit:
for sha1, fname in commit['blob'].iteritems():
if sha1 in commits:
out += "File %s, revision %d" % (fname, commits[sha1])
else:
out += "Change to file %s" % (fname,)
out += "\nEOF\n"
if 'blob' in commit:
for blob, basename in commit['blob'].iteritems():
out += "M 644 %s \"%s\"\n" % (blob, basename.replace(' ', '_'))
self.files_present.add(basename.replace(' ', '_'))
#log("\nUpdating file %s" % (basename.replace(' ', '_')))
if 'rename' in commit:
old, new = commit['rename']
# if new in self.renames:
# if self.options.debug: log("removing rename target %s" % new)
# del self.renames[new] # we have a target again, bring it back
# check if the original page really really exists
o = old
while o in self.renamed_from:
o = self.renamed_from[o]
self.files_present.add(new)
if o.replace(' ', '_') not in self.files_present:
log("\nInvalid rename: %s -> %s\n" % (o, new))
else:
#log("\nRename: %s -> ... -> %s -> %s\n" % (old, o, new))
self.files_present.remove(o.replace(' ', '_'))
self.files_present.add(new.replace(' ', '_'))
#if o == old:
self.renamed_from[new] = o
out += "R \"%s\" \"%s\"\n" % (o.replace(' ', '_'),
new.replace(' ', '_'))
# otherwise the page may have been renamed twice, try to find the original copy
# else:
# log("looked up replacement for old %s, it's %s, renaming to %s" % (old, o, new))
# out += "C \"%s\" \"%s\"\n" % (o.replace(' ', '_'), new.replace(' ', '_'))
if self.options.debug: log("renames: " + repr(self.renames))
if 'delete' in commit:
if commit['delete'].replace(' ', '_') in self.files_present:
self.files_present.remove(commit['delete'].replace(' ', '_'))
out += "D \"%s\"\n" % commit['delete'].replace(' ', '_')
else:
pass
#log("\nNot sure about deleting file: %s" % commit['delete'].replace(' ', '_'))
out += "\n"
self.output.write(out)
def createblobs(self, page):
self.pagecount += 1
sys.stderr.write("\rprocessing page %d/%d" % (self.pagecount, self.totalpagecount));
r = self.request
editlog = EditLog(r, rootpagename=page)
time = 0
attachments = dict() # file -> commit mapping
previouspath = None
p = Page(r, page)
# we iterate over the page's edit-log because it's more reliable and consistent than the general log
for line in editlog:
filename, _, _ = p.get_rev(rev=long(line.rev))
filename = os.path.abspath(filename)
u = User(r, line.userid)
basename = self.translate(line.pagename)
# setup proper username <email> from user account, use IP <hostname> otherwise
if u.exists():
name, email = self.authors.get(u.name, (u.name, u.email))
else:
name, email = (line.addr, line.hostname)
time = line.ed_time_usecs / 10 ** 6
idx = "%d%s" % (time, basename)
if self.options.debug:
log("line: " + line.pagename + " rev: " + line.rev + " idx: " + repr(idx))
# why the fuck.
basename = basename.encode('utf-8')
oldextra = line.extra
line.extra = line.extra.encode('utf-8')
# internal commit object
# this object will get added to the self.commits list of commits if relevant, below
commit = {
'time': time,
'committer': (name.encode('utf-8'), email.encode('utf-8'))
}
if len(line.comment) > 0: commit['comment'] = line.comment.encode('utf-8')
# old-style renames
if line.action == 'SAVENEW' and long(
line.rev) > 1 and previouspath != basename and previouspath is not None:
commit['rename'] = (previouspath + ".md", basename + ".md")
self.commits[idx] = commit
if self.options.debug: log(
"rename %s -> %s in %s" % (previouspath.decode('utf-8'), basename.decode('utf-8'), idx))
# new renames
elif line.action == 'SAVE/RENAME':
commit['rename'] = (line.extra + ".md", basename + ".md")
self.commits[idx] = commit
if self.options.debug: log(
"rename %s -> %s in %s" % (line.extra.decode('utf-8'), basename.decode('utf-8'), idx))
# just a new version, but may be a delete
elif line.action in ['SAVENEW', 'SAVE', 'SAVE/REVERT']:
blob = "blob\n"
try:
data = file(filename).read()
blob += "data %d\n" % len(data)
blob += data
if not 'blob' in commit: commit['blob'] = dict()
sha1 = hashlib.sha1("blob %d\0%s" % (len(data), data)).hexdigest()
commits[sha1] = long(line.rev)
commit['blob'][sha1] = basename + ".md"
self.commits[idx] = commit
if self.options.debug: log("blob %s -> %s id: %s" % (sha1, commit['blob'][sha1], idx))
# we assume failure to load the file is because it's been deleted
except IOError as e:
log("\nError processing %s: %s\n" % (basename, e))
commit['delete'] = basename + ".md"
self.commits[idx] = commit
continue
blob += "\n"
self.output.write(blob)
elif line.action in ['ATTNEW'] and keep_attachments:
# keep the last commit for the attachment as the right one
# we are forced to do this because attachments are not versionned in MoinMoin
if self.options.debug: log(
"old extra %s unquoted %s final %s" % (repr(oldextra), repr(urllib.unquote(oldextra)), repr(f)))
# store related commit in attachment table for when we process that page's attachment blobs
# convert attachment filename from latin-1 to utf-8
attachments[urllib.unquote(oldextra).encode('latin1').decode('utf-8')] = commit
elif not line.action in ['ATTDRW', 'ATTDEL', 'ATTNEW']: # ignored actions
log("Unknown action: " + line.action)
previouspath = basename # keep track of the previous page name for old-style renames
# attachment handling
files = AttachFile._get_files(r, page)
if self.options.debug: log("attachment mapping: " + repr(attachments))
if (len(files) > 0):
if not time: time = timestamp()
for f in files:
commit = dict()
# this is temporary files like gallery
if f.startswith('tmp.thumbnail.') \
or f.startswith('tmp.webnail.') \
or f in ['delete.me.to.regenerate.thumbnails.and.webnails', 'tmp.writetest']:
if self.options.debug: log("skipping tmp. attachment: " + f)
continue
if f.endswith('.tdraw'):
log("skipping .tdraw attachment: " + f)
continue
idx = "%d%s" % (time, page)
filename = os.path.abspath(AttachFile.getFilename(r, page, f))
if not f in attachments:
# it could be that this side is latin-1 encoded, which happens for old attachments
# convert back into utf-8
f = f.encode('latin-1').decode('utf-8')
if f in attachments:
commit = attachments[f]
idx = "%d%s%s" % (commit['time'], page, 'attach')
if self.options.debug: log("reusing commit with id %s: %s" % (idx, repr(commit)))
try:
st = os.stat(filename)
if not 'time' in commit:
# this means the attachment wasn't found in that page's edit-log
# this can happen with old attachments, which were recorded only in the global log
# XXX: fix this, we could get the commit info from the global log now
commit['time'] = st.st_mtime
log("\ncould not find commit for attachment %s, using timestamp %d" % (repr(f), commit['time']))
data = file(filename).read()
blob = "blob\n"
blob += "data %d\n" % len(data)
blob += data
blob += "\n"
if not 'blob' in commit: commit['blob'] = dict()
sha1 = hashlib.sha1("blob %d\0%s" % (len(data), data)).hexdigest()
commit['blob'][sha1] = os.path.join(page.encode('utf-8'), os.path.basename(filename))
if self.options.debug: log("blob (attachment on %s) %s -> %s id: %s" % (
page, sha1, commit['blob'][sha1].decode('utf-8'), idx))
self.output.write(blob)
self.commits[idx] = commit
except OSError as (errno, strerror):
# no such file or directory means the attachment was deleted
# everything else should be raised as an exception
if errno != 2:
raise
def translate(self, s):
"""This function translates MoinMoin page escapes into a unicode string"""
def translate_one(match):
result = ""
num = match.group(1)
while len(num) >= 2:
result += chr(num[:2])
num = num[2:]
return result
return self.hex_escape_re.sub(translate_one, s)
def resourceusage():
u = resource.getrusage(resource.RUSAGE_SELF)
log("memory usage: %dKB" % (u.ru_maxrss))
if __name__ == '__main__':
resourceusage()
try:
i = IkiwikiMigScript().run()
finally:
resourceusage()