Debian Codegraph @

hgext/convert/subversion.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # Subversion 1.4/1.5 Python API backend
2 #
3 # Copyright(C) 2007 Daniel Holth et al
4
5 from __future__ import annotations
6
7 import codecs
8 import locale
9 import os
10 import pickle
11 import re
12 import xml.dom.minidom
13
14 from mercurial.i18n import _
15 from mercurial import (
16 encoding,
17 error,
18 pycompat,
19 util,
20 vfs as vfsmod,
21 )
22 from mercurial.utils import (
23 dateutil,
24 procutil,
25 stringutil,
26 )
27
28 from . import common
29
30 stringio = util.stringio
31 propertycache = util.propertycache
32 urlerr = util.urlerr
33 urlreq = util.urlreq
34
35 commandline = common.commandline
36 commit = common.commit
37 converter_sink = common.converter_sink
38 converter_source = common.converter_source
39 decodeargs = common.decodeargs
40 encodeargs = common.encodeargs
41 makedatetimestamp = common.makedatetimestamp
42 mapfile = common.mapfile
43 MissingTool = common.MissingTool
44 NoRepo = common.NoRepo
45
46 # Subversion stuff. Works best with very recent Python SVN bindings
47 # e.g. SVN 1.5 or backports. Thanks to the bzr folks for enhancing
48 # these bindings.
49
50 try:
51 # pytype: disable=import-error
52 import svn
53 import svn.client
54 import svn.core
55 import svn.ra
56 import svn.delta
57
58 # pytype: enable=import-error
59 from . import transport
60 import warnings
61
62 warnings.filterwarnings(
63 'ignore', module='svn.core', category=DeprecationWarning
64 )
65 svn.core.SubversionException # trigger import to catch error
66
67 except ImportError:
68 svn = None
69
70
71 # In Subversion, paths and URLs are Unicode (encoded as UTF-8), which
72 # Subversion converts from / to native strings when interfacing with the OS.
73 # When passing paths and URLs to Subversion, we have to recode them such that
74 # it roundstrips with what Subversion is doing.
75
76 fsencoding = None
77
78
79 def init_fsencoding():
80 global fsencoding, fsencoding_is_utf8
81 if fsencoding is not None:
82 return
83 if pycompat.iswindows:
84 # On Windows, filenames are Unicode, but we store them using the MBCS
85 # encoding.
86 fsencoding = 'mbcs'
87 else:
88 # This is the encoding used to convert UTF-8 back to natively-encoded
89 # strings in Subversion 1.14.0 or earlier with APR 1.7.0 or earlier.
90 with util.with_lc_ctype():
91 fsencoding = locale.nl_langinfo(locale.CODESET) or 'ISO-8859-1'
92 fsencoding = codecs.lookup(fsencoding).name
93 fsencoding_is_utf8 = fsencoding == codecs.lookup('utf-8').name
94
95
96 def fs2svn(s):
97 if fsencoding_is_utf8:
98 return s
99 else:
100 return s.decode(fsencoding).encode('utf-8')
101
102
103 def formatsvndate(date):
104 return dateutil.datestr(date, b'%Y-%m-%dT%H:%M:%S.000000Z')
105
106
107 def parsesvndate(s):
108 # Example SVN datetime. Includes microseconds.
109 # ISO-8601 conformant
110 # '2007-01-04T17:35:00.902377Z'
111 return dateutil.parsedate(s[:19] + b' UTC', [b'%Y-%m-%dT%H:%M:%S'])
112
113
114 class SvnPathNotFound(Exception):
115 pass
116
117
118 def revsplit(rev):
119 """Parse a revision string and return (uuid, path, revnum).
120 >>> revsplit(b'svn:a2147622-4a9f-4db4-a8d3-13562ff547b2'
121 ... b'/proj%20B/mytrunk/mytrunk@1')
122 ('a2147622-4a9f-4db4-a8d3-13562ff547b2', '/proj%20B/mytrunk/mytrunk', 1)
123 >>> revsplit(b'svn:8af66a51-67f5-4354-b62c-98d67cc7be1d@1')
124 ('', '', 1)
125 >>> revsplit(b'@7')
126 ('', '', 7)
127 >>> revsplit(b'7')
128 ('', '', 0)
129 >>> revsplit(b'bad')
130 ('', '', 0)
131 """
132 parts = rev.rsplit(b'@', 1)
133 revnum = 0
134 if len(parts) > 1:
135 revnum = int(parts[1])
136 parts = parts[0].split(b'/', 1)
137 uuid = b''
138 mod = b''
139 if len(parts) > 1 and parts[0].startswith(b'svn:'):
140 uuid = parts[0][4:]
141 mod = b'/' + parts[1]
142 return uuid, mod, revnum
143
144
145 def quote(s):
146 # As of svn 1.7, many svn calls expect "canonical" paths. In
147 # theory, we should call svn.core.*canonicalize() on all paths
148 # before passing them to the API. Instead, we assume the base url
149 # is canonical and copy the behaviour of svn URL encoding function
150 # so we can extend it safely with new components. The "safe"
151 # characters were taken from the "svn_uri__char_validity" table in
152 # libsvn_subr/path.c.
153 return urlreq.quote(s, b"!$&'()*+,-./:=@_~")
154
155
156 def geturl(path):
157 """Convert path or URL to a SVN URL, encoded in UTF-8.
158
159 This can raise UnicodeDecodeError if the path or URL can't be converted to
160 unicode using `fsencoding`.
161 """
162 try:
163 return svn.client.url_from_path(
164 svn.core.svn_path_canonicalize(fs2svn(path))
165 )
166 except svn.core.SubversionException:
167 # svn.client.url_from_path() fails with local repositories
168 pass
169 if os.path.isdir(path):
170 path = os.path.normpath(util.abspath(path))
171 if pycompat.iswindows:
172 path = b'/' + util.normpath(path)
173 # Module URL is later compared with the repository URL returned
174 # by svn API, which is UTF-8.
175 path = fs2svn(path)
176 path = b'file://%s' % quote(path)
177 return svn.core.svn_path_canonicalize(path)
178
179
180 def optrev(number):
181 optrev = svn.core.svn_opt_revision_t()
182 optrev.kind = svn.core.svn_opt_revision_number
183 optrev.value.number = number
184 return optrev
185
186
187 class changedpath:
188 def __init__(self, p):
189 self.copyfrom_path = p.copyfrom_path
190 self.copyfrom_rev = p.copyfrom_rev
191 self.action = p.action
192
193
194 def get_log_child(
195 fp,
196 url,
197 paths,
198 start,
199 end,
200 limit=0,
201 discover_changed_paths=True,
202 strict_node_history=False,
203 ):
204 protocol = -1
205
206 def receiver(orig_paths, revnum, author, date, message, pool):
207 paths = {}
208 if orig_paths is not None:
209 for k, v in orig_paths.items():
210 paths[k] = changedpath(v)
211 pickle.dump((paths, revnum, author, date, message), fp, protocol)
212
213 try:
214 # Use an ra of our own so that our parent can consume
215 # our results without confusing the server.
216 t = transport.SvnRaTransport(url=url)
217 svn.ra.get_log(
218 t.ra,
219 paths,
220 start,
221 end,
222 limit,
223 discover_changed_paths,
224 strict_node_history,
225 receiver,
226 )
227 except OSError:
228 # Caller may interrupt the iteration
229 pickle.dump(None, fp, protocol)
230 except Exception as inst:
231 pickle.dump(stringutil.forcebytestr(inst), fp, protocol)
232 else:
233 pickle.dump(None, fp, protocol)
234 fp.flush()
235 # With large history, cleanup process goes crazy and suddenly
236 # consumes *huge* amount of memory. The output file being closed,
237 # there is no need for clean termination.
238 os._exit(0)
239
240
241 def debugsvnlog(ui, **opts):
242 """Fetch SVN log in a subprocess and channel them back to parent to
243 avoid memory collection issues.
244 """
245 with util.with_lc_ctype():
246 if svn is None:
247 raise error.Abort(
248 _(b'debugsvnlog could not load Subversion python bindings')
249 )
250
251 args = decodeargs(ui.fin.read())
252 get_log_child(ui.fout, *args)
253
254
255 class logstream:
256 """Interruptible revision log iterator."""
257
258 def __init__(self, stdout):
259 self._stdout = stdout
260
261 def __iter__(self):
262 while True:
263 try:
264 entry = pickle.load(self._stdout)
265 except EOFError:
266 raise error.Abort(
267 _(
268 b'Mercurial failed to run itself, check'
269 b' hg executable is in PATH'
270 )
271 )
272 try:
273 orig_paths, revnum, author, date, message = entry
274 except (TypeError, ValueError):
275 if entry is None:
276 break
277 raise error.Abort(_(b"log stream exception '%s'") % entry)
278 yield entry
279
280 def close(self):
281 if self._stdout:
282 self._stdout.close()
283 self._stdout = None
284
285
286 class directlogstream(list):
287 """Direct revision log iterator.
288 This can be used for debugging and development but it will probably leak
289 memory and is not suitable for real conversions."""
290
291 def __init__(
292 self,
293 url,
294 paths,
295 start,
296 end,
297 limit=0,
298 discover_changed_paths=True,
299 strict_node_history=False,
300 ):
301 def receiver(orig_paths, revnum, author, date, message, pool):
302 paths = {}
303 if orig_paths is not None:
304 for k, v in orig_paths.items():
305 paths[k] = changedpath(v)
306 self.append((paths, revnum, author, date, message))
307
308 # Use an ra of our own so that our parent can consume
309 # our results without confusing the server.
310 t = transport.SvnRaTransport(url=url)
311 svn.ra.get_log(
312 t.ra,
313 paths,
314 start,
315 end,
316 limit,
317 discover_changed_paths,
318 strict_node_history,
319 receiver,
320 )
321
322 def close(self):
323 pass
324
325
326 # Check to see if the given path is a local Subversion repo. Verify this by
327 # looking for several svn-specific files and directories in the given
328 # directory.
329 def filecheck(ui, path, proto):
330 for x in (b'locks', b'hooks', b'format', b'db'):
331 if not os.path.exists(os.path.join(path, x)):
332 return False
333 return True
334
335
336 # Check to see if a given path is the root of an svn repo over http. We verify
337 # this by requesting a version-controlled URL we know can't exist and looking
338 # for the svn-specific "not found" XML.
339 def httpcheck(ui, path, proto):
340 try:
341 opener = urlreq.buildopener()
342 rsp = opener.open(
343 pycompat.strurl(b'%s://%s/!svn/ver/0/.svn' % (proto, path)), b'rb'
344 )
345 data = rsp.read()
346 except urlerr.httperror as inst:
347 if inst.code != 404:
348 # Except for 404 we cannot know for sure this is not an svn repo
349 ui.warn(
350 _(
351 b'svn: cannot probe remote repository, assume it could '
352 b'be a subversion repository. Use --source-type if you '
353 b'know better.\n'
354 )
355 )
356 return True
357 data = inst.fp.read()
358 except Exception:
359 # Could be urlerr.urlerror if the URL is invalid or anything else.
360 return False
361 return b'<m:human-readable errcode="160013">' in data
362
363
364 protomap = {
365 b'http': httpcheck,
366 b'https': httpcheck,
367 b'file': filecheck,
368 }
369
370
371 def issvnurl(ui, url):
372 try:
373 proto, path = url.split(b'://', 1)
374 if proto == b'file':
375 if (
376 pycompat.iswindows
377 and path[:1] == b'/'
378 and path[1:2].isalpha()
379 and path[2:6].lower() == b'%3a/'
380 ):
381 path = path[:2] + b':/' + path[6:]
382 try:
383 unicodepath = path.decode(fsencoding)
384 except UnicodeDecodeError:
385 ui.warn(
386 _(
387 b'Subversion requires that file URLs can be converted '
388 b'to Unicode using the current locale encoding (%s)\n'
389 )
390 % pycompat.sysbytes(fsencoding)
391 )
392 return False
393
394 # Subversion paths are Unicode. Since it does percent-decoding on
395 # UTF-8-encoded strings, percent-encoded bytes are interpreted as
396 # UTF-8.
397 # On Python 3, we have to pass unicode to urlreq.url2pathname().
398 # Percent-decoded bytes get decoded using UTF-8 and the 'replace'
399 # error handler.
400 unicodepath = urlreq.url2pathname(unicodepath)
401 if '\N{REPLACEMENT CHARACTER}' in unicodepath:
402 ui.warn(
403 _(
404 b'Subversion does not support non-UTF-8 '
405 b'percent-encoded bytes in file URLs\n'
406 )
407 )
408 return False
409
410 # Below, we approximate how Subversion checks the path. On Unix, we
411 # should therefore convert the path to bytes using `fsencoding`
412 # (like Subversion does). On Windows, the right thing would
413 # actually be to leave the path as unicode. For now, we restrict
414 # the path to MBCS.
415 path = unicodepath.encode(fsencoding)
416 except ValueError:
417 proto = b'file'
418 path = util.abspath(url)
419 try:
420 path.decode(fsencoding)
421 except UnicodeDecodeError:
422 ui.warn(
423 _(
424 b'Subversion requires that paths can be converted to '
425 b'Unicode using the current locale encoding (%s)\n'
426 )
427 % pycompat.sysbytes(fsencoding)
428 )
429 return False
430 if proto == b'file':
431 path = util.pconvert(path)
432 elif proto in (b'http', 'https'):
433 if not encoding.isasciistr(path):
434 ui.warn(
435 _(
436 b"Subversion sources don't support non-ASCII characters in "
437 b"HTTP(S) URLs. Please percent-encode them.\n"
438 )
439 )
440 return False
441 check = protomap.get(proto, lambda *args: False)
442 while b'/' in path:
443 if check(ui, path, proto):
444 return True
445 path = path.rsplit(b'/', 1)[0]
446 return False
447
448
449 # SVN conversion code stolen from bzr-svn and tailor
450 #
451 # Subversion looks like a versioned filesystem, branches structures
452 # are defined by conventions and not enforced by the tool. First,
453 # we define the potential branches (modules) as "trunk" and "branches"
454 # children directories. Revisions are then identified by their
455 # module and revision number (and a repository identifier).
456 #
457 # The revision graph is really a tree (or a forest). By default, a
458 # revision parent is the previous revision in the same module. If the
459 # module directory is copied/moved from another module then the
460 # revision is the module root and its parent the source revision in
461 # the parent module. A revision has at most one parent.
462 #
463 class svn_source(converter_source):
464 def __init__(self, ui, repotype, url, revs=None):
465 super().__init__(ui, repotype, url, revs=revs)
466
467 init_fsencoding()
468 if not (
469 url.startswith(b'svn://')
470 or url.startswith(b'svn+ssh://')
471 or (
472 os.path.exists(url)
473 and os.path.exists(os.path.join(url, b'.svn'))
474 )
475 or issvnurl(ui, url)
476 ):
477 raise NoRepo(
478 _(b"%s does not look like a Subversion repository") % url
479 )
480 if svn is None:
481 raise MissingTool(_(b'could not load Subversion python bindings'))
482
483 try:
484 version = svn.core.SVN_VER_MAJOR, svn.core.SVN_VER_MINOR
485 if version < (1, 4):
486 raise MissingTool(
487 _(
488 b'Subversion python bindings %d.%d found, '
489 b'1.4 or later required'
490 )
491 % version
492 )
493 except AttributeError:
494 raise MissingTool(
495 _(
496 b'Subversion python bindings are too old, 1.4 '
497 b'or later required'
498 )
499 )
500
501 self.lastrevs = {}
502
503 latest = None
504 try:
505 # Support file://path@rev syntax. Useful e.g. to convert
506 # deleted branches.
507 at = url.rfind(b'@')
508 if at >= 0:
509 latest = int(url[at + 1 :])
510 url = url[:at]
511 except ValueError:
512 pass
513 self.url = geturl(url)
514 self.encoding = b'UTF-8' # Subversion is always nominal UTF-8
515 try:
516 with util.with_lc_ctype():
517 self.transport = transport.SvnRaTransport(url=self.url)
518 self.ra = self.transport.ra
519 self.ctx = self.transport.client
520 self.baseurl = svn.ra.get_repos_root(self.ra)
521 # Module is either empty or a repository path starting with
522 # a slash and not ending with a slash.
523 self.module = urlreq.unquote(self.url[len(self.baseurl) :])
524 self.prevmodule = None
525 self.rootmodule = self.module
526 self.commits = {}
527 self.paths = {}
528 self.uuid = svn.ra.get_uuid(self.ra)
529 except svn.core.SubversionException:
530 ui.traceback()
531 svnversion = b'%d.%d.%d' % (
532 svn.core.SVN_VER_MAJOR,
533 svn.core.SVN_VER_MINOR,
534 svn.core.SVN_VER_MICRO,
535 )
536 raise NoRepo(
537 _(
538 b"%s does not look like a Subversion repository "
539 b"to libsvn version %s"
540 )
541 % (self.url, svnversion)
542 )
543
544 if revs:
545 if len(revs) > 1:
546 raise error.Abort(
547 _(
548 b'subversion source does not support '
549 b'specifying multiple revisions'
550 )
551 )
552 try:
553 latest = int(revs[0])
554 except ValueError:
555 raise error.Abort(
556 _(b'svn: revision %s is not an integer') % revs[0]
557 )
558
559 trunkcfg = self.ui.config(b'convert', b'svn.trunk')
560 if trunkcfg is None:
561 trunkcfg = b'trunk'
562 self.trunkname = trunkcfg.strip(b'/')
563 self.startrev = self.ui.config(b'convert', b'svn.startrev')
564 try:
565 self.startrev = int(self.startrev)
566 if self.startrev < 0:
567 self.startrev = 0
568 except ValueError:
569 raise error.Abort(
570 _(b'svn: start revision %s is not an integer') % self.startrev
571 )
572
573 try:
574 with util.with_lc_ctype():
575 self.head = self.latest(self.module, latest)
576 except SvnPathNotFound:
577 self.head = None
578 if not self.head:
579 raise error.Abort(
580 _(b'no revision found in module %s') % self.module
581 )
582 self.last_changed = self.revnum(self.head)
583
584 self._changescache = (None, None)
585
586 if os.path.exists(os.path.join(url, b'.svn/entries')):
587 self.wc = url
588 else:
589 self.wc = None
590 self.convertfp = None
591
592 def before(self):
593 self.with_lc_ctype = util.with_lc_ctype()
594 self.with_lc_ctype.__enter__()
595
596 def after(self):
597 self.with_lc_ctype.__exit__(None, None, None)
598
599 def setrevmap(self, revmap):
600 lastrevs = {}
601 for revid in revmap:
602 uuid, module, revnum = revsplit(revid)
603 lastrevnum = lastrevs.setdefault(module, revnum)
604 if revnum > lastrevnum:
605 lastrevs[module] = revnum
606 self.lastrevs = lastrevs
607
608 def exists(self, path, optrev):
609 try:
610 svn.client.ls(
611 self.url.rstrip(b'/') + b'/' + quote(path),
612 optrev,
613 False,
614 self.ctx,
615 )
616 return True
617 except svn.core.SubversionException:
618 return False
619
620 def getheads(self):
621 def isdir(path, revnum):
622 kind = self._checkpath(path, revnum)
623 return kind == svn.core.svn_node_dir
624
625 def getcfgpath(name, rev):
626 cfgpath = self.ui.config(b'convert', b'svn.' + name)
627 if cfgpath is not None and cfgpath.strip() == b'':
628 return None
629 path = (cfgpath or name).strip(b'/')
630 if not self.exists(path, rev):
631 if self.module.endswith(path) and name == b'trunk':
632 # we are converting from inside this directory
633 return None
634 if cfgpath:
635 raise error.Abort(
636 _(b'expected %s to be at %r, but not found')
637 % (name, path)
638 )
639 return None
640 self.ui.note(
641 _(b'found %s at %r\n') % (name, pycompat.bytestr(path))
642 )
643 return path
644
645 rev = optrev(self.last_changed)
646 oldmodule = b''
647 trunk = getcfgpath(b'trunk', rev)
648 self.tags = getcfgpath(b'tags', rev)
649 branches = getcfgpath(b'branches', rev)
650
651 # If the project has a trunk or branches, we will extract heads
652 # from them. We keep the project root otherwise.
653 if trunk:
654 oldmodule = self.module or b''
655 self.module += b'/' + trunk
656 self.head = self.latest(self.module, self.last_changed)
657 if not self.head:
658 raise error.Abort(
659 _(b'no revision found in module %s') % self.module
660 )
661
662 # First head in the list is the module's head
663 self.heads = [self.head]
664 if self.tags is not None:
665 self.tags = b'%s/%s' % (oldmodule, (self.tags or b'tags'))
666
667 # Check if branches bring a few more heads to the list
668 if branches:
669 rpath = self.url.strip(b'/')
670 branchnames = svn.client.ls(
671 rpath + b'/' + quote(branches), rev, False, self.ctx
672 )
673 for branch in sorted(branchnames):
674 module = b'%s/%s/%s' % (oldmodule, branches, branch)
675 if not isdir(module, self.last_changed):
676 continue
677 brevid = self.latest(module, self.last_changed)
678 if not brevid:
679 self.ui.note(_(b'ignoring empty branch %s\n') % branch)
680 continue
681 self.ui.note(
682 _(b'found branch %s at %d\n')
683 % (branch, self.revnum(brevid))
684 )
685 self.heads.append(brevid)
686
687 if self.startrev and self.heads:
688 if len(self.heads) > 1:
689 raise error.Abort(
690 _(
691 b'svn: start revision is not supported '
692 b'with more than one branch'
693 )
694 )
695 revnum = self.revnum(self.heads[0])
696 if revnum < self.startrev:
697 raise error.Abort(
698 _(b'svn: no revision found after start revision %d')
699 % self.startrev
700 )
701
702 return self.heads
703
704 def _getchanges(self, rev, full):
705 (paths, parents) = self.paths[rev]
706 copies = {}
707 if parents:
708 files, self.removed, copies = self.expandpaths(rev, paths, parents)
709 if full or not parents:
710 # Perform a full checkout on roots
711 uuid, module, revnum = revsplit(rev)
712 entries = svn.client.ls(
713 self.baseurl + quote(module), optrev(revnum), True, self.ctx
714 )
715 files = [
716 n
717 for n, e in entries.items()
718 if e.kind == svn.core.svn_node_file
719 ]
720 self.removed = set()
721
722 files.sort()
723 files = pycompat.ziplist(files, [rev] * len(files))
724 return (files, copies)
725
726 def getchanges(self, rev, full):
727 # reuse cache from getchangedfiles
728 if self._changescache[0] == rev and not full:
729 # TODO: add type hints to avoid this warning, instead of
730 # suppressing it:
731 # No attribute '__iter__' on None [attribute-error]
732
733 # pytype: disable=attribute-error
734 (files, copies) = self._changescache[1]
735 # pytype: enable=attribute-error
736 else:
737 (files, copies) = self._getchanges(rev, full)
738 # caller caches the result, so free it here to release memory
739 del self.paths[rev]
740 return (files, copies, set())
741
742 def getchangedfiles(self, rev, i):
743 # called from filemap - cache computed values for reuse in getchanges
744 (files, copies) = self._getchanges(rev, False)
745 self._changescache = (rev, (files, copies))
746 return [f[0] for f in files]
747
748 def getcommit(self, rev):
749 if rev not in self.commits:
750 uuid, module, revnum = revsplit(rev)
751 self.module = module
752 self.reparent(module)
753 # We assume that:
754 # - requests for revisions after "stop" come from the
755 # revision graph backward traversal. Cache all of them
756 # down to stop, they will be used eventually.
757 # - requests for revisions before "stop" come to get
758 # isolated branches parents. Just fetch what is needed.
759 stop = self.lastrevs.get(module, 0)
760 if revnum < stop:
761 stop = revnum + 1
762 self._fetch_revisions(revnum, stop)
763 if rev not in self.commits:
764 raise error.Abort(_(b'svn: revision %s not found') % revnum)
765 revcommit = self.commits[rev]
766 # caller caches the result, so free it here to release memory
767 del self.commits[rev]
768 return revcommit
769
770 def checkrevformat(self, revstr, mapname=b'splicemap'):
771 """fails if revision format does not match the correct format"""
772 if not re.match(
773 br'svn:[0-9a-f]{8,8}-[0-9a-f]{4,4}-'
774 br'[0-9a-f]{4,4}-[0-9a-f]{4,4}-[0-9a-f]'
775 br'{12,12}(.*)@[0-9]+$',
776 revstr,
777 ):
778 raise error.Abort(
779 _(b'%s entry %s is not a valid revision identifier')
780 % (mapname, revstr)
781 )
782
783 def numcommits(self):
784 return int(self.head.rsplit(b'@', 1)[1]) - self.startrev
785
786 def gettags(self):
787 tags = {}
788 if self.tags is None:
789 return tags
790
791 # svn tags are just a convention, project branches left in a
792 # 'tags' directory. There is no other relationship than
793 # ancestry, which is expensive to discover and makes them hard
794 # to update incrementally. Worse, past revisions may be
795 # referenced by tags far away in the future, requiring a deep
796 # history traversal on every calculation. Current code
797 # performs a single backward traversal, tracking moves within
798 # the tags directory (tag renaming) and recording a new tag
799 # everytime a project is copied from outside the tags
800 # directory. It also lists deleted tags, this behaviour may
801 # change in the future.
802 pendings = []
803 tagspath = self.tags
804 start = svn.ra.get_latest_revnum(self.ra)
805 stream = self._getlog([self.tags], start, self.startrev)
806 try:
807 for entry in stream:
808 origpaths, revnum, author, date, message = entry
809 if not origpaths:
810 origpaths = []
811 copies = [
812 (e.copyfrom_path, e.copyfrom_rev, p)
813 for p, e in origpaths.items()
814 if e.copyfrom_path
815 ]
816 # Apply moves/copies from more specific to general
817 copies.sort(reverse=True)
818
819 srctagspath = tagspath
820 if copies and copies[-1][2] == tagspath:
821 # Track tags directory moves
822 srctagspath = copies.pop()[0]
823
824 for source, sourcerev, dest in copies:
825 if not dest.startswith(tagspath + b'/'):
826 continue
827 for tag in pendings:
828 if tag[0].startswith(dest):
829 tagpath = source + tag[0][len(dest) :]
830 tag[:2] = [tagpath, sourcerev]
831 break
832 else:
833 pendings.append([source, sourcerev, dest])
834
835 # Filter out tags with children coming from different
836 # parts of the repository like:
837 # /tags/tag.1 (from /trunk:10)
838 # /tags/tag.1/foo (from /branches/foo:12)
839 # Here/tags/tag.1 discarded as well as its children.
840 # It happens with tools like cvs2svn. Such tags cannot
841 # be represented in mercurial.
842 addeds = {
843 p: e.copyfrom_path
844 for p, e in origpaths.items()
845 if e.action == b'A' and e.copyfrom_path
846 }
847 badroots = set()
848 for destroot in addeds:
849 for source, sourcerev, dest in pendings:
850 if not dest.startswith(
851 destroot + b'/'
852 ) or source.startswith(addeds[destroot] + b'/'):
853 continue
854 badroots.add(destroot)
855 break
856
857 for badroot in badroots:
858 pendings = [
859 p
860 for p in pendings
861 if p[2] != badroot
862 and not p[2].startswith(badroot + b'/')
863 ]
864
865 # Tell tag renamings from tag creations
866 renamings = []
867 for source, sourcerev, dest in pendings:
868 tagname = dest.split(b'/')[-1]
869 if source.startswith(srctagspath):
870 renamings.append([source, sourcerev, tagname])
871 continue
872 if tagname in tags:
873 # Keep the latest tag value
874 continue
875 # From revision may be fake, get one with changes
876 try:
877 tagid = self.latest(source, sourcerev)
878 if tagid and tagname not in tags:
879 tags[tagname] = tagid
880 except SvnPathNotFound:
881 # It happens when we are following directories
882 # we assumed were copied with their parents
883 # but were really created in the tag
884 # directory.
885 pass
886 pendings = renamings
887 tagspath = srctagspath
888 finally:
889 stream.close()
890 return tags
891
892 def converted(self, rev, destrev):
893 if not self.wc:
894 return
895 if self.convertfp is None:
896 self.convertfp = open(
897 os.path.join(self.wc, b'.svn', b'hg-shamap'), 'ab'
898 )
899 self.convertfp.write(
900 util.tonativeeol(b'%s %d\n' % (destrev, self.revnum(rev)))
901 )
902 self.convertfp.flush()
903
904 def revid(self, revnum, module=None):
905 return b'svn:%s%s@%d' % (self.uuid, module or self.module, revnum)
906
907 def revnum(self, rev):
908 return int(rev.split(b'@')[-1])
909
910 def latest(self, path, stop=None):
911 """Find the latest revid affecting path, up to stop revision
912 number. If stop is None, default to repository latest
913 revision. It may return a revision in a different module,
914 since a branch may be moved without a change being
915 reported. Return None if computed module does not belong to
916 rootmodule subtree.
917 """
918
919 def findchanges(path, start, stop=None):
920 stream = self._getlog([path], start, stop or 1)
921 try:
922 for entry in stream:
923 paths, revnum, author, date, message = entry
924 if stop is None and paths:
925 # We do not know the latest changed revision,
926 # keep the first one with changed paths.
927 break
928 if stop is not None and revnum <= stop:
929 break
930
931 for p in paths:
932 if not path.startswith(p) or not paths[p].copyfrom_path:
933 continue
934 newpath = paths[p].copyfrom_path + path[len(p) :]
935 self.ui.debug(
936 b"branch renamed from %s to %s at %d\n"
937 % (path, newpath, revnum)
938 )
939 path = newpath
940 break
941 if not paths:
942 revnum = None
943 return revnum, path
944 finally:
945 stream.close()
946
947 if not path.startswith(self.rootmodule):
948 # Requests on foreign branches may be forbidden at server level
949 self.ui.debug(b'ignoring foreign branch %r\n' % path)
950 return None
951
952 if stop is None:
953 stop = svn.ra.get_latest_revnum(self.ra)
954 try:
955 prevmodule = self.reparent(b'')
956 dirent = svn.ra.stat(self.ra, path.strip(b'/'), stop)
957 self.reparent(prevmodule)
958 except svn.core.SubversionException:
959 dirent = None
960 if not dirent:
961 raise SvnPathNotFound(
962 _(b'%s not found up to revision %d') % (path, stop)
963 )
964
965 # stat() gives us the previous revision on this line of
966 # development, but it might be in *another module*. Fetch the
967 # log and detect renames down to the latest revision.
968 revnum, realpath = findchanges(path, stop, dirent.created_rev)
969 if revnum is None:
970 # Tools like svnsync can create empty revision, when
971 # synchronizing only a subtree for instance. These empty
972 # revisions created_rev still have their original values
973 # despite all changes having disappeared and can be
974 # returned by ra.stat(), at least when stating the root
975 # module. In that case, do not trust created_rev and scan
976 # the whole history.
977 revnum, realpath = findchanges(path, stop)
978 if revnum is None:
979 self.ui.debug(b'ignoring empty branch %r\n' % realpath)
980 return None
981
982 if not realpath.startswith(self.rootmodule):
983 self.ui.debug(b'ignoring foreign branch %r\n' % realpath)
984 return None
985 return self.revid(revnum, realpath)
986
987 def reparent(self, module):
988 """Reparent the svn transport and return the previous parent."""
989 if self.prevmodule == module:
990 return module
991 svnurl = self.baseurl + quote(module)
992 prevmodule = self.prevmodule
993 if prevmodule is None:
994 prevmodule = b''
995 self.ui.debug(b"reparent to %s\n" % svnurl)
996 svn.ra.reparent(self.ra, svnurl)
997 self.prevmodule = module
998 return prevmodule
999
1000 def expandpaths(self, rev, paths, parents):
1001 changed, removed = set(), set()
1002 copies = {}
1003
1004 new_module, revnum = revsplit(rev)[1:]
1005 if new_module != self.module:
1006 self.module = new_module
1007 self.reparent(self.module)
1008
1009 progress = self.ui.makeprogress(
1010 _(b'scanning paths'), unit=_(b'paths'), total=len(paths)
1011 )
1012 for i, (path, ent) in enumerate(paths):
1013 progress.update(i, item=path)
1014 entrypath = self.getrelpath(path)
1015
1016 kind = self._checkpath(entrypath, revnum)
1017 if kind == svn.core.svn_node_file:
1018 changed.add(self.recode(entrypath))
1019 if not ent.copyfrom_path or not parents:
1020 continue
1021 # Copy sources not in parent revisions cannot be
1022 # represented, ignore their origin for now
1023 pmodule, prevnum = revsplit(parents[0])[1:]
1024 if ent.copyfrom_rev < prevnum:
1025 continue
1026 copyfrom_path = self.getrelpath(ent.copyfrom_path, pmodule)
1027 if not copyfrom_path:
1028 continue
1029 self.ui.debug(
1030 b"copied to %s from %s@%d\n"
1031 % (entrypath, copyfrom_path, ent.copyfrom_rev)
1032 )
1033 copies[self.recode(entrypath)] = self.recode(copyfrom_path)
1034 elif kind == 0: # gone, but had better be a deleted *file*
1035 self.ui.debug(b"gone from %d\n" % ent.copyfrom_rev)
1036 pmodule, prevnum = revsplit(parents[0])[1:]
1037 parentpath = pmodule + b"/" + entrypath
1038 fromkind = self._checkpath(entrypath, prevnum, pmodule)
1039
1040 if fromkind == svn.core.svn_node_file:
1041 removed.add(self.recode(entrypath))
1042 elif fromkind == svn.core.svn_node_dir:
1043 oroot = parentpath.strip(b'/')
1044 nroot = path.strip(b'/')
1045 children = self._iterfiles(oroot, prevnum)
1046 for childpath in children:
1047 childpath = childpath.replace(oroot, nroot)
1048 childpath = self.getrelpath(b"/" + childpath, pmodule)
1049 if childpath:
1050 removed.add(self.recode(childpath))
1051 else:
1052 self.ui.debug(
1053 b'unknown path in revision %d: %s\n' % (revnum, path)
1054 )
1055 elif kind == svn.core.svn_node_dir:
1056 if ent.action == b'M':
1057 # If the directory just had a prop change,
1058 # then we shouldn't need to look for its children.
1059 continue
1060 if ent.action == b'R' and parents:
1061 # If a directory is replacing a file, mark the previous
1062 # file as deleted
1063 pmodule, prevnum = revsplit(parents[0])[1:]
1064 pkind = self._checkpath(entrypath, prevnum, pmodule)
1065 if pkind == svn.core.svn_node_file:
1066 removed.add(self.recode(entrypath))
1067 elif pkind == svn.core.svn_node_dir:
1068 # We do not know what files were kept or removed,
1069 # mark them all as changed.
1070 for childpath in self._iterfiles(pmodule, prevnum):
1071 childpath = self.getrelpath(b"/" + childpath)
1072 if childpath:
1073 changed.add(self.recode(childpath))
1074
1075 for childpath in self._iterfiles(path, revnum):
1076 childpath = self.getrelpath(b"/" + childpath)
1077 if childpath:
1078 changed.add(self.recode(childpath))
1079
1080 # Handle directory copies
1081 if not ent.copyfrom_path or not parents:
1082 continue
1083 # Copy sources not in parent revisions cannot be
1084 # represented, ignore their origin for now
1085 pmodule, prevnum = revsplit(parents[0])[1:]
1086 if ent.copyfrom_rev < prevnum:
1087 continue
1088 copyfrompath = self.getrelpath(ent.copyfrom_path, pmodule)
1089 if not copyfrompath:
1090 continue
1091 self.ui.debug(
1092 b"mark %s came from %s:%d\n"
1093 % (path, copyfrompath, ent.copyfrom_rev)
1094 )
1095 children = self._iterfiles(ent.copyfrom_path, ent.copyfrom_rev)
1096 for childpath in children:
1097 childpath = self.getrelpath(b"/" + childpath, pmodule)
1098 if not childpath:
1099 continue
1100 copytopath = path + childpath[len(copyfrompath) :]
1101 copytopath = self.getrelpath(copytopath)
1102 copies[self.recode(copytopath)] = self.recode(childpath)
1103
1104 progress.complete()
1105 changed.update(removed)
1106 return (list(changed), removed, copies)
1107
1108 def _fetch_revisions(self, from_revnum, to_revnum):
1109 if from_revnum < to_revnum:
1110 from_revnum, to_revnum = to_revnum, from_revnum
1111
1112 self.child_cset = None
1113
1114 def parselogentry(orig_paths, revnum, author, date, message):
1115 """Return the parsed commit object or None, and True if
1116 the revision is a branch root.
1117 """
1118 self.ui.debug(
1119 b"parsing revision %d (%d changes)\n"
1120 % (revnum, len(orig_paths))
1121 )
1122
1123 branched = False
1124 rev = self.revid(revnum)
1125 # branch log might return entries for a parent we already have
1126
1127 if rev in self.commits or revnum < to_revnum:
1128 return None, branched
1129
1130 parents = []
1131 # check whether this revision is the start of a branch or part
1132 # of a branch renaming
1133 orig_paths = sorted(orig_paths.items())
1134 root_paths = [
1135 (p, e) for p, e in orig_paths if self.module.startswith(p)
1136 ]
1137 if root_paths:
1138 path, ent = root_paths[-1]
1139 if ent.copyfrom_path:
1140 branched = True
1141 newpath = ent.copyfrom_path + self.module[len(path) :]
1142 # ent.copyfrom_rev may not be the actual last revision
1143 previd = self.latest(newpath, ent.copyfrom_rev)
1144 if previd is not None:
1145 prevmodule, prevnum = revsplit(previd)[1:]
1146 if prevnum >= self.startrev:
1147 parents = [previd]
1148 self.ui.note(
1149 _(b'found parent of branch %s at %d: %s\n')
1150 % (self.module, prevnum, prevmodule)
1151 )
1152 else:
1153 self.ui.debug(b"no copyfrom path, don't know what to do.\n")
1154
1155 paths = []
1156 # filter out unrelated paths
1157 for path, ent in orig_paths:
1158 if self.getrelpath(path) is None:
1159 continue
1160 paths.append((path, ent))
1161
1162 date = parsesvndate(date)
1163 if self.ui.configbool(b'convert', b'localtimezone'):
1164 date = makedatetimestamp(date[0])
1165
1166 if message:
1167 log = self.recode(message)
1168 else:
1169 log = b''
1170
1171 if author:
1172 author = self.recode(author)
1173 else:
1174 author = b''
1175
1176 try:
1177 branch = self.module.split(b"/")[-1]
1178 if branch == self.trunkname:
1179 branch = None
1180 except IndexError:
1181 branch = None
1182
1183 cset = commit(
1184 author=author,
1185 date=dateutil.datestr(date, b'%Y-%m-%d %H:%M:%S %1%2'),
1186 desc=log,
1187 parents=parents,
1188 branch=branch,
1189 rev=rev,
1190 )
1191
1192 self.commits[rev] = cset
1193 # The parents list is *shared* among self.paths and the
1194 # commit object. Both will be updated below.
1195 self.paths[rev] = (paths, cset.parents)
1196 if self.child_cset and not self.child_cset.parents:
1197 self.child_cset.parents[:] = [rev]
1198 self.child_cset = cset
1199 return cset, branched
1200
1201 self.ui.note(
1202 _(b'fetching revision log for "%s" from %d to %d\n')
1203 % (self.module, from_revnum, to_revnum)
1204 )
1205
1206 try:
1207 firstcset = None
1208 lastonbranch = False
1209 stream = self._getlog([self.module], from_revnum, to_revnum)
1210 try:
1211 for entry in stream:
1212 paths, revnum, author, date, message = entry
1213 if revnum < self.startrev:
1214 lastonbranch = True
1215 break
1216 if not paths:
1217 self.ui.debug(b'revision %d has no entries\n' % revnum)
1218 # If we ever leave the loop on an empty
1219 # revision, do not try to get a parent branch
1220 lastonbranch = lastonbranch or revnum == 0
1221 continue
1222 cset, lastonbranch = parselogentry(
1223 paths, revnum, author, date, message
1224 )
1225 if cset:
1226 firstcset = cset
1227 if lastonbranch:
1228 break
1229 finally:
1230 stream.close()
1231
1232 if not lastonbranch and firstcset and not firstcset.parents:
1233 # The first revision of the sequence (the last fetched one)
1234 # has invalid parents if not a branch root. Find the parent
1235 # revision now, if any.
1236 try:
1237 firstrevnum = self.revnum(firstcset.rev)
1238 if firstrevnum > 1:
1239 latest = self.latest(self.module, firstrevnum - 1)
1240 if latest:
1241 firstcset.parents.append(latest)
1242 except SvnPathNotFound:
1243 pass
1244 except svn.core.SubversionException as xxx_todo_changeme:
1245 (inst, num) = xxx_todo_changeme.args
1246 if num == svn.core.SVN_ERR_FS_NO_SUCH_REVISION:
1247 raise error.Abort(
1248 _(b'svn: branch has no revision %s') % to_revnum
1249 )
1250 raise
1251
1252 def getfile(self, file, rev):
1253 # TODO: ra.get_file transmits the whole file instead of diffs.
1254 if file in self.removed:
1255 return None, None
1256 try:
1257 new_module, revnum = revsplit(rev)[1:]
1258 if self.module != new_module:
1259 self.module = new_module
1260 self.reparent(self.module)
1261 io = stringio()
1262 info = svn.ra.get_file(self.ra, file, revnum, io)
1263 data = io.getvalue()
1264 # ra.get_file() seems to keep a reference on the input buffer
1265 # preventing collection. Release it explicitly.
1266 io.close()
1267 if isinstance(info, list):
1268 info = info[-1]
1269 mode = (b"svn:executable" in info) and b'x' or b''
1270 mode = (b"svn:special" in info) and b'l' or mode
1271 except svn.core.SubversionException as e:
1272 notfound = (
1273 svn.core.SVN_ERR_FS_NOT_FOUND,
1274 svn.core.SVN_ERR_RA_DAV_PATH_NOT_FOUND,
1275 )
1276 if e.apr_err in notfound: # File not found
1277 return None, None
1278 raise
1279 if mode == b'l':
1280 link_prefix = b"link "
1281 if data.startswith(link_prefix):
1282 data = data[len(link_prefix) :]
1283 return data, mode
1284
1285 def _iterfiles(self, path, revnum):
1286 """Enumerate all files in path at revnum, recursively."""
1287 path = path.strip(b'/')
1288 pool = svn.core.Pool()
1289 rpath = b'/'.join([self.baseurl, quote(path)]).strip(b'/')
1290 entries = svn.client.ls(rpath, optrev(revnum), True, self.ctx, pool)
1291 if path:
1292 path += b'/'
1293 return (
1294 (path + p)
1295 for p, e in entries.items()
1296 if e.kind == svn.core.svn_node_file
1297 )
1298
1299 def getrelpath(self, path, module=None):
1300 if module is None:
1301 module = self.module
1302 # Given the repository url of this wc, say
1303 # "http://server/plone/CMFPlone/branches/Plone-2_0-branch"
1304 # extract the "entry" portion (a relative path) from what
1305 # svn log --xml says, i.e.
1306 # "/CMFPlone/branches/Plone-2_0-branch/tests/PloneTestCase.py"
1307 # that is to say "tests/PloneTestCase.py"
1308 if path.startswith(module):
1309 relative = path.rstrip(b'/')[len(module) :]
1310 if relative.startswith(b'/'):
1311 return relative[1:]
1312 elif relative == b'':
1313 return relative
1314
1315 # The path is outside our tracked tree...
1316 self.ui.debug(
1317 b'%r is not under %r, ignoring\n'
1318 % (pycompat.bytestr(path), pycompat.bytestr(module))
1319 )
1320 return None
1321
1322 def _checkpath(self, path, revnum, module=None):
1323 if module is not None:
1324 prevmodule = self.reparent(b'')
1325 path = module + b'/' + path
1326 try:
1327 # ra.check_path does not like leading slashes very much, it leads
1328 # to PROPFIND subversion errors
1329 return svn.ra.check_path(self.ra, path.strip(b'/'), revnum)
1330 finally:
1331 if module is not None:
1332 self.reparent(prevmodule)
1333
1334 def _getlog(
1335 self,
1336 paths,
1337 start,
1338 end,
1339 limit=0,
1340 discover_changed_paths=True,
1341 strict_node_history=False,
1342 ):
1343 # Normalize path names, svn >= 1.5 only wants paths relative to
1344 # supplied URL
1345 relpaths = []
1346 for p in paths:
1347 if not p.startswith(b'/'):
1348 p = self.module + b'/' + p
1349 relpaths.append(p.strip(b'/'))
1350 args = [
1351 self.baseurl,
1352 relpaths,
1353 start,
1354 end,
1355 limit,
1356 discover_changed_paths,
1357 strict_node_history,
1358 ]
1359 # developer config: convert.svn.debugsvnlog
1360 if not self.ui.configbool(b'convert', b'svn.debugsvnlog'):
1361 return directlogstream(*args)
1362 arg = encodeargs(args)
1363 hgexe = procutil.hgexecutable()
1364 cmd = b'%s debugsvnlog' % procutil.shellquote(hgexe)
1365 stdin, stdout = procutil.popen2(cmd)
1366 stdin.write(arg)
1367 try:
1368 stdin.close()
1369 except OSError:
1370 raise error.Abort(
1371 _(
1372 b'Mercurial failed to run itself, check'
1373 b' hg executable is in PATH'
1374 )
1375 )
1376 return logstream(stdout)
1377
1378
1379 pre_revprop_change_template = b'''#!/bin/sh
1380
1381 REPOS="$1"
1382 REV="$2"
1383 USER="$3"
1384 PROPNAME="$4"
1385 ACTION="$5"
1386
1387 %(rules)s
1388
1389 echo "Changing prohibited revision property" >&2
1390 exit 1
1391 '''
1392
1393
1394 def gen_pre_revprop_change_hook(prop_actions_allowed):
1395 rules = []
1396 for action, propname in prop_actions_allowed:
1397 rules.append(
1398 (
1399 b'if [ "$ACTION" = "%s" -a "$PROPNAME" = "%s" ]; '
1400 b'then exit 0; fi'
1401 )
1402 % (action, propname)
1403 )
1404 return pre_revprop_change_template % {b'rules': b'\n'.join(rules)}
1405
1406
1407 class svn_sink(converter_sink, commandline):
1408 commit_re = re.compile(br'Committed revision (\d+).', re.M)
1409 uuid_re = re.compile(br'Repository UUID:\s*(\S+)', re.M)
1410
1411 def prerun(self):
1412 if self.wc:
1413 os.chdir(self.wc)
1414
1415 def postrun(self):
1416 if self.wc:
1417 os.chdir(self.cwd)
1418
1419 def join(self, name):
1420 return os.path.join(self.wc, b'.svn', name)
1421
1422 def revmapfile(self):
1423 return self.join(b'hg-shamap')
1424
1425 def authorfile(self):
1426 return self.join(b'hg-authormap')
1427
1428 def __init__(self, ui, repotype, path):
1429 converter_sink.__init__(self, ui, repotype, path)
1430 commandline.__init__(self, ui, b'svn')
1431 self.delete = []
1432 self.setexec = []
1433 self.delexec = []
1434 self.copies = []
1435 self.wc = None
1436 self.cwd = encoding.getcwd()
1437
1438 created = False
1439 if os.path.isfile(os.path.join(path, b'.svn', b'entries')):
1440 self.wc = os.path.realpath(path)
1441 self.run0(b'update')
1442 else:
1443 if not re.search(br'^(file|http|https|svn|svn\+ssh)://', path):
1444 path = os.path.realpath(path)
1445 if os.path.isdir(os.path.dirname(path)):
1446 if not os.path.exists(
1447 os.path.join(path, b'db', b'fs-type')
1448 ):
1449 ui.status(
1450 _(b"initializing svn repository '%s'\n")
1451 % os.path.basename(path)
1452 )
1453 commandline(ui, b'svnadmin').run0(b'create', path)
1454 created = path
1455 path = util.normpath(path)
1456 if not path.startswith(b'/'):
1457 path = b'/' + path
1458 path = b'file://' + path
1459
1460 wcpath = os.path.join(
1461 encoding.getcwd(), os.path.basename(path) + b'-wc'
1462 )
1463 ui.status(
1464 _(b"initializing svn working copy '%s'\n")
1465 % os.path.basename(wcpath)
1466 )
1467 self.run0(b'checkout', path, wcpath)
1468
1469 self.wc = wcpath
1470 self.opener = vfsmod.vfs(self.wc)
1471 self.wopener = vfsmod.vfs(self.wc)
1472 self.childmap = mapfile(ui, self.join(b'hg-childmap'))
1473 if util.checkexec(self.wc):
1474 self.is_exec = util.isexec
1475 else:
1476 self.is_exec = None
1477
1478 if created:
1479 prop_actions_allowed = [
1480 (b'M', b'svn:log'),
1481 (b'A', b'hg:convert-branch'),
1482 (b'A', b'hg:convert-rev'),
1483 ]
1484
1485 if self.ui.configbool(
1486 b'convert', b'svn.dangerous-set-commit-dates'
1487 ):
1488 prop_actions_allowed.append((b'M', b'svn:date'))
1489
1490 hook = os.path.join(created, b'hooks', b'pre-revprop-change')
1491
1492 util.writefile(
1493 hook, gen_pre_revprop_change_hook(prop_actions_allowed)
1494 )
1495
1496 util.setflags(hook, False, True)
1497
1498 output = self.run0(b'info')
1499 self.uuid = self.uuid_re.search(output).group(1).strip()
1500
1501 def wjoin(self, *names):
1502 return os.path.join(self.wc, *names)
1503
1504 @propertycache
1505 def manifest(self):
1506 # As of svn 1.7, the "add" command fails when receiving
1507 # already tracked entries, so we have to track and filter them
1508 # ourselves.
1509 m = set()
1510 output = self.run0(b'ls', recursive=True, xml=True)
1511 doc = xml.dom.minidom.parseString(output)
1512 for e in doc.getElementsByTagName('entry'):
1513 for n in e.childNodes:
1514 if n.nodeType != n.ELEMENT_NODE or n.tagName != 'name':
1515 continue
1516 name = ''.join(
1517 c.data for c in n.childNodes if c.nodeType == c.TEXT_NODE
1518 )
1519 # Entries are compared with names coming from
1520 # mercurial, so bytes with undefined encoding. Our
1521 # best bet is to assume they are in local
1522 # encoding. They will be passed to command line calls
1523 # later anyway, so they better be.
1524 m.add(encoding.unitolocal(name))
1525 break
1526 return m
1527
1528 def putfile(self, filename, flags, data):
1529 if b'l' in flags:
1530 self.wopener.symlink(data, filename)
1531 else:
1532 try:
1533 if os.path.islink(self.wjoin(filename)):
1534 os.unlink(filename)
1535 except OSError:
1536 pass
1537
1538 if self.is_exec:
1539 # We need to check executability of the file before the change,
1540 # because `vfs.write` is able to reset exec bit.
1541 wasexec = False
1542 if os.path.exists(self.wjoin(filename)):
1543 wasexec = self.is_exec(self.wjoin(filename))
1544
1545 self.wopener.write(filename, data)
1546
1547 if self.is_exec:
1548 if wasexec:
1549 if b'x' not in flags:
1550 self.delexec.append(filename)
1551 else:
1552 if b'x' in flags:
1553 self.setexec.append(filename)
1554 util.setflags(self.wjoin(filename), False, b'x' in flags)
1555
1556 def _copyfile(self, source, dest):
1557 # SVN's copy command pukes if the destination file exists, but
1558 # our copyfile method expects to record a copy that has
1559 # already occurred. Cross the semantic gap.
1560 wdest = self.wjoin(dest)
1561 exists = os.path.lexists(wdest)
1562 if exists:
1563 fd, tempname = pycompat.mkstemp(
1564 prefix=b'hg-copy-', dir=os.path.dirname(wdest)
1565 )
1566 os.close(fd)
1567 os.unlink(tempname)
1568 os.rename(wdest, tempname)
1569 try:
1570 self.run0(b'copy', source, dest)
1571 finally:
1572 self.manifest.add(dest)
1573 if exists:
1574 try:
1575 os.unlink(wdest)
1576 except OSError:
1577 pass
1578 os.rename(tempname, wdest)
1579
1580 def dirs_of(self, files):
1581 dirs = set()
1582 for f in files:
1583 if os.path.isdir(self.wjoin(f)):
1584 dirs.add(f)
1585 i = len(f)
1586 for i in iter(lambda: f.rfind(b'/', 0, i), -1):
1587 dirs.add(f[:i])
1588 return dirs
1589
1590 def add_dirs(self, files):
1591 add_dirs = [
1592 d for d in sorted(self.dirs_of(files)) if d not in self.manifest
1593 ]
1594 if add_dirs:
1595 self.manifest.update(add_dirs)
1596 self.xargs(add_dirs, b'add', non_recursive=True, quiet=True)
1597 return add_dirs
1598
1599 def add_files(self, files):
1600 files = [f for f in files if f not in self.manifest]
1601 if files:
1602 self.manifest.update(files)
1603 self.xargs(files, b'add', quiet=True)
1604 return files
1605
1606 def addchild(self, parent, child):
1607 self.childmap[parent] = child
1608
1609 def revid(self, rev):
1610 return b"svn:%s@%s" % (self.uuid, rev)
1611
1612 def putcommit(
1613 self, files, copies, parents, commit, source, revmap, full, cleanp2
1614 ):
1615 for parent in parents:
1616 try:
1617 return self.revid(self.childmap[parent])
1618 except KeyError:
1619 pass
1620
1621 # Apply changes to working copy
1622 for f, v in files:
1623 data, mode = source.getfile(f, v)
1624 if data is None:
1625 self.delete.append(f)
1626 else:
1627 self.putfile(f, mode, data)
1628 if f in copies:
1629 self.copies.append([copies[f], f])
1630 if full:
1631 self.delete.extend(sorted(self.manifest.difference(files)))
1632 files = [f[0] for f in files]
1633
1634 entries = set(self.delete)
1635 files = frozenset(files)
1636 entries.update(self.add_dirs(files.difference(entries)))
1637 if self.copies:
1638 for s, d in self.copies:
1639 self._copyfile(s, d)
1640 self.copies = []
1641 if self.delete:
1642 self.xargs(self.delete, b'delete')
1643 for f in self.delete:
1644 self.manifest.remove(f)
1645 self.delete = []
1646 entries.update(self.add_files(files.difference(entries)))
1647 if self.delexec:
1648 self.xargs(self.delexec, b'propdel', b'svn:executable')
1649 self.delexec = []
1650 if self.setexec:
1651 self.xargs(self.setexec, b'propset', b'svn:executable', b'*')
1652 self.setexec = []
1653
1654 fd, messagefile = pycompat.mkstemp(prefix=b'hg-convert-')
1655 fp = os.fdopen(fd, 'wb')
1656 fp.write(util.tonativeeol(commit.desc))
1657 fp.close()
1658 try:
1659 output = self.run0(
1660 b'commit',
1661 username=stringutil.shortuser(commit.author),
1662 file=messagefile,
1663 encoding=b'utf-8',
1664 )
1665 try:
1666 rev = self.commit_re.search(output).group(1)
1667 except AttributeError:
1668 if not files:
1669 return parents[0] if parents else b'None'
1670 self.ui.warn(_(b'unexpected svn output:\n'))
1671 self.ui.warn(output)
1672 raise error.Abort(_(b'unable to cope with svn output'))
1673 if commit.rev:
1674 self.run(
1675 b'propset',
1676 b'hg:convert-rev',
1677 commit.rev,
1678 revprop=True,
1679 revision=rev,
1680 )
1681 if commit.branch and commit.branch != b'default':
1682 self.run(
1683 b'propset',
1684 b'hg:convert-branch',
1685 commit.branch,
1686 revprop=True,
1687 revision=rev,
1688 )
1689
1690 if self.ui.configbool(
1691 b'convert', b'svn.dangerous-set-commit-dates'
1692 ):
1693 # Subverson always uses UTC to represent date and time
1694 date = dateutil.parsedate(commit.date)
1695 date = (date[0], 0)
1696
1697 # The only way to set date and time for svn commit is to use propset after commit is done
1698 self.run(
1699 b'propset',
1700 b'svn:date',
1701 formatsvndate(date),
1702 revprop=True,
1703 revision=rev,
1704 )
1705
1706 for parent in parents:
1707 self.addchild(parent, rev)
1708 return self.revid(rev)
1709 finally:
1710 os.unlink(messagefile)
1711
1712 def puttags(self, tags):
1713 self.ui.warn(_(b'writing Subversion tags is not yet implemented\n'))
1714 return None, None
1715
1716 def hascommitfrommap(self, rev):
1717 # We trust that revisions referenced in a map still is present
1718 # TODO: implement something better if necessary and feasible
1719 return True
1720
1721 def hascommitforsplicemap(self, rev):
1722 # This is not correct as one can convert to an existing subversion
1723 # repository and childmap would not list all revisions. Too bad.
1724 if rev in self.childmap:
1725 return True
1726 raise error.Abort(
1727 _(
1728 b'splice map revision %s not found in subversion '
1729 b'child map (revision lookups are not implemented)'
1730 )
1731 % rev
1732 )