Debian Codegraph @

hgext/convert/monotone.py

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