Debian Codegraph @

hgext/convert/subversion.py

raw ◀ ▶
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 _(b' (try installing the %s package)') % b'python3-subversion')
483
484 try:
485 version = svn.core.SVN_VER_MAJOR, svn.core.SVN_VER_MINOR
486 if version < (1, 4):
487 raise MissingTool(
488 _(
489 b'Subversion python bindings %d.%d found, '
490 b'1.4 or later required'
491 )
•492 % version +
493 _(b' (try upgrading the %s package)') % b'python-subversion'
494 )
495 except AttributeError:
496 raise MissingTool(
497 _(
498 b'Subversion python bindings are too old, 1.4 '
499 b'or later required'
•500 ) +
501 _(b' (try upgrading the %s package)') % b'python-subversion'
502 )
503
504 self.lastrevs = {}
505
506 latest = None
507 try:
508 # Support file://path@rev syntax. Useful e.g. to convert
509 # deleted branches.
510 at = url.rfind(b'@')
511 if at >= 0:
512 latest = int(url[at + 1 :])
513 url = url[:at]
514 except ValueError:
515 pass
516 self.url = geturl(url)
517 self.encoding = b'UTF-8' # Subversion is always nominal UTF-8
518 try:
519 with util.with_lc_ctype():
520 self.transport = transport.SvnRaTransport(url=self.url)
521 self.ra = self.transport.ra
522 self.ctx = self.transport.client
523 self.baseurl = svn.ra.get_repos_root(self.ra)
524 # Module is either empty or a repository path starting with
525 # a slash and not ending with a slash.
526 self.module = urlreq.unquote(self.url[len(self.baseurl) :])
527 self.prevmodule = None
528 self.rootmodule = self.module
529 self.commits = {}
530 self.paths = {}
531 self.uuid = svn.ra.get_uuid(self.ra)
532 except svn.core.SubversionException:
533 ui.traceback()
534 svnversion = b'%d.%d.%d' % (
535 svn.core.SVN_VER_MAJOR,
536 svn.core.SVN_VER_MINOR,
537 svn.core.SVN_VER_MICRO,
538 )
539 raise NoRepo(
540 _(
541 b"%s does not look like a Subversion repository "
542 b"to libsvn version %s"
543 )
544 % (self.url, svnversion)
545 )
546
547 if revs:
548 if len(revs) > 1:
549 raise error.Abort(
550 _(
551 b'subversion source does not support '
552 b'specifying multiple revisions'
553 )
554 )
555 try:
556 latest = int(revs[0])
557 except ValueError:
558 raise error.Abort(
559 _(b'svn: revision %s is not an integer') % revs[0]
560 )
561
562 trunkcfg = self.ui.config(b'convert', b'svn.trunk')
563 if trunkcfg is None:
564 trunkcfg = b'trunk'
565 self.trunkname = trunkcfg.strip(b'/')
566 self.startrev = self.ui.config(b'convert', b'svn.startrev')
567 try:
568 self.startrev = int(self.startrev)
569 if self.startrev < 0:
570 self.startrev = 0
571 except ValueError:
572 raise error.Abort(
573 _(b'svn: start revision %s is not an integer') % self.startrev
574 )
575
576 try:
577 with util.with_lc_ctype():
578 self.head = self.latest(self.module, latest)
579 except SvnPathNotFound:
580 self.head = None
581 if not self.head:
582 raise error.Abort(
583 _(b'no revision found in module %s') % self.module
584 )
585 self.last_changed = self.revnum(self.head)
586
587 self._changescache = (None, None)
588
589 if os.path.exists(os.path.join(url, b'.svn/entries')):
590 self.wc = url
591 else:
592 self.wc = None
593 self.convertfp = None
594
595 def before(self):
596 self.with_lc_ctype = util.with_lc_ctype()
597 self.with_lc_ctype.__enter__()
598
599 def after(self):
600 self.with_lc_ctype.__exit__(None, None, None)
601
602 def setrevmap(self, revmap):
603 lastrevs = {}
604 for revid in revmap:
605 uuid, module, revnum = revsplit(revid)
606 lastrevnum = lastrevs.setdefault(module, revnum)
607 if revnum > lastrevnum:
608 lastrevs[module] = revnum
609 self.lastrevs = lastrevs
610
611 def exists(self, path, optrev):
612 try:
613 svn.client.ls(
614 self.url.rstrip(b'/') + b'/' + quote(path),
615 optrev,
616 False,
617 self.ctx,
618 )
619 return True
620 except svn.core.SubversionException:
621 return False
622
623 def getheads(self):
624 def isdir(path, revnum):
625 kind = self._checkpath(path, revnum)
626 return kind == svn.core.svn_node_dir
627
628 def getcfgpath(name, rev):
629 cfgpath = self.ui.config(b'convert', b'svn.' + name)
630 if cfgpath is not None and cfgpath.strip() == b'':
631 return None
632 path = (cfgpath or name).strip(b'/')
633 if not self.exists(path, rev):
634 if self.module.endswith(path) and name == b'trunk':
635 # we are converting from inside this directory
636 return None
637 if cfgpath:
638 raise error.Abort(
639 _(b'expected %s to be at %r, but not found')
640 % (name, path)
641 )
642 return None
643 self.ui.note(
644 _(b'found %s at %r\n') % (name, pycompat.bytestr(path))
645 )
646 return path
647
648 rev = optrev(self.last_changed)
649 oldmodule = b''
650 trunk = getcfgpath(b'trunk', rev)
651 self.tags = getcfgpath(b'tags', rev)
652 branches = getcfgpath(b'branches', rev)
653
654 # If the project has a trunk or branches, we will extract heads
655 # from them. We keep the project root otherwise.
656 if trunk:
657 oldmodule = self.module or b''
658 self.module += b'/' + trunk
659 self.head = self.latest(self.module, self.last_changed)
660 if not self.head:
661 raise error.Abort(
662 _(b'no revision found in module %s') % self.module
663 )
664
665 # First head in the list is the module's head
666 self.heads = [self.head]
667 if self.tags is not None:
668 self.tags = b'%s/%s' % (oldmodule, (self.tags or b'tags'))
669
670 # Check if branches bring a few more heads to the list
671 if branches:
672 rpath = self.url.strip(b'/')
673 branchnames = svn.client.ls(
674 rpath + b'/' + quote(branches), rev, False, self.ctx
675 )
676 for branch in sorted(branchnames):
677 module = b'%s/%s/%s' % (oldmodule, branches, branch)
678 if not isdir(module, self.last_changed):
679 continue
680 brevid = self.latest(module, self.last_changed)
681 if not brevid:
682 self.ui.note(_(b'ignoring empty branch %s\n') % branch)
683 continue
684 self.ui.note(
685 _(b'found branch %s at %d\n')
686 % (branch, self.revnum(brevid))
687 )
688 self.heads.append(brevid)
689
690 if self.startrev and self.heads:
691 if len(self.heads) > 1:
692 raise error.Abort(
693 _(
694 b'svn: start revision is not supported '
695 b'with more than one branch'
696 )
697 )
698 revnum = self.revnum(self.heads[0])
699 if revnum < self.startrev:
700 raise error.Abort(
701 _(b'svn: no revision found after start revision %d')
702 % self.startrev
703 )
704
705 return self.heads
706
707 def _getchanges(self, rev, full):
708 (paths, parents) = self.paths[rev]
709 copies = {}
710 if parents:
711 files, self.removed, copies = self.expandpaths(rev, paths, parents)
712 if full or not parents:
713 # Perform a full checkout on roots
714 uuid, module, revnum = revsplit(rev)
715 entries = svn.client.ls(
716 self.baseurl + quote(module), optrev(revnum), True, self.ctx
717 )
718 files = [
719 n
720 for n, e in entries.items()
721 if e.kind == svn.core.svn_node_file
722 ]
723 self.removed = set()
724
725 files.sort()
726 files = pycompat.ziplist(files, [rev] * len(files))
727 return (files, copies)
728
729 def getchanges(self, rev, full):
730 # reuse cache from getchangedfiles
731 if self._changescache[0] == rev and not full:
732 # TODO: add type hints to avoid this warning, instead of
733 # suppressing it:
734 # No attribute '__iter__' on None [attribute-error]
735
736 # pytype: disable=attribute-error
737 (files, copies) = self._changescache[1]
738 # pytype: enable=attribute-error
739 else:
740 (files, copies) = self._getchanges(rev, full)
741 # caller caches the result, so free it here to release memory
742 del self.paths[rev]
743 return (files, copies, set())
744
745 def getchangedfiles(self, rev, i):
746 # called from filemap - cache computed values for reuse in getchanges
747 (files, copies) = self._getchanges(rev, False)
748 self._changescache = (rev, (files, copies))
749 return [f[0] for f in files]
750
751 def getcommit(self, rev):
752 if rev not in self.commits:
753 uuid, module, revnum = revsplit(rev)
754 self.module = module
755 self.reparent(module)
756 # We assume that:
757 # - requests for revisions after "stop" come from the
758 # revision graph backward traversal. Cache all of them
759 # down to stop, they will be used eventually.
760 # - requests for revisions before "stop" come to get
761 # isolated branches parents. Just fetch what is needed.
762 stop = self.lastrevs.get(module, 0)
763 if revnum < stop:
764 stop = revnum + 1
765 self._fetch_revisions(revnum, stop)
766 if rev not in self.commits:
767 raise error.Abort(_(b'svn: revision %s not found') % revnum)
768 revcommit = self.commits[rev]
769 # caller caches the result, so free it here to release memory
770 del self.commits[rev]
771 return revcommit
772
773 def checkrevformat(self, revstr, mapname=b'splicemap'):
774 """fails if revision format does not match the correct format"""
775 if not re.match(
776 br'svn:[0-9a-f]{8,8}-[0-9a-f]{4,4}-'
777 br'[0-9a-f]{4,4}-[0-9a-f]{4,4}-[0-9a-f]'
778 br'{12,12}(.*)@[0-9]+$',
779 revstr,
780 ):
781 raise error.Abort(
782 _(b'%s entry %s is not a valid revision identifier')
783 % (mapname, revstr)
784 )
785
786 def numcommits(self):
787 return int(self.head.rsplit(b'@', 1)[1]) - self.startrev
788
789 def gettags(self):
790 tags = {}
791 if self.tags is None:
792 return tags
793
794 # svn tags are just a convention, project branches left in a
795 # 'tags' directory. There is no other relationship than
796 # ancestry, which is expensive to discover and makes them hard
797 # to update incrementally. Worse, past revisions may be
798 # referenced by tags far away in the future, requiring a deep
799 # history traversal on every calculation. Current code
800 # performs a single backward traversal, tracking moves within
801 # the tags directory (tag renaming) and recording a new tag
802 # everytime a project is copied from outside the tags
803 # directory. It also lists deleted tags, this behaviour may
804 # change in the future.
805 pendings = []
806 tagspath = self.tags
807 start = svn.ra.get_latest_revnum(self.ra)
808 stream = self._getlog([self.tags], start, self.startrev)
809 try:
810 for entry in stream:
811 origpaths, revnum, author, date, message = entry
812 if not origpaths:
813 origpaths = []
814 copies = [
815 (e.copyfrom_path, e.copyfrom_rev, p)
816 for p, e in origpaths.items()
817 if e.copyfrom_path
818 ]
819 # Apply moves/copies from more specific to general
820 copies.sort(reverse=True)
821
822 srctagspath = tagspath
823 if copies and copies[-1][2] == tagspath:
824 # Track tags directory moves
825 srctagspath = copies.pop()[0]
826
827 for source, sourcerev, dest in copies:
828 if not dest.startswith(tagspath + b'/'):
829 continue
830 for tag in pendings:
831 if tag[0].startswith(dest):
832 tagpath = source + tag[0][len(dest) :]
833 tag[:2] = [tagpath, sourcerev]
834 break
835 else:
836 pendings.append([source, sourcerev, dest])
837
838 # Filter out tags with children coming from different
839 # parts of the repository like:
840 # /tags/tag.1 (from /trunk:10)
841 # /tags/tag.1/foo (from /branches/foo:12)
842 # Here/tags/tag.1 discarded as well as its children.
843 # It happens with tools like cvs2svn. Such tags cannot
844 # be represented in mercurial.
845 addeds = {
846 p: e.copyfrom_path
847 for p, e in origpaths.items()
848 if e.action == b'A' and e.copyfrom_path
849 }
850 badroots = set()
851 for destroot in addeds:
852 for source, sourcerev, dest in pendings:
853 if not dest.startswith(
854 destroot + b'/'
855 ) or source.startswith(addeds[destroot] + b'/'):
856 continue
857 badroots.add(destroot)
858 break
859
860 for badroot in badroots:
861 pendings = [
862 p
863 for p in pendings
864 if p[2] != badroot
865 and not p[2].startswith(badroot + b'/')
866 ]
867
868 # Tell tag renamings from tag creations
869 renamings = []
870 for source, sourcerev, dest in pendings:
871 tagname = dest.split(b'/')[-1]
872 if source.startswith(srctagspath):
873 renamings.append([source, sourcerev, tagname])
874 continue
875 if tagname in tags:
876 # Keep the latest tag value
877 continue
878 # From revision may be fake, get one with changes
879 try:
880 tagid = self.latest(source, sourcerev)
881 if tagid and tagname not in tags:
882 tags[tagname] = tagid
883 except SvnPathNotFound:
884 # It happens when we are following directories
885 # we assumed were copied with their parents
886 # but were really created in the tag
887 # directory.
888 pass
889 pendings = renamings
890 tagspath = srctagspath
891 finally:
892 stream.close()
893 return tags
894
895 def converted(self, rev, destrev):
896 if not self.wc:
897 return
898 if self.convertfp is None:
899 self.convertfp = open(
900 os.path.join(self.wc, b'.svn', b'hg-shamap'), 'ab'
901 )
902 self.convertfp.write(
903 util.tonativeeol(b'%s %d\n' % (destrev, self.revnum(rev)))
904 )
905 self.convertfp.flush()
906
907 def revid(self, revnum, module=None):
908 return b'svn:%s%s@%d' % (self.uuid, module or self.module, revnum)
909
910 def revnum(self, rev):
911 return int(rev.split(b'@')[-1])
912
913 def latest(self, path, stop=None):
914 """Find the latest revid affecting path, up to stop revision
915 number. If stop is None, default to repository latest
916 revision. It may return a revision in a different module,
917 since a branch may be moved without a change being
918 reported. Return None if computed module does not belong to
919 rootmodule subtree.
920 """
921
922 def findchanges(path, start, stop=None):
923 stream = self._getlog([path], start, stop or 1)
924 try:
925 for entry in stream:
926 paths, revnum, author, date, message = entry
927 if stop is None and paths:
928 # We do not know the latest changed revision,
929 # keep the first one with changed paths.
930 break
931 if stop is not None and revnum <= stop:
932 break
933
934 for p in paths:
935 if not path.startswith(p) or not paths[p].copyfrom_path:
936 continue
937 newpath = paths[p].copyfrom_path + path[len(p) :]
938 self.ui.debug(
939 b"branch renamed from %s to %s at %d\n"
940 % (path, newpath, revnum)
941 )
942 path = newpath
943 break
944 if not paths:
945 revnum = None
946 return revnum, path
947 finally:
948 stream.close()
949
950 if not path.startswith(self.rootmodule):
951 # Requests on foreign branches may be forbidden at server level
952 self.ui.debug(b'ignoring foreign branch %r\n' % path)
953 return None
954
955 if stop is None:
956 stop = svn.ra.get_latest_revnum(self.ra)
957 try:
958 prevmodule = self.reparent(b'')
959 dirent = svn.ra.stat(self.ra, path.strip(b'/'), stop)
960 self.reparent(prevmodule)
961 except svn.core.SubversionException:
962 dirent = None
963 if not dirent:
964 raise SvnPathNotFound(
965 _(b'%s not found up to revision %d') % (path, stop)
966 )
967
968 # stat() gives us the previous revision on this line of
969 # development, but it might be in *another module*. Fetch the
970 # log and detect renames down to the latest revision.
971 revnum, realpath = findchanges(path, stop, dirent.created_rev)
972 if revnum is None:
973 # Tools like svnsync can create empty revision, when
974 # synchronizing only a subtree for instance. These empty
975 # revisions created_rev still have their original values
976 # despite all changes having disappeared and can be
977 # returned by ra.stat(), at least when stating the root
978 # module. In that case, do not trust created_rev and scan
979 # the whole history.
980 revnum, realpath = findchanges(path, stop)
981 if revnum is None:
982 self.ui.debug(b'ignoring empty branch %r\n' % realpath)
983 return None
984
985 if not realpath.startswith(self.rootmodule):
986 self.ui.debug(b'ignoring foreign branch %r\n' % realpath)
987 return None
988 return self.revid(revnum, realpath)
989
990 def reparent(self, module):
991 """Reparent the svn transport and return the previous parent."""
992 if self.prevmodule == module:
993 return module
994 svnurl = self.baseurl + quote(module)
995 prevmodule = self.prevmodule
996 if prevmodule is None:
997 prevmodule = b''
998 self.ui.debug(b"reparent to %s\n" % svnurl)
999 svn.ra.reparent(self.ra, svnurl)
1000 self.prevmodule = module
1001 return prevmodule
1002
1003 def expandpaths(self, rev, paths, parents):
1004 changed, removed = set(), set()
1005 copies = {}
1006
1007 new_module, revnum = revsplit(rev)[1:]
1008 if new_module != self.module:
1009 self.module = new_module
1010 self.reparent(self.module)
1011
1012 progress = self.ui.makeprogress(
1013 _(b'scanning paths'), unit=_(b'paths'), total=len(paths)
1014 )
1015 for i, (path, ent) in enumerate(paths):
1016 progress.update(i, item=path)
1017 entrypath = self.getrelpath(path)
1018
1019 kind = self._checkpath(entrypath, revnum)
1020 if kind == svn.core.svn_node_file:
1021 changed.add(self.recode(entrypath))
1022 if not ent.copyfrom_path or not parents:
1023 continue
1024 # Copy sources not in parent revisions cannot be
1025 # represented, ignore their origin for now
1026 pmodule, prevnum = revsplit(parents[0])[1:]
1027 if ent.copyfrom_rev < prevnum:
1028 continue
1029 copyfrom_path = self.getrelpath(ent.copyfrom_path, pmodule)
1030 if not copyfrom_path:
1031 continue
1032 self.ui.debug(
1033 b"copied to %s from %s@%d\n"
1034 % (entrypath, copyfrom_path, ent.copyfrom_rev)
1035 )
1036 copies[self.recode(entrypath)] = self.recode(copyfrom_path)
1037 elif kind == 0: # gone, but had better be a deleted *file*
1038 self.ui.debug(b"gone from %d\n" % ent.copyfrom_rev)
1039 pmodule, prevnum = revsplit(parents[0])[1:]
1040 parentpath = pmodule + b"/" + entrypath
1041 fromkind = self._checkpath(entrypath, prevnum, pmodule)
1042
1043 if fromkind == svn.core.svn_node_file:
1044 removed.add(self.recode(entrypath))
1045 elif fromkind == svn.core.svn_node_dir:
1046 oroot = parentpath.strip(b'/')
1047 nroot = path.strip(b'/')
1048 children = self._iterfiles(oroot, prevnum)
1049 for childpath in children:
1050 childpath = childpath.replace(oroot, nroot)
1051 childpath = self.getrelpath(b"/" + childpath, pmodule)
1052 if childpath:
1053 removed.add(self.recode(childpath))
1054 else:
1055 self.ui.debug(
1056 b'unknown path in revision %d: %s\n' % (revnum, path)
1057 )
1058 elif kind == svn.core.svn_node_dir:
1059 if ent.action == b'M':
1060 # If the directory just had a prop change,
1061 # then we shouldn't need to look for its children.
1062 continue
1063 if ent.action == b'R' and parents:
1064 # If a directory is replacing a file, mark the previous
1065 # file as deleted
1066 pmodule, prevnum = revsplit(parents[0])[1:]
1067 pkind = self._checkpath(entrypath, prevnum, pmodule)
1068 if pkind == svn.core.svn_node_file:
1069 removed.add(self.recode(entrypath))
1070 elif pkind == svn.core.svn_node_dir:
1071 # We do not know what files were kept or removed,
1072 # mark them all as changed.
1073 for childpath in self._iterfiles(pmodule, prevnum):
1074 childpath = self.getrelpath(b"/" + childpath)
1075 if childpath:
1076 changed.add(self.recode(childpath))
1077
1078 for childpath in self._iterfiles(path, revnum):
1079 childpath = self.getrelpath(b"/" + childpath)
1080 if childpath:
1081 changed.add(self.recode(childpath))
1082
1083 # Handle directory copies
1084 if not ent.copyfrom_path or not parents:
1085 continue
1086 # Copy sources not in parent revisions cannot be
1087 # represented, ignore their origin for now
1088 pmodule, prevnum = revsplit(parents[0])[1:]
1089 if ent.copyfrom_rev < prevnum:
1090 continue
1091 copyfrompath = self.getrelpath(ent.copyfrom_path, pmodule)
1092 if not copyfrompath:
1093 continue
1094 self.ui.debug(
1095 b"mark %s came from %s:%d\n"
1096 % (path, copyfrompath, ent.copyfrom_rev)
1097 )
1098 children = self._iterfiles(ent.copyfrom_path, ent.copyfrom_rev)
1099 for childpath in children:
1100 childpath = self.getrelpath(b"/" + childpath, pmodule)
1101 if not childpath:
1102 continue
1103 copytopath = path + childpath[len(copyfrompath) :]
1104 copytopath = self.getrelpath(copytopath)
1105 copies[self.recode(copytopath)] = self.recode(childpath)
1106
1107 progress.complete()
1108 changed.update(removed)
1109 return (list(changed), removed, copies)
1110
1111 def _fetch_revisions(self, from_revnum, to_revnum):
1112 if from_revnum < to_revnum:
1113 from_revnum, to_revnum = to_revnum, from_revnum
1114
1115 self.child_cset = None
1116
1117 def parselogentry(orig_paths, revnum, author, date, message):
1118 """Return the parsed commit object or None, and True if
1119 the revision is a branch root.
1120 """
1121 self.ui.debug(
1122 b"parsing revision %d (%d changes)\n"
1123 % (revnum, len(orig_paths))
1124 )
1125
1126 branched = False
1127 rev = self.revid(revnum)
1128 # branch log might return entries for a parent we already have
1129
1130 if rev in self.commits or revnum < to_revnum:
1131 return None, branched
1132
1133 parents = []
1134 # check whether this revision is the start of a branch or part
1135 # of a branch renaming
1136 orig_paths = sorted(orig_paths.items())
1137 root_paths = [
1138 (p, e) for p, e in orig_paths if self.module.startswith(p)
1139 ]
1140 if root_paths:
1141 path, ent = root_paths[-1]
1142 if ent.copyfrom_path:
1143 branched = True
1144 newpath = ent.copyfrom_path + self.module[len(path) :]
1145 # ent.copyfrom_rev may not be the actual last revision
1146 previd = self.latest(newpath, ent.copyfrom_rev)
1147 if previd is not None:
1148 prevmodule, prevnum = revsplit(previd)[1:]
1149 if prevnum >= self.startrev:
1150 parents = [previd]
1151 self.ui.note(
1152 _(b'found parent of branch %s at %d: %s\n')
1153 % (self.module, prevnum, prevmodule)
1154 )
1155 else:
1156 self.ui.debug(b"no copyfrom path, don't know what to do.\n")
1157
1158 paths = []
1159 # filter out unrelated paths
1160 for path, ent in orig_paths:
1161 if self.getrelpath(path) is None:
1162 continue
1163 paths.append((path, ent))
1164
1165 date = parsesvndate(date)
1166 if self.ui.configbool(b'convert', b'localtimezone'):
1167 date = makedatetimestamp(date[0])
1168
1169 if message:
1170 log = self.recode(message)
1171 else:
1172 log = b''
1173
1174 if author:
1175 author = self.recode(author)
1176 else:
1177 author = b''
1178
1179 try:
1180 branch = self.module.split(b"/")[-1]
1181 if branch == self.trunkname:
1182 branch = None
1183 except IndexError:
1184 branch = None
1185
1186 cset = commit(
1187 author=author,
1188 date=dateutil.datestr(date, b'%Y-%m-%d %H:%M:%S %1%2'),
1189 desc=log,
1190 parents=parents,
1191 branch=branch,
1192 rev=rev,
1193 )
1194
1195 self.commits[rev] = cset
1196 # The parents list is *shared* among self.paths and the
1197 # commit object. Both will be updated below.
1198 self.paths[rev] = (paths, cset.parents)
1199 if self.child_cset and not self.child_cset.parents:
1200 self.child_cset.parents[:] = [rev]
1201 self.child_cset = cset
1202 return cset, branched
1203
1204 self.ui.note(
1205 _(b'fetching revision log for "%s" from %d to %d\n')
1206 % (self.module, from_revnum, to_revnum)
1207 )
1208
1209 try:
1210 firstcset = None
1211 lastonbranch = False
1212 stream = self._getlog([self.module], from_revnum, to_revnum)
1213 try:
1214 for entry in stream:
1215 paths, revnum, author, date, message = entry
1216 if revnum < self.startrev:
1217 lastonbranch = True
1218 break
1219 if not paths:
1220 self.ui.debug(b'revision %d has no entries\n' % revnum)
1221 # If we ever leave the loop on an empty
1222 # revision, do not try to get a parent branch
1223 lastonbranch = lastonbranch or revnum == 0
1224 continue
1225 cset, lastonbranch = parselogentry(
1226 paths, revnum, author, date, message
1227 )
1228 if cset:
1229 firstcset = cset
1230 if lastonbranch:
1231 break
1232 finally:
1233 stream.close()
1234
1235 if not lastonbranch and firstcset and not firstcset.parents:
1236 # The first revision of the sequence (the last fetched one)
1237 # has invalid parents if not a branch root. Find the parent
1238 # revision now, if any.
1239 try:
1240 firstrevnum = self.revnum(firstcset.rev)
1241 if firstrevnum > 1:
1242 latest = self.latest(self.module, firstrevnum - 1)
1243 if latest:
1244 firstcset.parents.append(latest)
1245 except SvnPathNotFound:
1246 pass
1247 except svn.core.SubversionException as xxx_todo_changeme:
1248 (inst, num) = xxx_todo_changeme.args
1249 if num == svn.core.SVN_ERR_FS_NO_SUCH_REVISION:
1250 raise error.Abort(
1251 _(b'svn: branch has no revision %s') % to_revnum
1252 )
1253 raise
1254
1255 def getfile(self, file, rev):
1256 # TODO: ra.get_file transmits the whole file instead of diffs.
1257 if file in self.removed:
1258 return None, None
1259 try:
1260 new_module, revnum = revsplit(rev)[1:]
1261 if self.module != new_module:
1262 self.module = new_module
1263 self.reparent(self.module)
1264 io = stringio()
1265 info = svn.ra.get_file(self.ra, file, revnum, io)
1266 data = io.getvalue()
1267 # ra.get_file() seems to keep a reference on the input buffer
1268 # preventing collection. Release it explicitly.
1269 io.close()
1270 if isinstance(info, list):
1271 info = info[-1]
1272 mode = (b"svn:executable" in info) and b'x' or b''
1273 mode = (b"svn:special" in info) and b'l' or mode
1274 except svn.core.SubversionException as e:
1275 notfound = (
1276 svn.core.SVN_ERR_FS_NOT_FOUND,
1277 svn.core.SVN_ERR_RA_DAV_PATH_NOT_FOUND,
1278 )
1279 if e.apr_err in notfound: # File not found
1280 return None, None
1281 raise
1282 if mode == b'l':
1283 link_prefix = b"link "
1284 if data.startswith(link_prefix):
1285 data = data[len(link_prefix) :]
1286 return data, mode
1287
1288 def _iterfiles(self, path, revnum):
1289 """Enumerate all files in path at revnum, recursively."""
1290 path = path.strip(b'/')
1291 pool = svn.core.Pool()
1292 rpath = b'/'.join([self.baseurl, quote(path)]).strip(b'/')
1293 entries = svn.client.ls(rpath, optrev(revnum), True, self.ctx, pool)
1294 if path:
1295 path += b'/'
1296 return (
1297 (path + p)
1298 for p, e in entries.items()
1299 if e.kind == svn.core.svn_node_file
1300 )
1301
1302 def getrelpath(self, path, module=None):
1303 if module is None:
1304 module = self.module
1305 # Given the repository url of this wc, say
1306 # "http://server/plone/CMFPlone/branches/Plone-2_0-branch"
1307 # extract the "entry" portion (a relative path) from what
1308 # svn log --xml says, i.e.
1309 # "/CMFPlone/branches/Plone-2_0-branch/tests/PloneTestCase.py"
1310 # that is to say "tests/PloneTestCase.py"
1311 if path.startswith(module):
1312 relative = path.rstrip(b'/')[len(module) :]
1313 if relative.startswith(b'/'):
1314 return relative[1:]
1315 elif relative == b'':
1316 return relative
1317
1318 # The path is outside our tracked tree...
1319 self.ui.debug(
1320 b'%r is not under %r, ignoring\n'
1321 % (pycompat.bytestr(path), pycompat.bytestr(module))
1322 )
1323 return None
1324
1325 def _checkpath(self, path, revnum, module=None):
1326 if module is not None:
1327 prevmodule = self.reparent(b'')
1328 path = module + b'/' + path
1329 try:
1330 # ra.check_path does not like leading slashes very much, it leads
1331 # to PROPFIND subversion errors
1332 return svn.ra.check_path(self.ra, path.strip(b'/'), revnum)
1333 finally:
1334 if module is not None:
1335 self.reparent(prevmodule)
1336
1337 def _getlog(
1338 self,
1339 paths,
1340 start,
1341 end,
1342 limit=0,
1343 discover_changed_paths=True,
1344 strict_node_history=False,
1345 ):
1346 # Normalize path names, svn >= 1.5 only wants paths relative to
1347 # supplied URL
1348 relpaths = []
1349 for p in paths:
1350 if not p.startswith(b'/'):
1351 p = self.module + b'/' + p
1352 relpaths.append(p.strip(b'/'))
1353 args = [
1354 self.baseurl,
1355 relpaths,
1356 start,
1357 end,
1358 limit,
1359 discover_changed_paths,
1360 strict_node_history,
1361 ]
1362 # developer config: convert.svn.debugsvnlog
1363 if not self.ui.configbool(b'convert', b'svn.debugsvnlog'):
1364 return directlogstream(*args)
1365 arg = encodeargs(args)
1366 hgexe = procutil.hgexecutable()
1367 cmd = b'%s debugsvnlog' % procutil.shellquote(hgexe)
1368 stdin, stdout = procutil.popen2(cmd)
1369 stdin.write(arg)
1370 try:
1371 stdin.close()
1372 except OSError:
1373 raise error.Abort(
1374 _(
1375 b'Mercurial failed to run itself, check'
1376 b' hg executable is in PATH'
1377 )
1378 )
1379 return logstream(stdout)
1380
1381
1382 pre_revprop_change_template = b'''#!/bin/sh
1383
1384 REPOS="$1"
1385 REV="$2"
1386 USER="$3"
1387 PROPNAME="$4"
1388 ACTION="$5"
1389
1390 %(rules)s
1391
1392 echo "Changing prohibited revision property" >&2
1393 exit 1
1394 '''
1395
1396
1397 def gen_pre_revprop_change_hook(prop_actions_allowed):
1398 rules = []
1399 for action, propname in prop_actions_allowed:
1400 rules.append(
1401 (
1402 b'if [ "$ACTION" = "%s" -a "$PROPNAME" = "%s" ]; '
1403 b'then exit 0; fi'
1404 )
1405 % (action, propname)
1406 )
1407 return pre_revprop_change_template % {b'rules': b'\n'.join(rules)}
1408
1409
1410 class svn_sink(converter_sink, commandline):
1411 commit_re = re.compile(br'Committed revision (\d+).', re.M)
1412 uuid_re = re.compile(br'Repository UUID:\s*(\S+)', re.M)
1413
1414 def prerun(self):
1415 if self.wc:
1416 os.chdir(self.wc)
1417
1418 def postrun(self):
1419 if self.wc:
1420 os.chdir(self.cwd)
1421
1422 def join(self, name):
1423 return os.path.join(self.wc, b'.svn', name)
1424
1425 def revmapfile(self):
1426 return self.join(b'hg-shamap')
1427
1428 def authorfile(self):
1429 return self.join(b'hg-authormap')
1430
1431 def __init__(self, ui, repotype, path):
•1432 common.checktool(b'svn', debname=b'subversion')
1433 common.checktool(b'svnadmin', debname=b'subversion')
1434
1435 converter_sink.__init__(self, ui, repotype, path)
1436 commandline.__init__(self, ui, b'svn')
1437 self.delete = []
1438 self.setexec = []
1439 self.delexec = []
1440 self.copies = []
1441 self.wc = None
1442 self.cwd = encoding.getcwd()
1443
1444 created = False
1445 if os.path.isfile(os.path.join(path, b'.svn', b'entries')):
1446 self.wc = os.path.realpath(path)
1447 self.run0(b'update')
1448 else:
1449 if not re.search(br'^(file|http|https|svn|svn\+ssh)://', path):
1450 path = os.path.realpath(path)
1451 if os.path.isdir(os.path.dirname(path)):
1452 if not os.path.exists(
1453 os.path.join(path, b'db', b'fs-type')
1454 ):
1455 ui.status(
1456 _(b"initializing svn repository '%s'\n")
1457 % os.path.basename(path)
1458 )
1459 commandline(ui, b'svnadmin').run0(b'create', path)
1460 created = path
1461 path = util.normpath(path)
1462 if not path.startswith(b'/'):
1463 path = b'/' + path
1464 path = b'file://' + path
1465
1466 wcpath = os.path.join(
1467 encoding.getcwd(), os.path.basename(path) + b'-wc'
1468 )
1469 ui.status(
1470 _(b"initializing svn working copy '%s'\n")
1471 % os.path.basename(wcpath)
1472 )
1473 self.run0(b'checkout', path, wcpath)
1474
1475 self.wc = wcpath
1476 self.opener = vfsmod.vfs(self.wc)
1477 self.wopener = vfsmod.vfs(self.wc)
1478 self.childmap = mapfile(ui, self.join(b'hg-childmap'))
1479 if util.checkexec(self.wc):
1480 self.is_exec = util.isexec
1481 else:
1482 self.is_exec = None
1483
1484 if created:
1485 prop_actions_allowed = [
1486 (b'M', b'svn:log'),
1487 (b'A', b'hg:convert-branch'),
1488 (b'A', b'hg:convert-rev'),
1489 ]
1490
1491 if self.ui.configbool(
1492 b'convert', b'svn.dangerous-set-commit-dates'
1493 ):
1494 prop_actions_allowed.append((b'M', b'svn:date'))
1495
1496 hook = os.path.join(created, b'hooks', b'pre-revprop-change')
1497
1498 util.writefile(
1499 hook, gen_pre_revprop_change_hook(prop_actions_allowed)
1500 )
1501
1502 util.setflags(hook, False, True)
1503
1504 output = self.run0(b'info')
1505 self.uuid = self.uuid_re.search(output).group(1).strip()
1506
1507 def wjoin(self, *names):
1508 return os.path.join(self.wc, *names)
1509
1510 @propertycache
1511 def manifest(self):
1512 # As of svn 1.7, the "add" command fails when receiving
1513 # already tracked entries, so we have to track and filter them
1514 # ourselves.
1515 m = set()
1516 output = self.run0(b'ls', recursive=True, xml=True)
1517 doc = xml.dom.minidom.parseString(output)
1518 for e in doc.getElementsByTagName('entry'):
1519 for n in e.childNodes:
1520 if n.nodeType != n.ELEMENT_NODE or n.tagName != 'name':
1521 continue
1522 name = ''.join(
1523 c.data for c in n.childNodes if c.nodeType == c.TEXT_NODE
1524 )
1525 # Entries are compared with names coming from
1526 # mercurial, so bytes with undefined encoding. Our
1527 # best bet is to assume they are in local
1528 # encoding. They will be passed to command line calls
1529 # later anyway, so they better be.
1530 m.add(encoding.unitolocal(name))
1531 break
1532 return m
1533
1534 def putfile(self, filename, flags, data):
1535 if b'l' in flags:
1536 self.wopener.symlink(data, filename)
1537 else:
1538 try:
1539 if os.path.islink(self.wjoin(filename)):
1540 os.unlink(filename)
1541 except OSError:
1542 pass
1543
1544 if self.is_exec:
1545 # We need to check executability of the file before the change,
1546 # because `vfs.write` is able to reset exec bit.
1547 wasexec = False
1548 if os.path.exists(self.wjoin(filename)):
1549 wasexec = self.is_exec(self.wjoin(filename))
1550
1551 self.wopener.write(filename, data)
1552
1553 if self.is_exec:
1554 if wasexec:
1555 if b'x' not in flags:
1556 self.delexec.append(filename)
1557 else:
1558 if b'x' in flags:
1559 self.setexec.append(filename)
1560 util.setflags(self.wjoin(filename), False, b'x' in flags)
1561
1562 def _copyfile(self, source, dest):
1563 # SVN's copy command pukes if the destination file exists, but
1564 # our copyfile method expects to record a copy that has
1565 # already occurred. Cross the semantic gap.
1566 wdest = self.wjoin(dest)
1567 exists = os.path.lexists(wdest)
1568 if exists:
1569 fd, tempname = pycompat.mkstemp(
1570 prefix=b'hg-copy-', dir=os.path.dirname(wdest)
1571 )
1572 os.close(fd)
1573 os.unlink(tempname)
1574 os.rename(wdest, tempname)
1575 try:
1576 self.run0(b'copy', source, dest)
1577 finally:
1578 self.manifest.add(dest)
1579 if exists:
1580 try:
1581 os.unlink(wdest)
1582 except OSError:
1583 pass
1584 os.rename(tempname, wdest)
1585
1586 def dirs_of(self, files):
1587 dirs = set()
1588 for f in files:
1589 if os.path.isdir(self.wjoin(f)):
1590 dirs.add(f)
1591 i = len(f)
1592 for i in iter(lambda: f.rfind(b'/', 0, i), -1):
1593 dirs.add(f[:i])
1594 return dirs
1595
1596 def add_dirs(self, files):
1597 add_dirs = [
1598 d for d in sorted(self.dirs_of(files)) if d not in self.manifest
1599 ]
1600 if add_dirs:
1601 self.manifest.update(add_dirs)
1602 self.xargs(add_dirs, b'add', non_recursive=True, quiet=True)
1603 return add_dirs
1604
1605 def add_files(self, files):
1606 files = [f for f in files if f not in self.manifest]
1607 if files:
1608 self.manifest.update(files)
1609 self.xargs(files, b'add', quiet=True)
1610 return files
1611
1612 def addchild(self, parent, child):
1613 self.childmap[parent] = child
1614
1615 def revid(self, rev):
1616 return b"svn:%s@%s" % (self.uuid, rev)
1617
1618 def putcommit(
1619 self, files, copies, parents, commit, source, revmap, full, cleanp2
1620 ):
1621 for parent in parents:
1622 try:
1623 return self.revid(self.childmap[parent])
1624 except KeyError:
1625 pass
1626
1627 # Apply changes to working copy
1628 for f, v in files:
1629 data, mode = source.getfile(f, v)
1630 if data is None:
1631 self.delete.append(f)
1632 else:
1633 self.putfile(f, mode, data)
1634 if f in copies:
1635 self.copies.append([copies[f], f])
1636 if full:
1637 self.delete.extend(sorted(self.manifest.difference(files)))
1638 files = [f[0] for f in files]
1639
1640 entries = set(self.delete)
1641 files = frozenset(files)
1642 entries.update(self.add_dirs(files.difference(entries)))
1643 if self.copies:
1644 for s, d in self.copies:
1645 self._copyfile(s, d)
1646 self.copies = []
1647 if self.delete:
1648 self.xargs(self.delete, b'delete')
1649 for f in self.delete:
1650 self.manifest.remove(f)
1651 self.delete = []
1652 entries.update(self.add_files(files.difference(entries)))
1653 if self.delexec:
1654 self.xargs(self.delexec, b'propdel', b'svn:executable')
1655 self.delexec = []
1656 if self.setexec:
1657 self.xargs(self.setexec, b'propset', b'svn:executable', b'*')
1658 self.setexec = []
1659
1660 fd, messagefile = pycompat.mkstemp(prefix=b'hg-convert-')
1661 fp = os.fdopen(fd, 'wb')
1662 fp.write(util.tonativeeol(commit.desc))
1663 fp.close()
1664 try:
1665 output = self.run0(
1666 b'commit',
1667 username=stringutil.shortuser(commit.author),
1668 file=messagefile,
1669 encoding=b'utf-8',
1670 )
1671 try:
1672 rev = self.commit_re.search(output).group(1)
1673 except AttributeError:
1674 if not files:
1675 return parents[0] if parents else b'None'
1676 self.ui.warn(_(b'unexpected svn output:\n'))
1677 self.ui.warn(output)
1678 raise error.Abort(_(b'unable to cope with svn output'))
1679 if commit.rev:
1680 self.run(
1681 b'propset',
1682 b'hg:convert-rev',
1683 commit.rev,
1684 revprop=True,
1685 revision=rev,
1686 )
1687 if commit.branch and commit.branch != b'default':
1688 self.run(
1689 b'propset',
1690 b'hg:convert-branch',
1691 commit.branch,
1692 revprop=True,
1693 revision=rev,
1694 )
1695
1696 if self.ui.configbool(
1697 b'convert', b'svn.dangerous-set-commit-dates'
1698 ):
1699 # Subverson always uses UTC to represent date and time
1700 date = dateutil.parsedate(commit.date)
1701 date = (date[0], 0)
1702
1703 # The only way to set date and time for svn commit is to use propset after commit is done
1704 self.run(
1705 b'propset',
1706 b'svn:date',
1707 formatsvndate(date),
1708 revprop=True,
1709 revision=rev,
1710 )
1711
1712 for parent in parents:
1713 self.addchild(parent, rev)
1714 return self.revid(rev)
1715 finally:
1716 os.unlink(messagefile)
1717
1718 def puttags(self, tags):
1719 self.ui.warn(_(b'writing Subversion tags is not yet implemented\n'))
1720 return None, None
1721
1722 def hascommitfrommap(self, rev):
1723 # We trust that revisions referenced in a map still is present
1724 # TODO: implement something better if necessary and feasible
1725 return True
1726
1727 def hascommitforsplicemap(self, rev):
1728 # This is not correct as one can convert to an existing subversion
1729 # repository and childmap would not list all revisions. Too bad.
1730 if rev in self.childmap:
1731 return True
1732 raise error.Abort(
1733 _(
1734 b'splice map revision %s not found in subversion '
1735 b'child map (revision lookups are not implemented)'
1736 )
1737 % rev
1738 )