##// END OF EJS Templates
convert/mtn: add support for using monotone's "automate stdio" when available...
Daniel Atallah -
r13760:ed97955e default
parent child Browse files
Show More
@@ -1,227 +1,361
1 # monotone.py - monotone support for the convert extension
1 # monotone.py - monotone support for the convert extension
2 #
2 #
3 # Copyright 2008, 2009 Mikkel Fahnoe Jorgensen <mikkel@dvide.com> and
3 # Copyright 2008, 2009 Mikkel Fahnoe Jorgensen <mikkel@dvide.com> and
4 # others
4 # others
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 import os, re
9 import os, re
10 from mercurial import util
10 from mercurial import util
11 from common import NoRepo, commit, converter_source, checktool
11 from common import NoRepo, commit, converter_source, checktool
12 from common import commandline
12 from common import commandline
13 from mercurial.i18n import _
13 from mercurial.i18n import _
14
14
15 class monotone_source(converter_source, commandline):
15 class monotone_source(converter_source, commandline):
16 def __init__(self, ui, path=None, rev=None):
16 def __init__(self, ui, path=None, rev=None):
17 converter_source.__init__(self, ui, path, rev)
17 converter_source.__init__(self, ui, path, rev)
18 commandline.__init__(self, ui, 'mtn')
18 commandline.__init__(self, ui, 'mtn')
19
19
20 self.ui = ui
20 self.ui = ui
21 self.path = path
21 self.path = path
22 self.automatestdio = False
22
23
23 norepo = NoRepo(_("%s does not look like a monotone repository")
24 norepo = NoRepo(_("%s does not look like a monotone repository")
24 % path)
25 % path)
25 if not os.path.exists(os.path.join(path, '_MTN')):
26 if not os.path.exists(os.path.join(path, '_MTN')):
26 # Could be a monotone repository (SQLite db file)
27 # Could be a monotone repository (SQLite db file)
27 try:
28 try:
28 header = file(path, 'rb').read(16)
29 header = file(path, 'rb').read(16)
29 except:
30 except:
30 header = ''
31 header = ''
31 if header != 'SQLite format 3\x00':
32 if header != 'SQLite format 3\x00':
32 raise norepo
33 raise norepo
33
34
34 # regular expressions for parsing monotone output
35 # regular expressions for parsing monotone output
35 space = r'\s*'
36 space = r'\s*'
36 name = r'\s+"((?:\\"|[^"])*)"\s*'
37 name = r'\s+"((?:\\"|[^"])*)"\s*'
37 value = name
38 value = name
38 revision = r'\s+\[(\w+)\]\s*'
39 revision = r'\s+\[(\w+)\]\s*'
39 lines = r'(?:.|\n)+'
40 lines = r'(?:.|\n)+'
40
41
41 self.dir_re = re.compile(space + "dir" + name)
42 self.dir_re = re.compile(space + "dir" + name)
42 self.file_re = re.compile(space + "file" + name +
43 self.file_re = re.compile(space + "file" + name +
43 "content" + revision)
44 "content" + revision)
44 self.add_file_re = re.compile(space + "add_file" + name +
45 self.add_file_re = re.compile(space + "add_file" + name +
45 "content" + revision)
46 "content" + revision)
46 self.patch_re = re.compile(space + "patch" + name +
47 self.patch_re = re.compile(space + "patch" + name +
47 "from" + revision + "to" + revision)
48 "from" + revision + "to" + revision)
48 self.rename_re = re.compile(space + "rename" + name + "to" + name)
49 self.rename_re = re.compile(space + "rename" + name + "to" + name)
49 self.delete_re = re.compile(space + "delete" + name)
50 self.delete_re = re.compile(space + "delete" + name)
50 self.tag_re = re.compile(space + "tag" + name + "revision" +
51 self.tag_re = re.compile(space + "tag" + name + "revision" +
51 revision)
52 revision)
52 self.cert_re = re.compile(lines + space + "name" + name +
53 self.cert_re = re.compile(lines + space + "name" + name +
53 "value" + value)
54 "value" + value)
54
55
55 attr = space + "file" + lines + space + "attr" + space
56 attr = space + "file" + lines + space + "attr" + space
56 self.attr_execute_re = re.compile(attr + '"mtn:execute"' +
57 self.attr_execute_re = re.compile(attr + '"mtn:execute"' +
57 space + '"true"')
58 space + '"true"')
58
59
59 # cached data
60 # cached data
60 self.manifest_rev = None
61 self.manifest_rev = None
61 self.manifest = None
62 self.manifest = None
62 self.files = None
63 self.files = None
63 self.dirs = None
64 self.dirs = None
64
65
65 checktool('mtn', abort=False)
66 checktool('mtn', abort=False)
66
67
67 # test if there are any revisions
68 # test if there are any revisions
68 self.rev = None
69 self.rev = None
69 try:
70 try:
70 self.getheads()
71 self.getheads()
71 except:
72 except:
72 raise norepo
73 raise norepo
73 self.rev = rev
74 self.rev = rev
74
75
75 def mtnrun(self, *args, **kwargs):
76 def mtnrun(self, *args, **kwargs):
77 if self.automatestdio:
78 return self.mtnrunstdio(*args, **kwargs)
79 else:
80 return self.mtnrunsingle(*args, **kwargs)
81
82 def mtnrunsingle(self, *args, **kwargs):
76 kwargs['d'] = self.path
83 kwargs['d'] = self.path
77 return self.run0('automate', *args, **kwargs)
84 return self.run0('automate', *args, **kwargs)
78
85
86 def mtnrunstdio(self, *args, **kwargs):
87 # Prepare the command in automate stdio format
88 command = []
89 for k, v in kwargs.iteritems():
90 command.append("%s:%s" % (len(k), k))
91 if v:
92 command.append("%s:%s" % (len(v), v))
93 if command:
94 command.insert(0, 'o')
95 command.append('e')
96
97 command.append('l')
98 for arg in args:
99 command += "%s:%s" % (len(arg), arg)
100 command.append('e')
101 command = ''.join(command)
102
103 self.ui.debug("mtn: sending '%s'\n" % command)
104 self.mtnwritefp.write(command)
105 self.mtnwritefp.flush()
106
107 return self.mtnstdioreadcommandoutput(command)
108
109 def mtnstdioreadpacket(self):
110 read = None
111 commandnbr = ''
112 while read != ':':
113 read = self.mtnreadfp.read(1)
114 if not read:
115 raise util.Abort(_('bad mtn packet - no end of commandnbr'))
116 commandnbr += read
117 commandnbr = commandnbr[:-1]
118
119 stream = self.mtnreadfp.read(1)
120 if stream not in 'mewptl':
121 raise util.Abort(_('bad mtn packet - bad stream type %s' % stream))
122
123 read = self.mtnreadfp.read(1)
124 if read != ':':
125 raise util.Abort(_('bad mtn packet - no divider before size'))
126
127 read = None
128 lengthstr = ''
129 while read != ':':
130 read = self.mtnreadfp.read(1)
131 if not read:
132 raise util.Abort(_('bad mtn packet - no end of packet size'))
133 lengthstr += read
134 try:
135 length = long(lengthstr[:-1])
136 except TypeError:
137 raise util.Abort(_('bad mtn packet - bad packet size %s')
138 % lengthstr)
139
140 read = self.mtnreadfp.read(length)
141 if len(read) != length:
142 raise util.Abort(_("bad mtn packet - unable to read full packet "
143 "read %s of %s") % (len(read), length))
144
145 return (commandnbr, stream, length, read)
146
147 def mtnstdioreadcommandoutput(self, command):
148 retval = ''
149 while True:
150 commandnbr, stream, length, output = self.mtnstdioreadpacket()
151 self.ui.debug('mtn: read packet %s:%s:%s\n' %
152 (commandnbr, stream, length))
153
154 if stream == 'l':
155 # End of command
156 if output != '0':
157 raise util.Abort(_("mtn command '%s' returned %s") %
158 (command, output))
159 break
160 elif stream in 'ew':
161 # Error, warning output
162 self.ui.warn(_('%s error:\n') % self.command)
163 self.ui.warn(output)
164 elif stream == 'p':
165 # Progress messages
166 self.ui.debug('mtn: ' + output)
167 elif stream == 'm':
168 # Main stream - command output
169 retval = output
170
171 return retval
172
79 def mtnloadmanifest(self, rev):
173 def mtnloadmanifest(self, rev):
80 if self.manifest_rev == rev:
174 if self.manifest_rev == rev:
81 return
175 return
82 self.manifest = self.mtnrun("get_manifest_of", rev).split("\n\n")
176 self.manifest = self.mtnrun("get_manifest_of", rev).split("\n\n")
83 self.manifest_rev = rev
177 self.manifest_rev = rev
84 self.files = {}
178 self.files = {}
85 self.dirs = {}
179 self.dirs = {}
86
180
87 for e in self.manifest:
181 for e in self.manifest:
88 m = self.file_re.match(e)
182 m = self.file_re.match(e)
89 if m:
183 if m:
90 attr = ""
184 attr = ""
91 name = m.group(1)
185 name = m.group(1)
92 node = m.group(2)
186 node = m.group(2)
93 if self.attr_execute_re.match(e):
187 if self.attr_execute_re.match(e):
94 attr += "x"
188 attr += "x"
95 self.files[name] = (node, attr)
189 self.files[name] = (node, attr)
96 m = self.dir_re.match(e)
190 m = self.dir_re.match(e)
97 if m:
191 if m:
98 self.dirs[m.group(1)] = True
192 self.dirs[m.group(1)] = True
99
193
100 def mtnisfile(self, name, rev):
194 def mtnisfile(self, name, rev):
101 # a non-file could be a directory or a deleted or renamed file
195 # a non-file could be a directory or a deleted or renamed file
102 self.mtnloadmanifest(rev)
196 self.mtnloadmanifest(rev)
103 return name in self.files
197 return name in self.files
104
198
105 def mtnisdir(self, name, rev):
199 def mtnisdir(self, name, rev):
106 self.mtnloadmanifest(rev)
200 self.mtnloadmanifest(rev)
107 return name in self.dirs
201 return name in self.dirs
108
202
109 def mtngetcerts(self, rev):
203 def mtngetcerts(self, rev):
110 certs = {"author":"<missing>", "date":"<missing>",
204 certs = {"author":"<missing>", "date":"<missing>",
111 "changelog":"<missing>", "branch":"<missing>"}
205 "changelog":"<missing>", "branch":"<missing>"}
112 certlist = self.mtnrun("certs", rev)
206 certlist = self.mtnrun("certs", rev)
113 # mtn < 0.45:
207 # mtn < 0.45:
114 # key "test@selenic.com"
208 # key "test@selenic.com"
115 # mtn >= 0.45:
209 # mtn >= 0.45:
116 # key [ff58a7ffb771907c4ff68995eada1c4da068d328]
210 # key [ff58a7ffb771907c4ff68995eada1c4da068d328]
117 certlist = re.split('\n\n key ["\[]', certlist)
211 certlist = re.split('\n\n key ["\[]', certlist)
118 for e in certlist:
212 for e in certlist:
119 m = self.cert_re.match(e)
213 m = self.cert_re.match(e)
120 if m:
214 if m:
121 name, value = m.groups()
215 name, value = m.groups()
122 value = value.replace(r'\"', '"')
216 value = value.replace(r'\"', '"')
123 value = value.replace(r'\\', '\\')
217 value = value.replace(r'\\', '\\')
124 certs[name] = value
218 certs[name] = value
125 # Monotone may have subsecond dates: 2005-02-05T09:39:12.364306
219 # Monotone may have subsecond dates: 2005-02-05T09:39:12.364306
126 # and all times are stored in UTC
220 # and all times are stored in UTC
127 certs["date"] = certs["date"].split('.')[0] + " UTC"
221 certs["date"] = certs["date"].split('.')[0] + " UTC"
128 return certs
222 return certs
129
223
130 # implement the converter_source interface:
224 # implement the converter_source interface:
131
225
132 def getheads(self):
226 def getheads(self):
133 if not self.rev:
227 if not self.rev:
134 return self.mtnrun("leaves").splitlines()
228 return self.mtnrun("leaves").splitlines()
135 else:
229 else:
136 return [self.rev]
230 return [self.rev]
137
231
138 def getchanges(self, rev):
232 def getchanges(self, rev):
139 #revision = self.mtncmd("get_revision %s" % rev).split("\n\n")
233 #revision = self.mtncmd("get_revision %s" % rev).split("\n\n")
140 revision = self.mtnrun("get_revision", rev).split("\n\n")
234 revision = self.mtnrun("get_revision", rev).split("\n\n")
141 files = {}
235 files = {}
142 ignoremove = {}
236 ignoremove = {}
143 renameddirs = []
237 renameddirs = []
144 copies = {}
238 copies = {}
145 for e in revision:
239 for e in revision:
146 m = self.add_file_re.match(e)
240 m = self.add_file_re.match(e)
147 if m:
241 if m:
148 files[m.group(1)] = rev
242 files[m.group(1)] = rev
149 ignoremove[m.group(1)] = rev
243 ignoremove[m.group(1)] = rev
150 m = self.patch_re.match(e)
244 m = self.patch_re.match(e)
151 if m:
245 if m:
152 files[m.group(1)] = rev
246 files[m.group(1)] = rev
153 # Delete/rename is handled later when the convert engine
247 # Delete/rename is handled later when the convert engine
154 # discovers an IOError exception from getfile,
248 # discovers an IOError exception from getfile,
155 # but only if we add the "from" file to the list of changes.
249 # but only if we add the "from" file to the list of changes.
156 m = self.delete_re.match(e)
250 m = self.delete_re.match(e)
157 if m:
251 if m:
158 files[m.group(1)] = rev
252 files[m.group(1)] = rev
159 m = self.rename_re.match(e)
253 m = self.rename_re.match(e)
160 if m:
254 if m:
161 toname = m.group(2)
255 toname = m.group(2)
162 fromname = m.group(1)
256 fromname = m.group(1)
163 if self.mtnisfile(toname, rev):
257 if self.mtnisfile(toname, rev):
164 ignoremove[toname] = 1
258 ignoremove[toname] = 1
165 copies[toname] = fromname
259 copies[toname] = fromname
166 files[toname] = rev
260 files[toname] = rev
167 files[fromname] = rev
261 files[fromname] = rev
168 elif self.mtnisdir(toname, rev):
262 elif self.mtnisdir(toname, rev):
169 renameddirs.append((fromname, toname))
263 renameddirs.append((fromname, toname))
170
264
171 # Directory renames can be handled only once we have recorded
265 # Directory renames can be handled only once we have recorded
172 # all new files
266 # all new files
173 for fromdir, todir in renameddirs:
267 for fromdir, todir in renameddirs:
174 renamed = {}
268 renamed = {}
175 for tofile in self.files:
269 for tofile in self.files:
176 if tofile in ignoremove:
270 if tofile in ignoremove:
177 continue
271 continue
178 if tofile.startswith(todir + '/'):
272 if tofile.startswith(todir + '/'):
179 renamed[tofile] = fromdir + tofile[len(todir):]
273 renamed[tofile] = fromdir + tofile[len(todir):]
180 # Avoid chained moves like:
274 # Avoid chained moves like:
181 # d1(/a) => d3/d1(/a)
275 # d1(/a) => d3/d1(/a)
182 # d2 => d3
276 # d2 => d3
183 ignoremove[tofile] = 1
277 ignoremove[tofile] = 1
184 for tofile, fromfile in renamed.items():
278 for tofile, fromfile in renamed.items():
185 self.ui.debug (_("copying file in renamed directory "
279 self.ui.debug (_("copying file in renamed directory "
186 "from '%s' to '%s'")
280 "from '%s' to '%s'")
187 % (fromfile, tofile), '\n')
281 % (fromfile, tofile), '\n')
188 files[tofile] = rev
282 files[tofile] = rev
189 copies[tofile] = fromfile
283 copies[tofile] = fromfile
190 for fromfile in renamed.values():
284 for fromfile in renamed.values():
191 files[fromfile] = rev
285 files[fromfile] = rev
192
286
193 return (files.items(), copies)
287 return (files.items(), copies)
194
288
195 def getfile(self, name, rev):
289 def getfile(self, name, rev):
196 if not self.mtnisfile(name, rev):
290 if not self.mtnisfile(name, rev):
197 raise IOError() # file was deleted or renamed
291 raise IOError() # file was deleted or renamed
198 try:
292 try:
199 data = self.mtnrun("get_file_of", name, r=rev)
293 data = self.mtnrun("get_file_of", name, r=rev)
200 except:
294 except:
201 raise IOError() # file was deleted or renamed
295 raise IOError() # file was deleted or renamed
202 self.mtnloadmanifest(rev)
296 self.mtnloadmanifest(rev)
203 node, attr = self.files.get(name, (None, ""))
297 node, attr = self.files.get(name, (None, ""))
204 return data, attr
298 return data, attr
205
299
206 def getcommit(self, rev):
300 def getcommit(self, rev):
207 certs = self.mtngetcerts(rev)
301 certs = self.mtngetcerts(rev)
208 return commit(
302 return commit(
209 author=certs["author"],
303 author=certs["author"],
210 date=util.datestr(util.strdate(certs["date"], "%Y-%m-%dT%H:%M:%S")),
304 date=util.datestr(util.strdate(certs["date"], "%Y-%m-%dT%H:%M:%S")),
211 desc=certs["changelog"],
305 desc=certs["changelog"],
212 rev=rev,
306 rev=rev,
213 parents=self.mtnrun("parents", rev).splitlines(),
307 parents=self.mtnrun("parents", rev).splitlines(),
214 branch=certs["branch"])
308 branch=certs["branch"])
215
309
216 def gettags(self):
310 def gettags(self):
217 tags = {}
311 tags = {}
218 for e in self.mtnrun("tags").split("\n\n"):
312 for e in self.mtnrun("tags").split("\n\n"):
219 m = self.tag_re.match(e)
313 m = self.tag_re.match(e)
220 if m:
314 if m:
221 tags[m.group(1)] = m.group(2)
315 tags[m.group(1)] = m.group(2)
222 return tags
316 return tags
223
317
224 def getchangedfiles(self, rev, i):
318 def getchangedfiles(self, rev, i):
225 # This function is only needed to support --filemap
319 # This function is only needed to support --filemap
226 # ... and we don't support that
320 # ... and we don't support that
227 raise NotImplementedError()
321 raise NotImplementedError()
322
323 def before(self):
324 # Check if we have a new enough version to use automate stdio
325 version = 0.0
326 try:
327 versionstr = self.mtnrunsingle("interface_version")
328 version = float(versionstr)
329 except Exception:
330 raise util.Abort(_("unable to determine mtn automate interface "
331 "version"))
332
333 if version >= 12.0:
334 self.automatestdio = True
335 self.ui.debug("mtn automate version %s - using automate stdio\n" %
336 version)
337
338 # launch the long-running automate stdio process
339 self.mtnwritefp, self.mtnreadfp = self._run2('automate', 'stdio',
340 '-d', self.path)
341 # read the headers
342 read = self.mtnreadfp.readline()
343 if read != 'format-version: 2\n':
344 raise util.Abort(_('mtn automate stdio header unexpected: %s')
345 % read)
346 while read != '\n':
347 read = self.mtnreadfp.readline()
348 if not read:
349 raise util.Abort(_("failed to reach end of mtn automate "
350 "stdio headers"))
351 else:
352 self.ui.debug("mtn automate version %s - not using automate stdio "
353 "(automate >= 12.0 - mtn >= 0.46 is needed)\n" % version)
354
355 def after(self):
356 if self.automatestdio:
357 self.mtnwritefp.close()
358 self.mtnwritefp = None
359 self.mtnreadfp.close()
360 self.mtnreadfp = None
361
General Comments 0
You need to be logged in to leave comments. Login now