Debian Codegraph @

hgext/convert/cvsps.py

raw
1 # Mercurial built-in replacement for cvsps.
2 #
3 # Copyright 2008, Frank Kingswood <[email protected]>
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 from __future__ import annotations
9
10 import functools
11 import os
12 import pickle
13 import re
14
15 from mercurial.i18n import _
16 from mercurial import (
17 encoding,
18 error,
19 hook,
20 pycompat,
21 util,
22 )
23 from mercurial.utils import (
24 dateutil,
25 procutil,
26 stringutil,
27 )
28
29
30 class logentry:
31 """Class logentry has the following attributes:
32 .author - author name as CVS knows it
33 .branch - name of branch this revision is on
34 .branches - revision tuple of branches starting at this revision
35 .comment - commit message
36 .commitid - CVS commitid or None
37 .date - the commit date as a (time, tz) tuple
38 .dead - true if file revision is dead
39 .file - Name of file
40 .lines - a tuple (+lines, -lines) or None
41 .parent - Previous revision of this entry
42 .rcs - name of file as returned from CVS
43 .revision - revision number as tuple
44 .tags - list of tags on the file
45 .synthetic - is this a synthetic "file ... added on ..." revision?
46 .mergepoint - the branch that has been merged from (if present in
47 rlog output) or None
48 .branchpoints - the branches that start at the current entry or empty
49 """
50
51 def __init__(self, **entries):
52 self.synthetic = False
53 self.__dict__.update(entries)
54
55 def __repr__(self):
56 items = ("%s=%r" % (k, self.__dict__[k]) for k in sorted(self.__dict__))
57 return "%s(%s)" % (type(self).__name__, ", ".join(items))
58
59
60 class logerror(Exception):
61 pass
62
63
64 def getrepopath(cvspath):
65 """Return the repository path from a CVS path.
66
67 >>> getrepopath(b'/foo/bar')
68 '/foo/bar'
69 >>> getrepopath(b'c:/foo/bar')
70 '/foo/bar'
71 >>> getrepopath(b':pserver:10/foo/bar')
72 '/foo/bar'
73 >>> getrepopath(b':pserver:10c:/foo/bar')
74 '/foo/bar'
75 >>> getrepopath(b':pserver:/foo/bar')
76 '/foo/bar'
77 >>> getrepopath(b':pserver:c:/foo/bar')
78 '/foo/bar'
79 >>> getrepopath(b':pserver:[email protected]:/foo/bar')
80 '/foo/bar'
81 >>> getrepopath(b':pserver:[email protected]:c:/foo/bar')
82 '/foo/bar'
83 >>> getrepopath(b'user@server/path/to/repository')
84 '/path/to/repository'
85 """
86 # According to CVS manual, CVS paths are expressed like:
87 # [:method:][[user][:password]@]hostname[:[port]]/path/to/repository
88 #
89 # CVSpath is splitted into parts and then position of the first occurrence
90 # of the '/' char after the '@' is located. The solution is the rest of the
91 # string after that '/' sign including it
92
93 parts = cvspath.split(b':')
94 atposition = parts[-1].find(b'@')
95 start = 0
96
97 if atposition != -1:
98 start = atposition
99
100 repopath = parts[-1][parts[-1].find(b'/', start) :]
101 return repopath
102
103
104 def createlog(ui, directory=None, root=b"", rlog=True, cache=None):
105 '''Collect the CVS rlog'''
106
107 # Because we store many duplicate commit log messages, reusing strings
108 # saves a lot of memory and pickle storage space.
109 _scache = {}
110
111 def scache(s):
112 """return a shared version of a string"""
113 return _scache.setdefault(s, s)
114
115 ui.status(_(b'collecting CVS rlog\n'))
116
117 log = [] # list of logentry objects containing the CVS state
118
119 # patterns to match in CVS (r)log output, by state of use
120 re_00 = re.compile(b'RCS file: (.+)$')
121 re_01 = re.compile(b'cvs \\[r?log aborted\\]: (.+)$')
122 re_02 = re.compile(b'cvs (r?log|server): (.+)\n$')
123 re_03 = re.compile(
124 b"(Cannot access.+CVSROOT)|(can't create temporary directory.+)$"
125 )
126 re_10 = re.compile(b'Working file: (.+)$')
127 re_20 = re.compile(b'symbolic names:')
128 re_30 = re.compile(b'\t(.+): ([\\d.]+)$')
129 re_31 = re.compile(b'----------------------------$')
130 re_32 = re.compile(
131 b'======================================='
132 b'======================================$'
133 )
134 re_50 = re.compile(br'revision ([\d.]+)(\s+locked by:\s+.+;)?$')
135 re_60 = re.compile(
136 br'date:\s+(.+);\s+author:\s+(.+);\s+state:\s+(.+?);'
137 br'(\s+lines:\s+(\+\d+)?\s+(-\d+)?;)?'
138 br'(\s+commitid:\s+([^;]+);)?'
139 br'(.*mergepoint:\s+([^;]+);)?'
140 )
141 re_70 = re.compile(b'branches: (.+);$')
142
143 file_added_re = re.compile(br'file [^/]+ was (initially )?added on branch')
144
145 prefix = b'' # leading path to strip of what we get from CVS
146
147 if directory is None:
148 # Current working directory
149
150 # Get the real directory in the repository
151 try:
152 with open(os.path.join(b'CVS', b'Repository'), 'rb') as f:
153 prefix = f.read().strip()
154 directory = prefix
155 if prefix == b".":
156 prefix = b""
157 except OSError:
158 raise logerror(_(b'not a CVS sandbox'))
159
160 if prefix and not prefix.endswith(pycompat.ossep):
161 prefix += pycompat.ossep
162
163 # Use the Root file in the sandbox, if it exists
164 try:
165 root = util.readfile(os.path.join(b'CVS', b'Root')).strip()
166 except OSError:
167 pass
168
169 if not root:
170 root = encoding.environ.get(b'CVSROOT', b'')
171
172 # read log cache if one exists
173 oldlog = []
174 date = None
175
176 if cache:
177 cachedir = os.path.expanduser(b'~/.hg.cvsps')
178 if not os.path.exists(cachedir):
179 os.mkdir(cachedir)
180
181 # The cvsps cache pickle needs a uniquified name, based on the
182 # repository location. The address may have all sort of nasties
183 # in it, slashes, colons and such. So here we take just the
184 # alphanumeric characters, concatenated in a way that does not
185 # mix up the various components, so that
186 # :pserver:user@server:/path
187 # and
188 # /pserver/user/server/path
189 # are mapped to different cache file names.
190 cachefile = root.split(b":") + [directory, b"cache"]
191 cachefile = [b'-'.join(re.findall(br'\w+', s)) for s in cachefile if s]
192 cachefile = os.path.join(
193 cachedir, b'.'.join([s for s in cachefile if s])
194 )
195
196 if cache == b'update':
197 try:
198 ui.note(_(b'reading cvs log cache %s\n') % cachefile)
199 with open(cachefile, 'rb') as fp:
200 oldlog = pickle.load(fp)
201 for e in oldlog:
202 if not (
203 hasattr(e, 'branchpoints')
204 and hasattr(e, 'commitid')
205 and hasattr(e, 'mergepoint')
206 ):
207 ui.status(_(b'ignoring old cache\n'))
208 oldlog = []
209 break
210
211 ui.note(_(b'cache has %d log entries\n') % len(oldlog))
212 except Exception as e:
213 ui.note(_(b'error reading cache: %r\n') % e)
214
215 if oldlog:
216 date = oldlog[-1].date # last commit date as a (time,tz) tuple
217 date = dateutil.datestr(date, b'%Y/%m/%d %H:%M:%S %1%2')
218
219 # build the CVS commandline
220 cmd = [b'cvs', b'-q']
221 if root:
222 cmd.append(b'-d%s' % root)
223 p = util.normpath(getrepopath(root))
224 if not p.endswith(b'/'):
225 p += b'/'
226 if prefix:
227 # looks like normpath replaces "" by "."
228 prefix = p + util.normpath(prefix)
229 else:
230 prefix = p
231 cmd.append([b'log', b'rlog'][rlog])
232 if date:
233 # no space between option and date string
234 cmd.append(b'-d>%s' % date)
235 cmd.append(directory)
236
237 # state machine begins here
238 tags = {} # dictionary of revisions on current file with their tags
239 branchmap = {} # mapping between branch names and revision numbers
240 rcsmap = {}
241 state = 0
242 store = False # set when a new record can be appended
243
244 cmd = [procutil.shellquote(arg) for arg in cmd]
245 ui.note(_(b"running %s\n") % (b' '.join(cmd)))
246 ui.debug(b"prefix=%r directory=%r root=%r\n" % (prefix, directory, root))
247
248 pfp = procutil.popen(b' '.join(cmd), b'rb')
249 peek = util.fromnativeeol(pfp.readline())
250 while True:
251 line = peek
252 if line == b'':
253 break
254 peek = util.fromnativeeol(pfp.readline())
255 if line.endswith(b'\n'):
256 line = line[:-1]
257 # ui.debug('state=%d line=%r\n' % (state, line))
258
259 if state == 0:
260 # initial state, consume input until we see 'RCS file'
261 match = re_00.match(line)
262 if match:
263 rcs = match.group(1)
264 tags = {}
265 if rlog:
266 filename = util.normpath(rcs[:-2])
267 if filename.startswith(prefix):
268 filename = filename[len(prefix) :]
269 if filename.startswith(b'/'):
270 filename = filename[1:]
271 if filename.startswith(b'Attic/'):
272 filename = filename[6:]
273 else:
274 filename = filename.replace(b'/Attic/', b'/')
275 state = 2
276 continue
277 state = 1
278 continue
279 match = re_01.match(line)
280 if match:
281 raise logerror(match.group(1))
282 match = re_02.match(line)
283 if match:
284 raise logerror(match.group(2))
285 if re_03.match(line):
286 raise logerror(line)
287
288 elif state == 1:
289 # expect 'Working file' (only when using log instead of rlog)
290 match = re_10.match(line)
291 assert match, _(b'RCS file must be followed by working file')
292 filename = util.normpath(match.group(1))
293 state = 2
294
295 elif state == 2:
296 # expect 'symbolic names'
297 if re_20.match(line):
298 branchmap = {}
299 state = 3
300
301 elif state == 3:
302 # read the symbolic names and store as tags
303 match = re_30.match(line)
304 if match:
305 rev = [int(x) for x in match.group(2).split(b'.')]
306
307 # Convert magic branch number to an odd-numbered one
308 revn = len(rev)
309 if revn > 3 and (revn % 2) == 0 and rev[-2] == 0:
310 rev = rev[:-2] + rev[-1:]
311 rev = tuple(rev)
312
313 if rev not in tags:
314 tags[rev] = []
315 tags[rev].append(match.group(1))
316 branchmap[match.group(1)] = match.group(2)
317
318 elif re_31.match(line):
319 state = 5
320 elif re_32.match(line):
321 state = 0
322
323 elif state == 4:
324 # expecting '------' separator before first revision
325 if re_31.match(line):
326 state = 5
327 else:
328 assert not re_32.match(line), _(
329 b'must have at least some revisions'
330 )
331
332 elif state == 5:
333 # expecting revision number and possibly (ignored) lock indication
334 # we create the logentry here from values stored in states 0 to 4,
335 # as this state is re-entered for subsequent revisions of a file.
336 match = re_50.match(line)
337 assert match, _(b'expected revision number')
338 e = logentry(
339 rcs=scache(rcs),
340 file=scache(filename),
341 revision=tuple([int(x) for x in match.group(1).split(b'.')]),
342 branches=[],
343 parent=None,
344 commitid=None,
345 mergepoint=None,
346 branchpoints=set(),
347 )
348
349 state = 6
350
351 elif state == 6:
352 # expecting date, author, state, lines changed
353 match = re_60.match(line)
354 assert match, _(b'revision must be followed by date line')
355 d = match.group(1)
356 if d[2] == b'/':
357 # Y2K
358 d = b'19' + d
359
360 if len(d.split()) != 3:
361 # cvs log dates always in GMT
362 d = d + b' UTC'
363 e.date = dateutil.parsedate(
364 d,
365 [
366 b'%y/%m/%d %H:%M:%S',
367 b'%Y/%m/%d %H:%M:%S',
368 b'%Y-%m-%d %H:%M:%S',
369 ],
370 )
371 e.author = scache(match.group(2))
372 e.dead = match.group(3).lower() == b'dead'
373
374 if match.group(5):
375 if match.group(6):
376 e.lines = (int(match.group(5)), int(match.group(6)))
377 else:
378 e.lines = (int(match.group(5)), 0)
379 elif match.group(6):
380 e.lines = (0, int(match.group(6)))
381 else:
382 e.lines = None
383
384 if match.group(7): # cvs 1.12 commitid
385 e.commitid = match.group(8)
386
387 if match.group(9): # cvsnt mergepoint
388 myrev = match.group(10).split(b'.')
389 if len(myrev) == 2: # head
390 e.mergepoint = b'HEAD'
391 else:
392 myrev = b'.'.join(myrev[:-2] + [b'0', myrev[-2]])
393 branches = [b for b in branchmap if branchmap[b] == myrev]
394 assert len(branches) == 1, (
395 b'unknown branch: %s' % e.mergepoint
396 )
397 e.mergepoint = branches[0]
398
399 e.comment = []
400 state = 7
401
402 elif state == 7:
403 # read the revision numbers of branches that start at this revision
404 # or store the commit log message otherwise
405 m = re_70.match(line)
406 if m:
407 e.branches = [
408 tuple([int(y) for y in x.strip().split(b'.')])
409 for x in m.group(1).split(b';')
410 ]
411 state = 8
412 elif re_31.match(line) and re_50.match(peek):
413 state = 5
414 store = True
415 elif re_32.match(line):
416 state = 0
417 store = True
418 else:
419 e.comment.append(line)
420
421 elif state == 8:
422 # store commit log message
423 if re_31.match(line):
424 cpeek = peek
425 if cpeek.endswith(b'\n'):
426 cpeek = cpeek[:-1]
427 if re_50.match(cpeek):
428 state = 5
429 store = True
430 else:
431 e.comment.append(line)
432 elif re_32.match(line):
433 state = 0
434 store = True
435 else:
436 e.comment.append(line)
437
438 # When a file is added on a branch B1, CVS creates a synthetic
439 # dead trunk revision 1.1 so that the branch has a root.
440 # Likewise, if you merge such a file to a later branch B2 (one
441 # that already existed when the file was added on B1), CVS
442 # creates a synthetic dead revision 1.1.x.1 on B2. Don't drop
443 # these revisions now, but mark them synthetic so
444 # createchangeset() can take care of them.
445 if (
446 store
447 and e.dead
448 and e.revision[-1] == 1
449 and len(e.comment) == 1 # 1.1 or 1.1.x.1
450 and file_added_re.match(e.comment[0])
451 ):
452 ui.debug(
453 b'found synthetic revision in %s: %r\n' % (e.rcs, e.comment[0])
454 )
455 e.synthetic = True
456
457 if store:
458 # clean up the results and save in the log.
459 store = False
460 e.tags = sorted([scache(x) for x in tags.get(e.revision, [])])
461 e.comment = scache(b'\n'.join(e.comment))
462
463 revn = len(e.revision)
464 if revn > 3 and (revn % 2) == 0:
465 e.branch = tags.get(e.revision[:-1], [None])[0]
466 else:
467 e.branch = None
468
469 # find the branches starting from this revision
470 branchpoints = set()
471 for branch, revision in branchmap.items():
472 revparts = tuple([int(i) for i in revision.split(b'.')])
473 if len(revparts) < 2: # bad tags
474 continue
475 if revparts[-2] == 0 and revparts[-1] % 2 == 0:
476 # normal branch
477 if revparts[:-2] == e.revision:
478 branchpoints.add(branch)
479 elif revparts == (1, 1, 1): # vendor branch
480 if revparts in e.branches:
481 branchpoints.add(branch)
482 e.branchpoints = branchpoints
483
484 log.append(e)
485
486 rcsmap[e.rcs.replace(b'/Attic/', b'/')] = e.rcs
487
488 if len(log) % 100 == 0:
489 ui.status(
490 stringutil.ellipsis(b'%d %s' % (len(log), e.file), 80)
491 + b'\n'
492 )
493
494 log.sort(key=lambda x: (x.rcs, x.revision))
495
496 # find parent revisions of individual files
497 versions = {}
498 for e in sorted(oldlog, key=lambda x: (x.rcs, x.revision)):
499 rcs = e.rcs.replace(b'/Attic/', b'/')
500 if rcs in rcsmap:
501 e.rcs = rcsmap[rcs]
502 branch = e.revision[:-1]
503 versions[(e.rcs, branch)] = e.revision
504
505 for e in log:
506 branch = e.revision[:-1]
507 p = versions.get((e.rcs, branch), None)
508 if p is None:
509 p = e.revision[:-2]
510 e.parent = p
511 versions[(e.rcs, branch)] = e.revision
512
513 # update the log cache
514 if cache:
515 if log:
516 # join up the old and new logs
517 log.sort(key=lambda x: x.date)
518
519 if oldlog and oldlog[-1].date >= log[0].date:
520 raise logerror(
521 _(
522 b'log cache overlaps with new log entries,'
523 b' re-run without cache.'
524 )
525 )
526
527 log = oldlog + log
528
529 # write the new cachefile
530 ui.note(_(b'writing cvs log cache %s\n') % cachefile)
531
532 with open(cachefile, 'wb') as fp:
533 pickle.dump(log, fp)
534 else:
535 log = oldlog
536
537 ui.status(_(b'%d log entries\n') % len(log))
538
539 encodings = ui.configlist(b'convert', b'cvsps.logencoding')
540 if encodings:
541
542 def revstr(r):
543 # this is needed, because logentry.revision is a tuple of "int"
544 # (e.g. (1, 2) for "1.2")
545 return b'.'.join(pycompat.maplist(pycompat.bytestr, r))
546
547 for entry in log:
548 comment = entry.comment
549 for e in encodings:
550 try:
551 entry.comment = comment.decode(pycompat.sysstr(e)).encode(
552 'utf-8'
553 )
554 if ui.debugflag:
555 ui.debug(
556 b"transcoding by %s: %s of %s\n"
557 % (e, revstr(entry.revision), entry.file)
558 )
559 break
560 except UnicodeDecodeError:
561 pass # try next encoding
562 except LookupError as inst: # unknown encoding, maybe
563 raise error.Abort(
564 pycompat.bytestr(inst),
565 hint=_(
566 b'check convert.cvsps.logencoding configuration'
567 ),
568 )
569 else:
570 raise error.Abort(
571 _(
572 b"no encoding can transcode"
573 b" CVS log message for %s of %s"
574 )
575 % (revstr(entry.revision), entry.file),
576 hint=_(b'check convert.cvsps.logencoding configuration'),
577 )
578
579 hook.hook(ui, None, b"cvslog", True, log=log)
580
581 return log
582
583
584 class changeset:
585 """Class changeset has the following attributes:
586 .id - integer identifying this changeset (list index)
587 .author - author name as CVS knows it
588 .branch - name of branch this changeset is on, or None
589 .comment - commit message
590 .commitid - CVS commitid or None
591 .date - the commit date as a (time,tz) tuple
592 .entries - list of logentry objects in this changeset
593 .parents - list of one or two parent changesets
594 .tags - list of tags on this changeset
595 .synthetic - from synthetic revision "file ... added on branch ..."
596 .mergepoint- the branch that has been merged from or None
597 .branchpoints- the branches that start at the current entry or empty
598 """
599
600 def __init__(self, **entries):
601 self.id = None
602 self.synthetic = False
603 self.__dict__.update(entries)
604
605 def __repr__(self):
606 items = (
607 b"%s=%r" % (k, self.__dict__[k]) for k in sorted(self.__dict__)
608 )
609 return b"%s(%s)" % (type(self).__name__, b", ".join(items))
610
611
612 def createchangeset(ui, log, fuzz=60, mergefrom=None, mergeto=None):
613 '''Convert log into changesets.'''
614
615 ui.status(_(b'creating changesets\n'))
616
617 # try to order commitids by date
618 mindate = {}
619 for e in log:
620 if e.commitid:
621 if e.commitid not in mindate:
622 mindate[e.commitid] = e.date
623 else:
624 mindate[e.commitid] = min(e.date, mindate[e.commitid])
625
626 # Merge changesets
627 log.sort(
628 key=lambda x: (
629 mindate.get(x.commitid, (-1, 0)),
630 x.commitid or b'',
631 x.comment,
632 x.author,
633 x.branch or b'',
634 x.date,
635 x.branchpoints,
636 )
637 )
638
639 changesets = []
640 files = set()
641 c = None
642 for i, e in enumerate(log):
643 # Check if log entry belongs to the current changeset or not.
644
645 # Since CVS is file-centric, two different file revisions with
646 # different branchpoints should be treated as belonging to two
647 # different changesets (and the ordering is important and not
648 # honoured by cvsps at this point).
649 #
650 # Consider the following case:
651 # foo 1.1 branchpoints: [MYBRANCH]
652 # bar 1.1 branchpoints: [MYBRANCH, MYBRANCH2]
653 #
654 # Here foo is part only of MYBRANCH, but not MYBRANCH2, e.g. a
655 # later version of foo may be in MYBRANCH2, so foo should be the
656 # first changeset and bar the next and MYBRANCH and MYBRANCH2
657 # should both start off of the bar changeset. No provisions are
658 # made to ensure that this is, in fact, what happens.
659 if not (
660 c
661 and e.branchpoints == c.branchpoints
662 and ( # cvs commitids
663 (e.commitid is not None and e.commitid == c.commitid)
664 or ( # no commitids, use fuzzy commit detection
665 (e.commitid is None or c.commitid is None)
666 and e.comment == c.comment
667 and e.author == c.author
668 and e.branch == c.branch
669 and (
670 (c.date[0] + c.date[1])
671 <= (e.date[0] + e.date[1])
672 <= (c.date[0] + c.date[1]) + fuzz
673 )
674 and e.file not in files
675 )
676 )
677 ):
678 c = changeset(
679 comment=e.comment,
680 author=e.author,
681 branch=e.branch,
682 date=e.date,
683 entries=[],
684 mergepoint=e.mergepoint,
685 branchpoints=e.branchpoints,
686 commitid=e.commitid,
687 )
688 changesets.append(c)
689
690 files = set()
691 if len(changesets) % 100 == 0:
692 t = b'%d %s' % (
693 len(changesets),
694 pycompat.byterepr(e.comment)[2:-1],
695 )
696 ui.status(stringutil.ellipsis(t, 80) + b'\n')
697
698 c.entries.append(e)
699 files.add(e.file)
700 c.date = e.date # changeset date is date of latest commit in it
701
702 # Mark synthetic changesets
703
704 for c in changesets:
705 # Synthetic revisions always get their own changeset, because
706 # the log message includes the filename. E.g. if you add file3
707 # and file4 on a branch, you get four log entries and three
708 # changesets:
709 # "File file3 was added on branch ..." (synthetic, 1 entry)
710 # "File file4 was added on branch ..." (synthetic, 1 entry)
711 # "Add file3 and file4 to fix ..." (real, 2 entries)
712 # Hence the check for 1 entry here.
713 c.synthetic = len(c.entries) == 1 and c.entries[0].synthetic
714
715 # Sort files in each changeset
716
717 def entitycompare(l, r):
718 """Mimic cvsps sorting order"""
719 l = l.file.split(b'/')
720 r = r.file.split(b'/')
721 nl = len(l)
722 nr = len(r)
723 n = min(nl, nr)
724 for i in range(n):
725 if i + 1 == nl and nl < nr:
726 return -1
727 elif i + 1 == nr and nl > nr:
728 return +1
729 elif l[i] < r[i]:
730 return -1
731 elif l[i] > r[i]:
732 return +1
733 return 0
734
735 for c in changesets:
736 c.entries.sort(key=functools.cmp_to_key(entitycompare))
737
738 # Sort changesets by date
739
740 odd = set()
741
742 def cscmp(l, r):
743 d = sum(l.date) - sum(r.date)
744 if d:
745 return d
746
747 # detect vendor branches and initial commits on a branch
748 le = {}
749 for e in l.entries:
750 le[e.rcs] = e.revision
751 re = {}
752 for e in r.entries:
753 re[e.rcs] = e.revision
754
755 d = 0
756 for e in l.entries:
757 if re.get(e.rcs, None) == e.parent:
758 assert not d
759 d = 1
760 break
761
762 for e in r.entries:
763 if le.get(e.rcs, None) == e.parent:
764 if d:
765 odd.add((l, r))
766 d = -1
767 break
768 # By this point, the changesets are sufficiently compared that
769 # we don't really care about ordering. However, this leaves
770 # some race conditions in the tests, so we compare on the
771 # number of files modified, the files contained in each
772 # changeset, and the branchpoints in the change to ensure test
773 # output remains stable.
774
775 # recommended replacement for cmp from
776 # https://docs.python.org/3.0/whatsnew/3.0.html
777 c = lambda x, y: (x > y) - (x < y)
778 # Sort bigger changes first.
779 if not d:
780 d = c(len(l.entries), len(r.entries))
781 # Try sorting by filename in the change.
782 if not d:
783 d = c([e.file for e in l.entries], [e.file for e in r.entries])
784 # Try and put changes without a branch point before ones with
785 # a branch point.
786 if not d:
787 d = c(len(l.branchpoints), len(r.branchpoints))
788 return d
789
790 changesets.sort(key=functools.cmp_to_key(cscmp))
791
792 # Collect tags
793
794 globaltags = {}
795 for c in changesets:
796 for e in c.entries:
797 for tag in e.tags:
798 # remember which is the latest changeset to have this tag
799 globaltags[tag] = c
800
801 for c in changesets:
802 tags = set()
803 for e in c.entries:
804 tags.update(e.tags)
805 # remember tags only if this is the latest changeset to have it
806 c.tags = sorted(tag for tag in tags if globaltags[tag] is c)
807
808 # Find parent changesets, handle {{mergetobranch BRANCHNAME}}
809 # by inserting dummy changesets with two parents, and handle
810 # {{mergefrombranch BRANCHNAME}} by setting two parents.
811
812 if mergeto is None:
813 mergeto = br'{{mergetobranch ([-\w]+)}}'
814 if mergeto:
815 mergeto = re.compile(mergeto)
816
817 if mergefrom is None:
818 mergefrom = br'{{mergefrombranch ([-\w]+)}}'
819 if mergefrom:
820 mergefrom = re.compile(mergefrom)
821
822 versions = {} # changeset index where we saw any particular file version
823 branches = {} # changeset index where we saw a branch
824 n = len(changesets)
825 i = 0
826 while i < n:
827 c = changesets[i]
828
829 for f in c.entries:
830 versions[(f.rcs, f.revision)] = i
831
832 p = None
833 if c.branch in branches:
834 p = branches[c.branch]
835 else:
836 # first changeset on a new branch
837 # the parent is a changeset with the branch in its
838 # branchpoints such that it is the latest possible
839 # commit without any intervening, unrelated commits.
840
841 for candidate in range(i):
842 if c.branch not in changesets[candidate].branchpoints:
843 if p is not None:
844 break
845 continue
846 p = candidate
847
848 c.parents = []
849 if p is not None:
850 p = changesets[p]
851
852 # Ensure no changeset has a synthetic changeset as a parent.
853 while p.synthetic:
854 assert len(p.parents) <= 1, _(
855 b'synthetic changeset cannot have multiple parents'
856 )
857 if p.parents:
858 p = p.parents[0]
859 else:
860 p = None
861 break
862
863 if p is not None:
864 c.parents.append(p)
865
866 if c.mergepoint:
867 if c.mergepoint == b'HEAD':
868 c.mergepoint = None
869 c.parents.append(changesets[branches[c.mergepoint]])
870
871 if mergefrom:
872 m = mergefrom.search(c.comment)
873 if m:
874 m = m.group(1)
875 if m == b'HEAD':
876 m = None
877 try:
878 candidate = changesets[branches[m]]
879 except KeyError:
880 ui.warn(
881 _(
882 b"warning: CVS commit message references "
883 b"non-existent branch %r:\n%s\n"
884 )
885 % (pycompat.bytestr(m), c.comment)
886 )
887 if m in branches and c.branch != m and not candidate.synthetic:
888 c.parents.append(candidate)
889
890 if mergeto:
891 m = mergeto.search(c.comment)
892 if m:
893 if m.groups():
894 m = m.group(1)
895 if m == b'HEAD':
896 m = None
897 else:
898 m = None # if no group found then merge to HEAD
899 if m in branches and c.branch != m:
900 # insert empty changeset for merge
901 cc = changeset(
902 author=c.author,
903 branch=m,
904 date=c.date,
905 comment=b'convert-repo: CVS merge from branch %s'
906 % c.branch,
907 entries=[],
908 tags=[],
909 parents=[changesets[branches[m]], c],
910 )
911 changesets.insert(i + 1, cc)
912 branches[m] = i + 1
913
914 # adjust our loop counters now we have inserted a new entry
915 n += 1
916 i += 2
917 continue
918
919 branches[c.branch] = i
920 i += 1
921
922 # Drop synthetic changesets (safe now that we have ensured no other
923 # changesets can have them as parents).
924 i = 0
925 while i < len(changesets):
926 if changesets[i].synthetic:
927 del changesets[i]
928 else:
929 i += 1
930
931 # Number changesets
932
933 for i, c in enumerate(changesets):
934 c.id = i + 1
935
936 if odd:
937 for l, r in odd:
938 if l.id is not None and r.id is not None:
939 ui.warn(
940 _(b'changeset %d is both before and after %d\n')
941 % (l.id, r.id)
942 )
943
944 ui.status(_(b'%d changeset entries\n') % len(changesets))
945
946 hook.hook(ui, None, b"cvschangesets", True, changesets=changesets)
947
948 return changesets
949
950
951 def debugcvsps(ui, *args, **opts):
952 """Read CVS rlog for current directory or named path in
953 repository, and convert the log to changesets based on matching
954 commit log entries and dates.
955 """
956 opts = pycompat.byteskwargs(opts)
957 if opts[b"new_cache"]:
958 cache = b"write"
959 elif opts[b"update_cache"]:
960 cache = b"update"
961 else:
962 cache = None
963
964 revisions = opts[b"revisions"]
965
966 try:
967 if args:
968 log = []
969 for d in args:
970 log += createlog(ui, d, root=opts[b"root"], cache=cache)
971 else:
972 log = createlog(ui, root=opts[b"root"], cache=cache)
973 except logerror as e:
974 ui.write(b"%r\n" % e)
975 return
976
977 changesets = createchangeset(ui, log, opts[b"fuzz"])
978 del log
979
980 # Print changesets (optionally filtered)
981
982 off = len(revisions)
983 branches = {} # latest version number in each branch
984 ancestors = {} # parent branch
985 for cs in changesets:
986 if opts[b"ancestors"]:
987 if cs.branch not in branches and cs.parents and cs.parents[0].id:
988 ancestors[cs.branch] = (
989 changesets[cs.parents[0].id - 1].branch,
990 cs.parents[0].id,
991 )
992 branches[cs.branch] = cs.id
993
994 # limit by branches
995 if (
996 opts[b"branches"]
997 and (cs.branch or b'HEAD') not in opts[b"branches"]
998 ):
999 continue
1000
1001 if not off:
1002 # Note: trailing spaces on several lines here are needed to have
1003 # bug-for-bug compatibility with cvsps.
1004 ui.write(b'---------------------\n')
1005 ui.writenoi18n(b'PatchSet %d \n' % cs.id)
1006 ui.writenoi18n(
1007 b'Date: %s\n'
1008 % dateutil.datestr(cs.date, b'%Y/%m/%d %H:%M:%S %1%2')
1009 )
1010 ui.writenoi18n(b'Author: %s\n' % cs.author)
1011 ui.writenoi18n(b'Branch: %s\n' % (cs.branch or b'HEAD'))
1012 ui.writenoi18n(
1013 b'Tag%s: %s \n'
1014 % (
1015 [b'', b's'][len(cs.tags) > 1],
1016 b','.join(cs.tags) or b'(none)',
1017 )
1018 )
1019 if cs.branchpoints:
1020 ui.writenoi18n(
1021 b'Branchpoints: %s \n' % b', '.join(sorted(cs.branchpoints))
1022 )
1023 if opts[b"parents"] and cs.parents:
1024 if len(cs.parents) > 1:
1025 ui.writenoi18n(
1026 b'Parents: %s\n'
1027 % (b','.join([(b"%d" % p.id) for p in cs.parents]))
1028 )
1029 else:
1030 ui.writenoi18n(b'Parent: %d\n' % cs.parents[0].id)
1031
1032 if opts[b"ancestors"]:
1033 b = cs.branch
1034 r = []
1035 while b:
1036 b, c = ancestors[b]
1037 r.append(b'%s:%d:%d' % (b or b"HEAD", c, branches[b]))
1038 if r:
1039 ui.writenoi18n(b'Ancestors: %s\n' % (b','.join(r)))
1040
1041 ui.writenoi18n(b'Log:\n')
1042 ui.write(b'%s\n\n' % cs.comment)
1043 ui.writenoi18n(b'Members: \n')
1044 for f in cs.entries:
1045 fn = f.file
1046 if fn.startswith(opts[b"prefix"]):
1047 fn = fn[len(opts[b"prefix"]) :]
1048 ui.write(
1049 b'\t%s:%s->%s%s \n'
1050 % (
1051 fn,
1052 b'.'.join([b"%d" % x for x in f.parent]) or b'INITIAL',
1053 b'.'.join([(b"%d" % x) for x in f.revision]),
1054 [b'', b'(DEAD)'][f.dead],
1055 )
1056 )
1057 ui.write(b'\n')
1058
1059 # have we seen the start tag?
1060 if revisions and off:
1061 if revisions[0] == (b"%d" % cs.id) or revisions[0] in cs.tags:
1062 off = False
1063
1064 # see if we reached the end tag
1065 if len(revisions) > 1 and not off:
1066 if revisions[1] == (b"%d" % cs.id) or revisions[1] in cs.tags:
1067 break