Debian Codegraph @

hgext/convert/common.py

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