Debian Codegraph @

hgext/convert/common.py

raw ◀ ▶
1 Debian patch touch this file
1 # common.py - common code for the convert extension
2 #
3 # Copyright 2005-2009 Olivia Mackall <[email protected]> and others
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 from __future__ import annotations
9
10 import base64
11 import os
12 import pickle
13 import re
14 import shlex
15 import subprocess
16 import typing
17
18 from typing import (
19 Any,
20 AnyStr,
21 )
22
23 from mercurial.i18n import _
24 from mercurial import (
25 encoding,
26 error,
27 phases,
28 pycompat,
29 util,
30 )
31 from mercurial.utils import (
32 dateutil,
33 procutil,
34 )
35
36 if typing.TYPE_CHECKING:
37 from typing import (
38 overload,
39 )
40 from mercurial import (
41 ui as uimod,
42 )
43
44 propertycache = util.propertycache
45
46
47 if typing.TYPE_CHECKING:
48
49 @overload
50 def _encodeornone(d: str) -> bytes:
51 pass
52
53 @overload
54 def _encodeornone(d: None) -> None:
55 pass
56
57
58 def _encodeornone(d):
59 if d is None:
60 return
61 return d.encode('latin1')
62
63
64 class _shlexpy3proxy:
65 def __init__(self, l: shlex.shlex) -> None:
66 self._l = l
67
68 def __iter__(self):
69 return (_encodeornone(v) for v in self._l)
70
71 def get_token(self):
72 return _encodeornone(self._l.get_token())
73
74 @property
75 def infile(self) -> bytes:
76 if self._l.infile is not None:
77 return encoding.strtolocal(self._l.infile)
78 return b'<unknown>'
79
80 @property
81 def lineno(self) -> int:
82 return self._l.lineno
83
84
85 def shlexer(
86 data=None,
87 filepath: bytes | None = None,
88 wordchars: bytes | None = None,
89 whitespace: bytes | None = None,
90 ):
91 if data is None:
92 data = open(filepath, encoding='latin1')
93 else:
94 if filepath is not None:
95 raise error.ProgrammingError(
96 b'shlexer only accepts data or filepath, not both'
97 )
98 data = data.decode('latin1')
99 infile = encoding.strfromlocal(filepath) if filepath is not None else None
100 l = shlex.shlex(data, infile=infile, posix=True)
101 if whitespace is not None:
102 l.whitespace_split = True
103 l.whitespace += whitespace.decode('latin1')
104 if wordchars is not None:
105 l.wordchars += wordchars.decode('latin1')
106 return _shlexpy3proxy(l)
107
108
109 def encodeargs(args: Any) -> bytes:
110 def encodearg(s: bytes) -> bytes:
111 lines = base64.encodebytes(s)
112 lines = [l.splitlines()[0] for l in pycompat.iterbytestr(lines)]
113 return b''.join(lines)
114
115 s = pickle.dumps(args)
116 return encodearg(s)
117
118
119 def decodeargs(s: bytes) -> Any:
120 s = base64.decodebytes(s)
121 return pickle.loads(s)
122
123
124 class MissingTool(Exception):
125 pass
126
127
128 def checktool(
•129 exe: bytes, name: bytes | None = None, abort: bool = True, debname: bytes | None = None
130 ) -> None:
131 name = name or exe
132 if not procutil.findexe(exe):
133 if abort:
134 exc = error.Abort
135 else:
136 exc = MissingTool
•137 raise exc(_(b'cannot find required "%s" tool') % name +
138 (debname and _(b' (try installing the %s package)') % debname or b''))
139
140
141 class NoRepo(Exception):
142 pass
143
144
145 SKIPREV: bytes = b'SKIP'
146
147
148 class commit:
149 def __init__(
150 self,
151 author: bytes,
152 date: bytes,
153 desc: bytes,
154 parents,
155 branch: bytes | None = None,
156 rev=None,
157 extra=None,
158 sortkey=None,
159 saverev=True,
160 phase: int = phases.draft,
161 optparents=None,
162 ctx=None,
163 ) -> None:
164 self.author = author or b'unknown'
165 self.date = date or b'0 0'
166 self.desc = desc
167 self.parents = parents # will be converted and used as parents
168 self.optparents = optparents or [] # will be used if already converted
169 self.branch = branch
170 self.rev = rev
171 self.extra = extra or {}
172 self.sortkey = sortkey
173 self.saverev = saverev
174 self.phase = phase
175 self.ctx = ctx # for hg to hg conversions
176
177
178 class converter_source:
179 """Conversion source interface"""
180
181 def __init__(
182 self,
183 ui: uimod.ui,
184 repotype: bytes,
185 path: bytes | None = None,
186 revs=None,
187 ) -> None:
188 """Initialize conversion source (or raise NoRepo("message")
189 exception if path is not a valid repository)"""
190 self.ui = ui
191 self.path = path
192 self.revs = revs
193 self.repotype = repotype
194
195 self.encoding = b'utf-8'
196
197 def checkhexformat(
198 self, revstr: bytes, mapname: bytes = b'splicemap'
199 ) -> None:
200 """fails if revstr is not a 40 byte hex. mercurial and git both uses
201 such format for their revision numbering
202 """
203 if not re.match(br'[0-9a-fA-F]{40,40}$', revstr):
204 raise error.Abort(
205 _(b'%s entry %s is not a valid revision identifier')
206 % (mapname, revstr)
207 )
208
209 def before(self) -> None:
210 pass
211
212 def after(self) -> None:
213 pass
214
215 def targetfilebelongstosource(self, targetfilename):
216 """Returns true if the given targetfile belongs to the source repo. This
217 is useful when only a subdirectory of the target belongs to the source
218 repo."""
219 # For normal full repo converts, this is always True.
220 return True
221
222 def setrevmap(self, revmap):
223 """set the map of already-converted revisions"""
224
225 def getheads(self):
226 """Return a list of this repository's heads"""
227 raise NotImplementedError
228
229 def getfile(self, name, rev):
230 """Return a pair (data, mode) where data is the file content
231 as a string and mode one of '', 'x' or 'l'. rev is the
232 identifier returned by a previous call to getchanges().
233 Data is None if file is missing/deleted in rev.
234 """
235 raise NotImplementedError
236
237 def getchanges(self, version, full):
238 """Returns a tuple of (files, copies, cleanp2).
239
240 files is a sorted list of (filename, id) tuples for all files
241 changed between version and its first parent returned by
242 getcommit(). If full, all files in that revision is returned.
243 id is the source revision id of the file.
244
245 copies is a dictionary of dest: source
246
247 cleanp2 is the set of files filenames that are clean against p2.
248 (Files that are clean against p1 are already not in files (unless
249 full). This makes it possible to handle p2 clean files similarly.)
250 """
251 raise NotImplementedError
252
253 def getcommit(self, version):
254 """Return the commit object for version"""
255 raise NotImplementedError
256
257 def numcommits(self):
258 """Return the number of commits in this source.
259
260 If unknown, return None.
261 """
262 return None
263
264 def gettags(self):
265 """Return the tags as a dictionary of name: revision
266
267 Tag names must be UTF-8 strings.
268 """
269 raise NotImplementedError
270
271 def recode(self, s: AnyStr, encoding: bytes | None = None) -> bytes:
272 if not encoding:
273 encoding = self.encoding or b'utf-8'
274
275 if isinstance(s, str):
276 return s.encode("utf-8")
277 try:
278 return s.decode(pycompat.sysstr(encoding)).encode("utf-8")
279 except UnicodeError:
280 try:
281 return s.decode("latin-1").encode("utf-8")
282 except UnicodeError:
283 return s.decode(pycompat.sysstr(encoding), "replace").encode(
284 "utf-8"
285 )
286
287 def getchangedfiles(self, rev, i):
288 """Return the files changed by rev compared to parent[i].
289
290 i is an index selecting one of the parents of rev. The return
291 value should be the list of files that are different in rev and
292 this parent.
293
294 If rev has no parents, i is None.
295
296 This function is only needed to support --filemap
297 """
298 raise NotImplementedError
299
300 def converted(self, rev, sinkrev) -> None:
301 '''Notify the source that a revision has been converted.'''
302
303 def hasnativeorder(self) -> bool:
304 """Return true if this source has a meaningful, native revision
305 order. For instance, Mercurial revisions are store sequentially
306 while there is no such global ordering with Darcs.
307 """
308 return False
309
310 def hasnativeclose(self) -> bool:
311 """Return true if this source has ability to close branch."""
312 return False
313
314 def lookuprev(self, rev):
315 """If rev is a meaningful revision reference in source, return
316 the referenced identifier in the same format used by getcommit().
317 return None otherwise.
318 """
319 return None
320
321 def getbookmarks(self):
322 """Return the bookmarks as a dictionary of name: revision
323
324 Bookmark names are to be UTF-8 strings.
325 """
326 return {}
327
328 def checkrevformat(self, revstr, mapname: bytes = b'splicemap') -> bool:
329 """revstr is a string that describes a revision in the given
330 source control system. Return true if revstr has correct
331 format.
332 """
333 return True
334
335
336 class converter_sink:
337 """Conversion sink (target) interface"""
338
339 def __init__(self, ui: uimod.ui, repotype: bytes, path: bytes) -> None:
340 """Initialize conversion sink (or raise NoRepo("message")
341 exception if path is not a valid repository)
342
343 created is a list of paths to remove if a fatal error occurs
344 later"""
345 self.ui = ui
346 self.path = path
347 self.created = []
348 self.repotype = repotype
349
350 def revmapfile(self):
351 """Path to a file that will contain lines
352 source_rev_id sink_rev_id
353 mapping equivalent revision identifiers for each system."""
354 raise NotImplementedError
355
356 def authorfile(self):
357 """Path to a file that will contain lines
358 srcauthor=dstauthor
359 mapping equivalent authors identifiers for each system."""
360 return None
361
362 def putcommit(
363 self, files, copies, parents, commit, source, revmap, full, cleanp2
364 ):
365 """Create a revision with all changed files listed in 'files'
366 and having listed parents. 'commit' is a commit object
367 containing at a minimum the author, date, and message for this
368 changeset. 'files' is a list of (path, version) tuples,
369 'copies' is a dictionary mapping destinations to sources,
370 'source' is the source repository, and 'revmap' is a mapfile
371 of source revisions to converted revisions. Only getfile() and
372 lookuprev() should be called on 'source'. 'full' means that 'files'
373 is complete and all other files should be removed.
374 'cleanp2' is a set of the filenames that are unchanged from p2
375 (only in the common merge case where there two parents).
376
377 Note that the sink repository is not told to update itself to
378 a particular revision (or even what that revision would be)
379 before it receives the file data.
380 """
381 raise NotImplementedError
382
383 def puttags(self, tags):
384 """Put tags into sink.
385
386 tags: {tagname: sink_rev_id, ...} where tagname is an UTF-8 string.
387 Return a pair (tag_revision, tag_parent_revision), or (None, None)
388 if nothing was changed.
389 """
390 raise NotImplementedError
391
392 def setbranch(self, branch, pbranches):
393 """Set the current branch name. Called before the first putcommit
394 on the branch.
395 branch: branch name for subsequent commits
396 pbranches: (converted parent revision, parent branch) tuples"""
397
398 def setfilemapmode(self, active):
399 """Tell the destination that we're using a filemap
400
401 Some converter_sources (svn in particular) can claim that a file
402 was changed in a revision, even if there was no change. This method
403 tells the destination that we're using a filemap and that it should
404 filter empty revisions.
405 """
406
407 def before(self) -> None:
408 pass
409
410 def after(self) -> None:
411 pass
412
413 def putbookmarks(self, bookmarks):
414 """Put bookmarks into sink.
415
416 bookmarks: {bookmarkname: sink_rev_id, ...}
417 where bookmarkname is an UTF-8 string.
418 """
419
420 def hascommitfrommap(self, rev):
421 """Return False if a rev mentioned in a filemap is known to not be
422 present."""
423 raise NotImplementedError
424
425 def hascommitforsplicemap(self, rev):
426 """This method is for the special needs for splicemap handling and not
427 for general use. Returns True if the sink contains rev, aborts on some
428 special cases."""
429 raise NotImplementedError
430
431
432 class commandline:
433 def __init__(self, ui: uimod.ui, command: bytes) -> None:
434 self.ui = ui
435 self.command = command
436
437 def prerun(self) -> None:
438 pass
439
440 def postrun(self) -> None:
441 pass
442
443 def _cmdline(self, cmd: bytes, *args: bytes, **kwargs) -> bytes:
444 kwargs = pycompat.byteskwargs(kwargs)
445 cmdline = [self.command, cmd] + list(args)
446 for k, v in kwargs.items():
447 if len(k) == 1:
448 cmdline.append(b'-' + k)
449 else:
450 cmdline.append(b'--' + k.replace(b'_', b'-'))
451 try:
452 if len(k) == 1:
453 cmdline.append(b'' + v)
454 else:
455 cmdline[-1] += b'=' + v
456 except TypeError:
457 pass
458 cmdline = [procutil.shellquote(arg) for arg in cmdline]
459 if not self.ui.debugflag:
460 cmdline += [b'2>', pycompat.bytestr(os.devnull)]
461 cmdline = b' '.join(cmdline)
462 return cmdline
463
464 def _run(self, cmd: bytes, *args: bytes, **kwargs):
465 def popen(cmdline):
466 p = subprocess.Popen(
467 procutil.tonativestr(cmdline),
468 shell=True,
469 bufsize=-1,
470 close_fds=procutil.closefds,
471 stdout=subprocess.PIPE,
472 )
473 return p
474
475 return self._dorun(popen, cmd, *args, **kwargs)
476
477 def _run2(self, cmd: bytes, *args: bytes, **kwargs):
478 return self._dorun(procutil.popen2, cmd, *args, **kwargs)
479
480 def _run3(self, cmd: bytes, *args: bytes, **kwargs):
481 return self._dorun(procutil.popen3, cmd, *args, **kwargs)
482
483 def _dorun(self, openfunc, cmd: bytes, *args: bytes, **kwargs):
484 cmdline = self._cmdline(cmd, *args, **kwargs)
485 self.ui.debug(b'running: %s\n' % (cmdline,))
486 self.prerun()
487 try:
488 return openfunc(cmdline)
489 finally:
490 self.postrun()
491
492 def run(self, cmd: bytes, *args: bytes, **kwargs):
493 p = self._run(cmd, *args, **kwargs)
494 output = p.communicate()[0]
495 self.ui.debug(output)
496 return output, p.returncode
497
498 def runlines(self, cmd: bytes, *args: bytes, **kwargs):
499 p = self._run(cmd, *args, **kwargs)
500 output = p.stdout.readlines()
501 p.wait()
502 self.ui.debug(b''.join(output))
503 return output, p.returncode
504
505 def checkexit(self, status, output: bytes = b'') -> None:
506 if status:
507 if output:
508 self.ui.warn(_(b'%s error:\n') % self.command)
509 self.ui.warn(output)
510 msg = procutil.explainexit(status)
511 raise error.Abort(b'%s %s' % (self.command, msg))
512
513 def run0(self, cmd: bytes, *args: bytes, **kwargs):
514 output, status = self.run(cmd, *args, **kwargs)
515 self.checkexit(status, output)
516 return output
517
518 def runlines0(self, cmd: bytes, *args: bytes, **kwargs):
519 output, status = self.runlines(cmd, *args, **kwargs)
520 self.checkexit(status, b''.join(output))
521 return output
522
523 @propertycache
524 def argmax(self):
525 # POSIX requires at least 4096 bytes for ARG_MAX
526 argmax = 4096
527 try:
528 argmax = os.sysconf("SC_ARG_MAX")
529 except (AttributeError, ValueError):
530 pass
531
532 # Windows shells impose their own limits on command line length,
533 # down to 2047 bytes for cmd.exe under Windows NT/2k and 2500 bytes
534 # for older 4nt.exe. See http://support.microsoft.com/kb/830473 for
535 # details about cmd.exe limitations.
536
537 # Since ARG_MAX is for command line _and_ environment, lower our limit
538 # (and make happy Windows shells while doing this).
539 return argmax // 2 - 1
540
541 def _limit_arglist(self, arglist, cmd: bytes, *args: bytes, **kwargs):
542 cmdlen = len(self._cmdline(cmd, *args, **kwargs))
543 limit = self.argmax - cmdlen
544 numbytes = 0
545 fl = []
546 for fn in arglist:
547 b = len(fn) + 3
548 if numbytes + b < limit or len(fl) == 0:
549 fl.append(fn)
550 numbytes += b
551 else:
552 yield fl
553 fl = [fn]
554 numbytes = b
555 if fl:
556 yield fl
557
558 def xargs(self, arglist, cmd: bytes, *args: bytes, **kwargs):
559 for l in self._limit_arglist(arglist, cmd, *args, **kwargs):
560 self.run0(cmd, *(list(args) + l), **kwargs)
561
562
563 class mapfile(dict):
564 def __init__(self, ui: uimod.ui, path: bytes) -> None:
565 super().__init__()
566 self.ui = ui
567 self.path = path
568 self.fp = None
569 self.order = []
570 self._read()
571
572 def _read(self) -> None:
573 if not self.path:
574 return
575 try:
576 fp = open(self.path, 'rb')
577 except FileNotFoundError:
578 return
579
580 try:
581 for i, line in enumerate(fp):
582 line = line.splitlines()[0].rstrip()
583 if not line:
584 # Ignore blank lines
585 continue
586 try:
587 key, value = line.rsplit(b' ', 1)
588 except ValueError:
589 raise error.Abort(
590 _(b'syntax error in %s(%d): key/value pair expected')
591 % (self.path, i + 1)
592 )
593 if key not in self:
594 self.order.append(key)
595 super().__setitem__(key, value)
596 finally:
597 fp.close()
598
599 def __setitem__(self, key, value) -> None:
600 if self.fp is None:
601 try:
602 self.fp = open(self.path, 'ab')
603 except OSError as err:
604 raise error.Abort(
605 _(b'could not open map file %r: %s')
606 % (self.path, encoding.strtolocal(err.strerror))
607 )
608 self.fp.write(util.tonativeeol(b'%s %s\n' % (key, value)))
609 self.fp.flush()
610 super().__setitem__(key, value)
611
612 def close(self) -> None:
613 if self.fp:
614 self.fp.close()
615 self.fp = None
616
617
618 def makedatetimestamp(t: float) -> dateutil.hgdate:
619 return dateutil.makedate(t)