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
|
#!/usr/bin/env python
"""
darcs-fast-export - darcs backend for fast data exporters
Copyright (c) 2008 Miklos Vajna <vmiklos@frugalware.org>
Copyright (c) 2008 Matthias Andree <matthias.andree@gmx.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
"""
import sys
import os
import re
import time
import shutil
import optparse
import subprocess
class Handler:
def __init__(self):
self.marks = {}
self.files = []
self.prevfiles = None
self.ch = None
self.line = None
self.unread_line = False
self.eof = False
self.debug = False
self.export_marks = []
self.import_marks = []
def read_next_line(self):
if self.unread_line:
self.unread_line = False
return
self.line = ""
if self.eof:
return
if self.ch:
self.line += self.ch
self.ch = None
buf = sys.stdin.readline()
if not len(buf):
self.eof = True
else:
self.line += buf
if self.debug:
print "read_next_line: '%s'" % self.line
def read(self, length):
buf = ""
if self.ch:
buf += self.ch
self.ch = None
buf += sys.stdin.read(length)
if self.debug:
print "read: '%s'" % buf
return buf
def skip_optional_lf(self):
self.ch = self.read(1)
if self.ch == "\n":
self.ch = None
def bug(self, s):
raise Exception(s)
def get_date(self, ts, tz):
# first fix the case when tz is higher than +1200, as
# darcs won't accept it
if int(tz[:3]) > 12:
ts = str(int(ts) + 60*60*24)
tz = str(int(tz[:3])-24) + tz[3:]
# int(ts) is seconds since epoch. Since we're trying to
# capture both the absolute time of the commit and the
# localtime in the timezone of the committer, we need to turn
# the (seconds-since-epoch, committer-timezone-offset) pair
# that we get from the git-fast-export stream format into a
# localized-time-plus-timezone-marker string that darcs will
# accept. Therefore, we parse the timezone-offset (which
# looks like +0500 or +0000 or -0730 or something) and add it
# to seconds-since-epoch before calling gmtime().
mo = re.search(r'^([\+\-])(\d\d)(\d\d)$', tz)
offset = 60*60*int(mo.group(2)) + 60*int(mo.group(3))
if mo.group(1) == "-":
offset = -offset
offset_time = int(ts) + offset
s = time.strftime("%a %b %d %H:%M:%S %Y", time.gmtime(offset_time))
items = s.split(' ')
return " ".join(items[:-1]) + " " + tz + " " + items[-1]
def handle_mark(self):
if self.line.startswith("mark :"):
self.mark_num = int(self.line[6:-1])
self.read_next_line()
def handle_data(self):
if not self.line.startswith("data "):
self.bug("Expected 'data n' command, found: '%s'" % self.line[:-1])
length = int(self.line[5:-1])
self.buf = self.read(length)
self.skip_optional_lf()
def handle_blob(self):
self.read_next_line()
self.handle_mark()
self.handle_data()
self.marks[self.mark_num] = self.buf
def handle_ident(self, s):
items = s.split(' ')
self.ident = " ".join(items[:-2])
self.date = self.get_date(items[-2], items[-1])
def handle_msg(self):
items = self.buf.split('\n')
self.short = items[0]
self.long = "\n".join(items[1:])
def handle_tag(self):
version = self.line[:-1].split(' ')[1]
self.read_next_line()
if self.line.startswith("from "):
self.read_next_line()
if self.line.startswith("tagger "):
self.handle_ident(self.line[7:-1])
self.read_next_line()
self.handle_data()
self.skip_optional_lf()
sock = subprocess.Popen(["darcs", "tag", "--pipe"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
buf = [self.date, self.ident, version]
sock.stdin.write("\n".join(buf))
sock.stdin.close()
self.log("Tagging %s:\n%s" % (version, sock.stdout.read()))
sock.stdout.close()
def handle_commit(self):
if not self.prevfiles and self.options.import_marks:
# first commit in an incremental continued
# import
for (root, dirs, files) in os.walk("."):
for i in files:
path = os.path.normpath(os.path.join(root, i))
if path.startswith("_darcs") or "-darcs-backup" in path:
continue
self.files.append(path)
self.prevfiles = self.files[:]
adds = []
self.read_next_line()
self.handle_mark()
if self.line.startswith("author "):
self.handle_ident(self.line[7:-1])
self.read_next_line()
if self.line.startswith("committer "):
self.handle_ident(self.line[10:-1])
self.read_next_line()
self.handle_data()
self.skip_optional_lf()
self.handle_msg()
self.read_next_line()
if self.line.startswith("from "):
self.read_next_line()
while self.line.startswith("merge "):
self.read_next_line()
while len(self.line) > 0:
if self.line.startswith("deleteall"):
path = self.line[2:-1]
for path in self.files:
os.unlink(path)
self.files = []
elif self.line.startswith("D "):
path = self.line[2:-1]
if os.path.exists(path):
os.unlink(path)
if path in self.files:
self.files.remove(path)
elif self.line.startswith("R "):
os.system("darcs mv %s" % self.line[2:])
elif self.line.startswith("C "):
src, dest = self.line[:-1].split(' ')[1:]
shutil.copy(src.strip('"'), dest.strip('"'))
os.system("darcs add %s" % dest)
elif self.line.startswith("M "):
items = self.line.split(' ')
path = items[3][:-1]
dir = os.path.split(path)[0]
if len(dir) and not os.path.exists(dir):
os.makedirs(dir)
sock = open(path, "w")
if items[2] != "inline":
idx = int(items[2][1:])
sock.write(self.marks[idx])
del self.marks[idx]
else:
self.read_next_line()
self.handle_data()
sock.write(self.buf)
sock.close()
if path not in self.prevfiles:
adds.append(path)
if path not in self.files:
self.files.append(path)
else:
self.unread_line = True
break
self.read_next_line()
if not len(self.line):
break
for i in adds:
os.system("darcs add %s" % i)
sock = subprocess.Popen(["darcs", "record", "--ignore-times", "-a", "--pipe"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
buf = [self.date, self.ident, self.short, self.long]
sock.stdin.write("\n".join(buf))
sock.stdin.close()
self.log("Recording :%s:\n%s" % (self.mark_num, sock.stdout.read()))
sock.stdout.close()
if self.options.export_marks:
# yeah, an xml parser would be better, but
# should we mess with encodings just because of
# this? i hope not
sock = os.popen("darcs changes --last=1 --xml", "r")
buf = sock.read()
sock.close()
hash = buf.split('\n')[1].split("'")[-2]
self.export_marks.append(":%s %s" % (self.mark_num, hash))
def handle_progress(self, s):
print "progress [%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), s.strip())
sys.stdout.flush()
def handle_opts(self):
# Option Parser
usage="%prog [options]"
opp = optparse.OptionParser(usage=usage)
opp.add_option("--import-marks", metavar="IFILE",
help="read state for incremental imports from IFILE")
opp.add_option("--export-marks", metavar="OFILE",
help="write state for incremental imports to OFILE")
opp.add_option("--logfile", metavar="L",
help="log file which contains the output of external programs invoked during the conversion")
(self.options, args) = opp.parse_args()
if self.options.logfile:
logfile = self.options.logfile
else:
logfile = "_darcs/import.log"
self.logsock = open(os.path.abspath(logfile), "a")
def log(self, s):
self.logsock.write("[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), s))
self.logsock.flush()
def handle_export_marks(self):
if self.options.export_marks:
sock = open(self.options.export_marks, 'w')
sock.write("\n".join(self.export_marks))
sock.write("\n")
sock.close()
def handle_import_marks(self):
if self.options.import_marks:
sock = open(self.options.import_marks)
for i in sock.readlines():
line = i.strip()
if not len(line):
continue
self.import_marks.append(line.split(' ')[1])
self.export_marks.append(line)
sock.close()
def handle(self):
self.handle_opts()
self.handle_import_marks()
while not self.eof:
self.read_next_line()
if not len(self.line[:-1]):
pass
elif self.line.startswith("blob"):
self.handle_blob()
elif self.line.startswith("commit"):
self.handle_commit()
elif self.line.startswith("tag"):
self.handle_tag()
elif self.line.startswith("reset"):
self.read_next_line()
if not self.line.startswith("from "):
self.unread_line = True
elif self.line.startswith("checkpoint"):
pass
elif self.line.startswith("progress"):
self.handle_progress(self.line[9:])
else:
self.bug("'%s': invalid command" % self.line[:-1])
self.handle_export_marks()
if __name__ == "__main__":
h = Handler()
h.handle()
|