Simplify logic and improve warning message for duplicate symbol definitions.
[cvs2svn.git] / cvs2svn_lib / collect_data.py
blob44e6424c0d43f3552dd19fe84224a300128f37a7
1 # (Be in -*- python -*- mode.)
3 # ====================================================================
4 # Copyright (c) 2000-2007 CollabNet. All rights reserved.
6 # This software is licensed as described in the file COPYING, which
7 # you should have received as part of this distribution. The terms
8 # are also available at http://subversion.tigris.org/license-1.html.
9 # If newer versions of this license are posted there, you may use a
10 # newer version instead, at your option.
12 # This software consists of voluntary contributions made by many
13 # individuals. For exact contribution history, see the revision
14 # history and logs, available at http://cvs2svn.tigris.org/.
15 # ====================================================================
17 """Data collection classes.
19 This module contains the code used to collect data from the CVS
20 repository. It parses *,v files, recording all useful information
21 except for the actual file contents (though even the file contents
22 might be recorded by the RevisionRecorder if one is configured).
24 As a *,v file is parsed, the information pertaining to the file is
25 accumulated in memory, mostly in _RevisionData, _BranchData, and
26 _TagData objects. When parsing is complete, a final pass is made over
27 the data to create some final dependency links, collect statistics,
28 etc., then the _*Data objects are converted into CVSItem objects
29 (CVSRevision, CVSBranch, and CVSTag respectively) and the CVSItems are
30 dumped into databases.
32 During the data collection, persistent unique ids are allocated to
33 many types of objects: CVSFile, Symbol, and CVSItems. CVSItems are a
34 special case. CVSItem ids are unique across all CVSItem types, and
35 the ids are carried over from the corresponding data collection
36 objects:
38 _RevisionData -> CVSRevision
40 _BranchData -> CVSBranch
42 _TagData -> CVSTag
44 In a later pass it is possible to convert tags <-> branches. But even
45 if this occurs, the new branch or tag uses the same id as the old tag
46 or branch.
48 """
51 import os
52 import stat
53 import re
55 from cvs2svn_lib import config
56 from cvs2svn_lib.common import DB_OPEN_NEW
57 from cvs2svn_lib.common import FatalError
58 from cvs2svn_lib.common import warning_prefix
59 from cvs2svn_lib.common import error_prefix
60 from cvs2svn_lib.common import IllegalSVNPathError
61 from cvs2svn_lib.common import verify_svn_filename_legal
62 from cvs2svn_lib.log import Log
63 from cvs2svn_lib.context import Ctx
64 from cvs2svn_lib.artifact_manager import artifact_manager
65 from cvs2svn_lib.project import FileInAndOutOfAtticException
66 from cvs2svn_lib.cvs_file import CVSPath
67 from cvs2svn_lib.cvs_file import CVSDirectory
68 from cvs2svn_lib.cvs_file import CVSFile
69 from cvs2svn_lib.symbol import Symbol
70 from cvs2svn_lib.symbol import Trunk
71 from cvs2svn_lib.cvs_item import CVSRevision
72 from cvs2svn_lib.cvs_item import CVSBranch
73 from cvs2svn_lib.cvs_item import CVSTag
74 from cvs2svn_lib.cvs_item import cvs_revision_type_map
75 from cvs2svn_lib.cvs_file_items import VendorBranchError
76 from cvs2svn_lib.cvs_file_items import CVSFileItems
77 from cvs2svn_lib.key_generator import KeyGenerator
78 from cvs2svn_lib.cvs_item_database import NewCVSItemStore
79 from cvs2svn_lib.symbol_statistics import SymbolStatisticsCollector
80 from cvs2svn_lib.metadata_database import MetadataDatabase
81 from cvs2svn_lib.metadata_database import MetadataLogger
83 import cvs2svn_rcsparse
86 # A regular expression defining "valid" revision numbers (used to
87 # check that symbol definitions are reasonable).
88 _valid_revision_re = re.compile(r'''
90 (?:\d+\.)+ # Digit groups with trailing dots
91 \d+ # And the last digit group.
93 ''', re.VERBOSE)
95 _branch_revision_re = re.compile(r'''
97 ((?:\d+\.\d+\.)+) # A nonzero even number of digit groups w/trailing dot
98 (?:0\.)? # CVS sticks an extra 0 here; RCS does not
99 (\d+) # And the last digit group
101 ''', re.VERBOSE)
104 def rev_tuple(rev):
105 """Return a tuple of integers corresponding to revision number REV.
107 For example, if REV is '1.2.3.4', then return (1,2,3,4)."""
109 return tuple([int(x) for x in rev.split('.')])
112 def is_trunk_revision(rev):
113 """Return True iff REV is a trunk revision.
115 REV is a revision number corresponding to a specific revision (i.e.,
116 not a whole branch)."""
118 return rev.count('.') == 1
121 def is_branch_revision_number(rev):
122 """Return True iff REV is a branch revision number.
124 REV is a CVS revision number in canonical form (i.e., with zeros
125 removed). Return True iff it refers to a whole branch, as opposed
126 to a single revision."""
128 return rev.count('.') % 2 == 0
131 def is_same_line_of_development(rev1, rev2):
132 """Return True if rev1 and rev2 are on the same line of
133 development (i.e., both on trunk, or both on the same branch);
134 return False otherwise. Either rev1 or rev2 can be None, in
135 which case automatically return False."""
137 if rev1 is None or rev2 is None:
138 return False
139 if rev1.count('.') == 1 and rev2.count('.') == 1:
140 return True
141 if rev1[0:rev1.rfind('.')] == rev2[0:rev2.rfind('.')]:
142 return True
143 return False
146 class _RevisionData:
147 """We track the state of each revision so that in set_revision_info,
148 we can determine if our op is an add/change/delete. We can do this
149 because in set_revision_info, we'll have all of the _RevisionData
150 for a file at our fingertips, and we need to examine the state of
151 our prev_rev to determine if we're an add or a change. Without the
152 state of the prev_rev, we are unable to distinguish between an add
153 and a change."""
155 def __init__(self, cvs_rev_id, rev, timestamp, author, state):
156 # The id of this revision:
157 self.cvs_rev_id = cvs_rev_id
158 self.rev = rev
159 self.timestamp = timestamp
160 self.author = author
161 self.original_timestamp = timestamp
162 self.state = state
164 # If this is the first revision on a branch, then this is the
165 # branch_data of that branch; otherwise it is None.
166 self.parent_branch_data = None
168 # The revision number of the parent of this revision along the
169 # same line of development, if any. For the first revision R on a
170 # branch, we consider the revision from which R sprouted to be the
171 # 'parent'. If this is the root revision in the file's revision
172 # tree, then this field is None.
174 # Note that this revision can't be determined arithmetically (due
175 # to cvsadmin -o), which is why this field is necessary.
176 self.parent = None
178 # The revision number of the primary child of this revision (the
179 # child along the same line of development), if any; otherwise,
180 # None.
181 self.child = None
183 # The _BranchData instances of branches that sprout from this
184 # revision, sorted in ascending order by branch number. It would
185 # be inconvenient to initialize it here because we would have to
186 # scan through all branches known by the _SymbolDataCollector to
187 # find the ones having us as the parent. Instead, this
188 # information is filled in by
189 # _FileDataCollector._resolve_dependencies() and sorted by
190 # _FileDataCollector._sort_branches().
191 self.branches_data = []
193 # The revision numbers of the first commits on any branches on
194 # which commits occurred. This dependency is kept explicitly
195 # because otherwise a revision-only topological sort would miss
196 # the dependency that exists via branches_data.
197 self.branches_revs_data = []
199 # The _TagData instances of tags that are connected to this
200 # revision.
201 self.tags_data = []
203 # A token that may be returned from
204 # RevisionRecorder.record_text(). It can be used by
205 # RevisionReader to obtain the text again.
206 self.revision_recorder_token = None
208 def get_first_on_branch_id(self):
209 return self.parent_branch_data and self.parent_branch_data.id
212 class _SymbolData:
213 """Collection area for information about a symbol in a single CVSFile.
215 SYMBOL is an instance of Symbol, undifferentiated as a Branch or a
216 Tag regardless of whether self is a _BranchData or a _TagData."""
218 def __init__(self, id, symbol):
219 """Initialize an object for SYMBOL."""
221 # The unique id that will be used for this particular symbol in
222 # this particular file. This same id will be used for the CVSItem
223 # that is derived from this instance.
224 self.id = id
226 # An instance of Symbol.
227 self.symbol = symbol
230 class _BranchData(_SymbolData):
231 """Collection area for information about a Branch in a single CVSFile."""
233 def __init__(self, id, symbol, branch_number):
234 _SymbolData.__init__(self, id, symbol)
236 # The branch number (e.g., '1.5.2') of this branch.
237 self.branch_number = branch_number
239 # The revision number of the revision from which this branch
240 # sprouts (e.g., '1.5').
241 self.parent = self.branch_number[:self.branch_number.rindex(".")]
243 # The revision number of the first commit on this branch, if any
244 # (e.g., '1.5.2.1'); otherwise, None.
245 self.child = None
248 class _TagData(_SymbolData):
249 """Collection area for information about a Tag in a single CVSFile."""
251 def __init__(self, id, symbol, rev):
252 _SymbolData.__init__(self, id, symbol)
254 # The revision number being tagged (e.g., '1.5.2.3').
255 self.rev = rev
258 class _SymbolDataCollector(object):
259 """Collect information about symbols in a single CVSFile."""
261 def __init__(self, fdc, cvs_file):
262 self.fdc = fdc
263 self.cvs_file = cvs_file
265 self.pdc = self.fdc.pdc
266 self.collect_data = self.fdc.collect_data
268 # A list [(name, revision), ...] of symbols defined in the header
269 # of the file. The name has already been transformed using the
270 # symbol transform rules. If the symbol transform rules indicate
271 # that the symbol should be ignored, then it is never added to
272 # this list. This list is processed then deleted in
273 # process_symbols().
274 self._symbol_defs = []
276 # Map { branch_number : _BranchData }, where branch_number has an
277 # odd number of digits.
278 self.branches_data = { }
280 # Map { revision : [ tag_data ] }, where revision has an even
281 # number of digits, and the value is a list of _TagData objects
282 # for tags that apply to that revision.
283 self.tags_data = { }
285 def _add_branch(self, name, branch_number):
286 """Record that BRANCH_NUMBER is the branch number for branch NAME,
287 and derive and record the revision from which NAME sprouts.
288 BRANCH_NUMBER is an RCS branch number with an odd number of
289 components, for example '1.7.2' (never '1.7.0.2'). Return the
290 _BranchData instance (which is usually newly-created)."""
292 branch_data = self.branches_data.get(branch_number)
294 if branch_data is not None:
295 Log().warn(
296 "%s: in '%s':\n"
297 " branch '%s' already has name '%s',\n"
298 " cannot also have name '%s', ignoring the latter\n"
299 % (warning_prefix,
300 self.cvs_file.filename, branch_number,
301 branch_data.symbol.name, name)
303 return branch_data
305 symbol = self.pdc.get_symbol(name)
306 branch_data = _BranchData(
307 self.collect_data.item_key_generator.gen_id(), symbol, branch_number
309 self.branches_data[branch_number] = branch_data
310 return branch_data
312 def _add_unlabeled_branch(self, branch_number):
313 name = "unlabeled-" + branch_number
314 return self._add_branch(name, branch_number)
316 def _add_tag(self, name, revision):
317 """Record that tag NAME refers to the specified REVISION."""
319 symbol = self.pdc.get_symbol(name)
320 tag_data = _TagData(
321 self.collect_data.item_key_generator.gen_id(), symbol, revision
323 self.tags_data.setdefault(revision, []).append(tag_data)
324 return tag_data
326 def transform_symbol(self, name, revision):
327 """Transform a symbol according to the project's symbol transforms.
329 Transform the symbol with the original name NAME and canonicalized
330 revision number REVISION. Return the new symbol name or None if
331 the symbol should be ignored entirely.
333 Log the results of the symbol transform if necessary."""
335 old_name = name
336 # Apply any user-defined symbol transforms to the symbol name:
337 name = self.cvs_file.project.transform_symbol(
338 self.cvs_file, name, revision
341 if name is None:
342 # Ignore symbol:
343 self.pdc.log_symbol_transform(old_name, None)
344 Log().verbose(
345 " symbol '%s'=%s ignored in %s"
346 % (old_name, revision, self.cvs_file.filename,)
348 else:
349 if name != old_name:
350 self.pdc.log_symbol_transform(old_name, name)
351 Log().verbose(
352 " symbol '%s'=%s transformed to '%s' in %s"
353 % (old_name, revision, name, self.cvs_file.filename,)
356 return name
358 def define_symbol(self, name, revision):
359 """Record a symbol definition for later processing."""
361 # Canonicalize the revision number:
362 revision = _branch_revision_re.sub(r'\1\2', revision)
364 # Apply any user-defined symbol transforms to the symbol name:
365 name = self.transform_symbol(name, revision)
367 if name is not None:
368 # Verify that the revision number is valid:
369 if _valid_revision_re.match(revision):
370 # The revision number is valid; record it for later processing:
371 self._symbol_defs.append( (name, revision) )
372 else:
373 Log().warn(
374 'In %r:\n'
375 ' branch %r references invalid revision %s\n'
376 ' and will be ignored.'
377 % (self.cvs_file.filename, name, revision,)
380 def _eliminate_trivial_duplicate_defs(self):
381 """Remove identical duplicate definitions in SELF._symbol_defs.
383 Duplicate definitions of symbol names have been seen in the wild,
384 and they can also happen when --symbol-transform is used. If a
385 symbol is defined to the same revision number repeatedly, then
386 ignore all but the last definition."""
388 # A map { (name, revision) : [index,...] } of the indexes where
389 # symbol definitions name=revision were found:
390 known_definitions = {}
391 for (i, symbol_def) in enumerate(self._symbol_defs):
392 known_definitions.setdefault(symbol_def, []).append(i)
394 # A set of the indexes of entries that have to be removed from
395 # _symbol_defs:
396 dup_indexes = set()
397 for ((name, revision), indexes) in known_definitions.iteritems():
398 if len(indexes) > 1:
399 Log().verbose(
400 "in %r:\n"
401 " symbol %s:%s defined multiple times; ignoring duplicates\n"
402 % (self.cvs_file.filename, name, revision,)
404 dup_indexes.update(indexes[:-1])
406 self._symbol_defs = [
407 symbol_def
408 for (i, symbol_def) in enumerate(self._symbol_defs)
409 if i not in dup_indexes
412 def _process_duplicate_defs(self):
413 """Look for and process duplicate names in SELF._symbol_defs.
415 Duplicate definitions of symbol names have been seen in the wild,
416 and they can also happen when --symbol-transform is used. If a
417 symbol is defined multiple times, then it is a fatal error. This
418 method should be called after _eliminate_trivial_duplicate_defs()."""
420 # A map {name : [index,...]} mapping the names of symbols to a
421 # list of their definitions' indexes in self._symbol_defs:
422 known_symbols = {}
424 for (i, (name, revision)) in enumerate(self._symbol_defs):
425 if name in known_symbols:
426 known_symbols[name].append(i)
427 else:
428 known_symbols[name] = [i]
430 names = known_symbols.keys()
431 names.sort()
432 dup_indexes = set()
433 for name in names:
434 indexes = known_symbols[name]
435 if len(indexes) > 1:
436 # This symbol was defined multiple times.
437 self.collect_data.record_fatal_error(
438 "Multiple definitions of the symbol '%s' in '%s': %s" % (
439 name, self.cvs_file.filename,
440 ' '.join([self._symbol_defs[i][1] for i in indexes]),
443 # Ignore all but the last definition for now, to allow the
444 # conversion to proceed:
445 dup_indexes.update(indexes[:-1])
447 self._symbol_defs = [
448 symbol_def
449 for (i, symbol_def) in enumerate(self._symbol_defs)
450 if i not in dup_indexes
453 def _process_symbol(self, name, revision):
454 """Process a symbol called NAME, which is associated with REVISON.
456 REVISION is a canonical revision number with zeros removed, for
457 example: '1.7', '1.7.2', or '1.1.1' or '1.1.1.1'. NAME is a
458 transformed branch or tag name."""
460 # Add symbol to our records:
461 if is_branch_revision_number(revision):
462 self._add_branch(name, revision)
463 else:
464 self._add_tag(name, revision)
466 def process_symbols(self):
467 """Process the symbol definitions from SELF._symbol_defs."""
469 self._eliminate_trivial_duplicate_defs()
470 self._process_duplicate_defs()
472 for (name, revision) in self._symbol_defs:
473 self._process_symbol(name, revision)
475 del self._symbol_defs
477 @staticmethod
478 def rev_to_branch_number(revision):
479 """Return the branch_number of the branch on which REVISION lies.
481 REVISION is a branch revision number with an even number of
482 components; for example '1.7.2.1' (never '1.7.2' nor '1.7.0.2').
483 The return value is the branch number (for example, '1.7.2').
484 Return none iff REVISION is a trunk revision such as '1.2'."""
486 if is_trunk_revision(revision):
487 return None
488 return revision[:revision.rindex(".")]
490 def rev_to_branch_data(self, revision):
491 """Return the branch_data of the branch on which REVISION lies.
493 REVISION must be a branch revision number with an even number of
494 components; for example '1.7.2.1' (never '1.7.2' nor '1.7.0.2').
495 Raise KeyError iff REVISION is unknown."""
497 assert not is_trunk_revision(revision)
499 return self.branches_data[self.rev_to_branch_number(revision)]
501 def rev_to_lod(self, revision):
502 """Return the line of development on which REVISION lies.
504 REVISION must be a revision number with an even number of
505 components. Raise KeyError iff REVISION is unknown."""
507 if is_trunk_revision(revision):
508 return self.pdc.trunk
509 else:
510 return self.rev_to_branch_data(revision).symbol
513 class _FileDataCollector(cvs2svn_rcsparse.Sink):
514 """Class responsible for collecting RCS data for a particular file.
516 Any collected data that need to be remembered are stored into the
517 referenced CollectData instance."""
519 def __init__(self, pdc, cvs_file):
520 """Create an object that is prepared to receive data for CVS_FILE.
521 CVS_FILE is a CVSFile instance. COLLECT_DATA is used to store the
522 information collected about the file."""
524 self.pdc = pdc
525 self.cvs_file = cvs_file
527 self.collect_data = self.pdc.collect_data
528 self.project = self.cvs_file.project
530 # A place to store information about the symbols in this file:
531 self.sdc = _SymbolDataCollector(self, self.cvs_file)
533 # { revision : _RevisionData instance }
534 self._rev_data = { }
536 # Lists [ (parent, child) ] of revision number pairs indicating
537 # that revision child depends on revision parent along the main
538 # line of development.
539 self._primary_dependencies = []
541 # If set, this is an RCS branch number -- rcsparse calls this the
542 # "principal branch", but CVS and RCS refer to it as the "default
543 # branch", so that's what we call it, even though the rcsparse API
544 # setter method is still 'set_principal_branch'.
545 self.default_branch = None
547 # True iff revision 1.1 of the file appears to have been imported
548 # (as opposed to added normally).
549 self._file_imported = False
551 def _get_rev_id(self, revision):
552 if revision is None:
553 return None
554 return self._rev_data[revision].cvs_rev_id
556 def set_principal_branch(self, branch):
557 """This is a callback method declared in Sink."""
559 if branch.find('.') == -1:
560 # This just sets the default branch to trunk. Normally this
561 # shouldn't occur, but it has been seen in at least one CVS
562 # repository. Just ignore it.
563 pass
564 else:
565 self.default_branch = branch
567 def set_expansion(self, mode):
568 """This is a callback method declared in Sink."""
570 self.cvs_file.mode = mode
572 def define_tag(self, name, revision):
573 """Remember the symbol name and revision, but don't process them yet.
575 This is a callback method declared in Sink."""
577 self.sdc.define_symbol(name, revision)
579 def admin_completed(self):
580 """This is a callback method declared in Sink."""
582 self.sdc.process_symbols()
584 def define_revision(self, revision, timestamp, author, state,
585 branches, next):
586 """This is a callback method declared in Sink."""
588 for branch in branches:
589 try:
590 branch_data = self.sdc.rev_to_branch_data(branch)
591 except KeyError:
592 # Normally we learn about the branches from the branch names
593 # and numbers parsed from the symbolic name header. But this
594 # must have been an unlabeled branch that slipped through the
595 # net. Generate a name for it and create a _BranchData record
596 # for it now.
597 branch_data = self.sdc._add_unlabeled_branch(
598 self.sdc.rev_to_branch_number(branch))
600 assert branch_data.child is None
601 branch_data.child = branch
603 if revision in self._rev_data:
604 # This revision has already been seen.
605 Log().error('File %r contains duplicate definitions of revision %s.'
606 % (self.cvs_file.filename, revision,))
607 raise RuntimeError
609 # Record basic information about the revision:
610 rev_data = _RevisionData(
611 self.collect_data.item_key_generator.gen_id(),
612 revision, int(timestamp), author, state)
613 self._rev_data[revision] = rev_data
615 # When on trunk, the RCS 'next' revision number points to what
616 # humans might consider to be the 'previous' revision number. For
617 # example, 1.3's RCS 'next' is 1.2.
619 # However, on a branch, the RCS 'next' revision number really does
620 # point to what humans would consider to be the 'next' revision
621 # number. For example, 1.1.2.1's RCS 'next' would be 1.1.2.2.
623 # In other words, in RCS, 'next' always means "where to find the next
624 # deltatext that you need this revision to retrieve.
626 # That said, we don't *want* RCS's behavior here, so we determine
627 # whether we're on trunk or a branch and set the dependencies
628 # accordingly.
629 if next:
630 if is_trunk_revision(revision):
631 self._primary_dependencies.append( (next, revision,) )
632 else:
633 self._primary_dependencies.append( (revision, next,) )
635 def _resolve_primary_dependencies(self):
636 """Resolve the dependencies listed in self._primary_dependencies."""
638 for (parent, child,) in self._primary_dependencies:
639 parent_data = self._rev_data[parent]
640 assert parent_data.child is None
641 parent_data.child = child
643 child_data = self._rev_data[child]
644 assert child_data.parent is None
645 child_data.parent = parent
647 def _resolve_branch_dependencies(self):
648 """Resolve dependencies involving branches."""
650 for branch_data in self.sdc.branches_data.values():
651 # The branch_data's parent has the branch as a child regardless
652 # of whether the branch had any subsequent commits:
653 try:
654 parent_data = self._rev_data[branch_data.parent]
655 except KeyError:
656 Log().warn(
657 'In %r:\n'
658 ' branch %r references non-existing revision %s\n'
659 ' and will be ignored.'
660 % (self.cvs_file.filename, branch_data.symbol.name,
661 branch_data.parent,))
662 del self.sdc.branches_data[branch_data.branch_number]
663 else:
664 parent_data.branches_data.append(branch_data)
666 # If the branch has a child (i.e., something was committed on
667 # the branch), then we store a reference to the branch_data
668 # there, define the child's parent to be the branch's parent,
669 # and list the child in the branch parent's branches_revs_data:
670 if branch_data.child is not None:
671 child_data = self._rev_data[branch_data.child]
672 assert child_data.parent_branch_data is None
673 child_data.parent_branch_data = branch_data
674 assert child_data.parent is None
675 child_data.parent = branch_data.parent
676 parent_data.branches_revs_data.append(branch_data.child)
678 def _sort_branches(self):
679 """Sort the branches sprouting from each revision in creation order.
681 Creation order is taken to be the reverse of the order that they
682 are listed in the symbols part of the RCS file. (If a branch is
683 created then deleted, a later branch can be assigned the recycled
684 branch number; therefore branch numbers are not an indication of
685 creation order.)"""
687 for rev_data in self._rev_data.values():
688 rev_data.branches_data.sort(lambda a, b: - cmp(a.id, b.id))
690 def _resolve_tag_dependencies(self):
691 """Resolve dependencies involving tags."""
693 for (rev, tag_data_list) in self.sdc.tags_data.items():
694 try:
695 parent_data = self._rev_data[rev]
696 except KeyError:
697 Log().warn(
698 'In %r:\n'
699 ' the following tag(s) reference non-existing revision %s\n'
700 ' and will be ignored:\n'
701 ' %s' % (
702 self.cvs_file.filename, rev,
703 ', '.join([repr(tag_data.symbol.name)
704 for tag_data in tag_data_list]),))
705 del self.sdc.tags_data[rev]
706 else:
707 for tag_data in tag_data_list:
708 assert tag_data.rev == rev
709 # The tag_data's rev has the tag as a child:
710 parent_data.tags_data.append(tag_data)
712 def _determine_operation(self, rev_data):
713 prev_rev_data = self._rev_data.get(rev_data.parent)
714 return cvs_revision_type_map[(
715 rev_data.state != 'dead',
716 prev_rev_data is not None and prev_rev_data.state != 'dead',
719 def _get_cvs_revision(self, rev_data):
720 """Create and return a CVSRevision for REV_DATA."""
722 branch_ids = [
723 branch_data.id
724 for branch_data in rev_data.branches_data
727 branch_commit_ids = [
728 self._get_rev_id(rev)
729 for rev in rev_data.branches_revs_data
732 tag_ids = [
733 tag_data.id
734 for tag_data in rev_data.tags_data
737 revision_type = self._determine_operation(rev_data)
739 return revision_type(
740 self._get_rev_id(rev_data.rev), self.cvs_file,
741 rev_data.timestamp, None,
742 self._get_rev_id(rev_data.parent),
743 self._get_rev_id(rev_data.child),
744 rev_data.rev,
745 True,
746 self.sdc.rev_to_lod(rev_data.rev),
747 rev_data.get_first_on_branch_id(),
748 False, None, None,
749 tag_ids, branch_ids, branch_commit_ids,
750 rev_data.revision_recorder_token)
752 def _get_cvs_revisions(self):
753 """Generate the CVSRevisions present in this file."""
755 for rev_data in self._rev_data.itervalues():
756 yield self._get_cvs_revision(rev_data)
758 def _get_cvs_branches(self):
759 """Generate the CVSBranches present in this file."""
761 for branch_data in self.sdc.branches_data.values():
762 yield CVSBranch(
763 branch_data.id, self.cvs_file, branch_data.symbol,
764 branch_data.branch_number,
765 self.sdc.rev_to_lod(branch_data.parent),
766 self._get_rev_id(branch_data.parent),
767 self._get_rev_id(branch_data.child),
768 None,
771 def _get_cvs_tags(self):
772 """Generate the CVSTags present in this file."""
774 for tags_data in self.sdc.tags_data.values():
775 for tag_data in tags_data:
776 yield CVSTag(
777 tag_data.id, self.cvs_file, tag_data.symbol,
778 self.sdc.rev_to_lod(tag_data.rev),
779 self._get_rev_id(tag_data.rev),
780 None,
783 def tree_completed(self):
784 """The revision tree has been parsed.
786 Analyze it for consistency and connect some loose ends.
788 This is a callback method declared in Sink."""
790 self._resolve_primary_dependencies()
791 self._resolve_branch_dependencies()
792 self._sort_branches()
793 self._resolve_tag_dependencies()
795 # Compute the preliminary CVSFileItems for this file:
796 cvs_items = []
797 cvs_items.extend(self._get_cvs_revisions())
798 cvs_items.extend(self._get_cvs_branches())
799 cvs_items.extend(self._get_cvs_tags())
800 self._cvs_file_items = CVSFileItems(
801 self.cvs_file, self.pdc.trunk, cvs_items
804 self._cvs_file_items.check_link_consistency()
806 # Tell the revision recorder about the file dependency tree.
807 self.collect_data.revision_recorder.start_file(self._cvs_file_items)
809 def set_revision_info(self, revision, log, text):
810 """This is a callback method declared in Sink."""
812 rev_data = self._rev_data[revision]
813 cvs_rev = self._cvs_file_items[rev_data.cvs_rev_id]
815 if cvs_rev.metadata_id is not None:
816 # Users have reported problems with repositories in which the
817 # deltatext block for revision 1.1 appears twice. It is not
818 # known whether this results from a CVS/RCS bug, or from botched
819 # hand-editing of the repository. In any case, empirically, cvs
820 # and rcs both use the first version when checking out data, so
821 # that's what we will do. (For the record: "cvs log" fails on
822 # such a file; "rlog" prints the log message from the first
823 # block and ignores the second one.)
824 Log().warn(
825 "%s: in '%s':\n"
826 " Deltatext block for revision %s appeared twice;\n"
827 " ignoring the second occurrence.\n"
828 % (warning_prefix, self.cvs_file.filename, revision,)
830 return
832 if is_trunk_revision(revision):
833 branch_name = None
834 else:
835 branch_name = self.sdc.rev_to_branch_data(revision).symbol.name
837 cvs_rev.metadata_id = self.collect_data.metadata_logger.store(
838 self.project, branch_name, rev_data.author, log
840 cvs_rev.deltatext_exists = bool(text)
842 # If this is revision 1.1, determine whether the file appears to
843 # have been created via 'cvs add' instead of 'cvs import'. The
844 # test is that the log message CVS uses for 1.1 in imports is
845 # "Initial revision\n" with no period. (This fact helps determine
846 # whether this file might have had a default branch in the past.)
847 if revision == '1.1':
848 self._file_imported = (log == 'Initial revision\n')
850 cvs_rev.revision_recorder_token = \
851 self.collect_data.revision_recorder.record_text(cvs_rev, log, text)
853 def parse_completed(self):
854 """Finish the processing of this file.
856 This is a callback method declared in Sink."""
858 # Make sure that there was an info section for each revision:
859 for cvs_item in self._cvs_file_items.values():
860 if isinstance(cvs_item, CVSRevision) and cvs_item.metadata_id is None:
861 self.collect_data.record_fatal_error(
862 '%r has no deltatext section for revision %s'
863 % (self.cvs_file.filename, cvs_item.rev,)
866 def _process_ntdbrs(self):
867 """Fix up any non-trunk default branch revisions (if present).
869 If a non-trunk default branch is determined to have existed, yield
870 the _RevisionData.ids for all revisions that were once non-trunk
871 default revisions, in dependency order.
873 There are two cases to handle:
875 One case is simple. The RCS file lists a default branch
876 explicitly in its header, such as '1.1.1'. In this case, we know
877 that every revision on the vendor branch is to be treated as head
878 of trunk at that point in time.
880 But there's also a degenerate case. The RCS file does not
881 currently have a default branch, yet we can deduce that for some
882 period in the past it probably *did* have one. For example, the
883 file has vendor revisions 1.1.1.1 -> 1.1.1.96, all of which are
884 dated before 1.2, and then it has 1.1.1.97 -> 1.1.1.100 dated
885 after 1.2. In this case, we should record 1.1.1.96 as the last
886 vendor revision to have been the head of the default branch.
888 If any non-trunk default branch revisions are found:
890 - Set their ntdbr members to True.
892 - Connect the last one with revision 1.2.
894 - Remove revision 1.1 if it is not needed.
898 try:
899 if self.default_branch:
900 vendor_cvs_branch_id = self.sdc.branches_data[self.default_branch].id
901 vendor_lod_items = self._cvs_file_items.get_lod_items(
902 self._cvs_file_items[vendor_cvs_branch_id]
904 if not self._cvs_file_items.process_live_ntdb(vendor_lod_items):
905 return
906 elif self._file_imported:
907 vendor_branch_data = self.sdc.branches_data.get('1.1.1')
908 if vendor_branch_data is None:
909 return
910 else:
911 vendor_lod_items = self._cvs_file_items.get_lod_items(
912 self._cvs_file_items[vendor_branch_data.id]
914 if not self._cvs_file_items.process_historical_ntdb(
915 vendor_lod_items
917 return
918 else:
919 return
920 except VendorBranchError, e:
921 self.collect_data.record_fatal_error(str(e))
922 return
924 if self._file_imported:
925 self._cvs_file_items.imported_remove_1_1(vendor_lod_items)
927 self._cvs_file_items.check_link_consistency()
929 def get_cvs_file_items(self):
930 """Finish up and return a CVSFileItems instance for this file.
932 This method must only be called once."""
934 self._process_ntdbrs()
936 # Break a circular reference loop, allowing the memory for self
937 # and sdc to be freed.
938 del self.sdc
940 return self._cvs_file_items
943 class _ProjectDataCollector:
944 def __init__(self, collect_data, project):
945 self.collect_data = collect_data
946 self.project = project
947 self.num_files = 0
949 # The Trunk LineOfDevelopment object for this project:
950 self.trunk = Trunk(
951 self.collect_data.symbol_key_generator.gen_id(), self.project
953 self.project.trunk_id = self.trunk.id
955 # This causes a record for self.trunk to spring into existence:
956 self.collect_data.symbol_stats[self.trunk]
958 # A map { name -> Symbol } for all known symbols in this project.
959 # The symbols listed here are undifferentiated into Branches and
960 # Tags because the same name might appear as a branch in one file
961 # and a tag in another.
962 self.symbols = {}
964 # A map { (old_name, new_name) : count } indicating how many files
965 # were affected by each each symbol name transformation:
966 self.symbol_transform_counts = {}
968 def get_symbol(self, name):
969 """Return the Symbol object for the symbol named NAME in this project.
971 If such a symbol does not yet exist, allocate a new symbol_id,
972 create a Symbol instance, store it in self.symbols, and return it."""
974 symbol = self.symbols.get(name)
975 if symbol is None:
976 symbol = Symbol(
977 self.collect_data.symbol_key_generator.gen_id(),
978 self.project, name)
979 self.symbols[name] = symbol
980 return symbol
982 def log_symbol_transform(self, old_name, new_name):
983 """Record that OLD_NAME was transformed to NEW_NAME in one file.
985 This information is used to generated a statistical summary of
986 symbol transforms."""
988 try:
989 self.symbol_transform_counts[old_name, new_name] += 1
990 except KeyError:
991 self.symbol_transform_counts[old_name, new_name] = 1
993 def summarize_symbol_transforms(self):
994 if self.symbol_transform_counts and Log().is_on(Log.NORMAL):
995 log = Log()
996 log.normal('Summary of symbol transforms:')
997 transforms = self.symbol_transform_counts.items()
998 transforms.sort()
999 for ((old_name, new_name), count) in transforms:
1000 if new_name is None:
1001 log.normal(' "%s" ignored in %d files' % (old_name, count,))
1002 else:
1003 log.normal(
1004 ' "%s" transformed to "%s" in %d files'
1005 % (old_name, new_name, count,)
1008 def _process_cvs_file_items(self, cvs_file_items):
1009 """Process the CVSFileItems from one CVSFile."""
1011 # Remove CVSRevisionDeletes that are not needed:
1012 cvs_file_items.remove_unneeded_deletes(self.collect_data.metadata_db)
1014 # Remove initial branch deletes that are not needed:
1015 cvs_file_items.remove_initial_branch_deletes(
1016 self.collect_data.metadata_db
1019 # If this is a --trunk-only conversion, discard all branches and
1020 # tags, then draft any non-trunk default branch revisions to
1021 # trunk:
1022 if Ctx().trunk_only:
1023 cvs_file_items.exclude_non_trunk()
1025 self.collect_data.revision_recorder.finish_file(cvs_file_items)
1026 self.collect_data.add_cvs_file_items(cvs_file_items)
1027 self.collect_data.symbol_stats.register(cvs_file_items)
1029 def process_file(self, cvs_file):
1030 Log().normal(cvs_file.filename)
1031 fdc = _FileDataCollector(self, cvs_file)
1032 try:
1033 cvs2svn_rcsparse.parse(open(cvs_file.filename, 'rb'), fdc)
1034 except (cvs2svn_rcsparse.common.RCSParseError, ValueError, RuntimeError):
1035 self.collect_data.record_fatal_error(
1036 "%r is not a valid ,v file" % (cvs_file.filename,)
1038 # Abort the processing of this file, but let the pass continue
1039 # with other files:
1040 return
1041 except:
1042 Log().warn("Exception occurred while parsing %s" % cvs_file.filename)
1043 raise
1044 else:
1045 self.num_files += 1
1047 cvs_file_items = fdc.get_cvs_file_items()
1049 del fdc
1051 self._process_cvs_file_items(cvs_file_items)
1054 class CollectData:
1055 """Repository for data collected by parsing the CVS repository files.
1057 This class manages the databases into which information collected
1058 from the CVS repository is stored. The data are stored into this
1059 class by _FileDataCollector instances, one of which is created for
1060 each file to be parsed."""
1062 def __init__(self, revision_recorder, stats_keeper):
1063 self.revision_recorder = revision_recorder
1064 self._cvs_item_store = NewCVSItemStore(
1065 artifact_manager.get_temp_file(config.CVS_ITEMS_STORE))
1066 self.metadata_db = MetadataDatabase(
1067 artifact_manager.get_temp_file(config.METADATA_STORE),
1068 artifact_manager.get_temp_file(config.METADATA_INDEX_TABLE),
1069 DB_OPEN_NEW,
1071 self.metadata_logger = MetadataLogger(self.metadata_db)
1072 self.fatal_errors = []
1073 self.num_files = 0
1074 self.symbol_stats = SymbolStatisticsCollector()
1075 self.stats_keeper = stats_keeper
1077 # Key generator for CVSFiles:
1078 self.file_key_generator = KeyGenerator()
1080 # Key generator for CVSItems:
1081 self.item_key_generator = KeyGenerator()
1083 # Key generator for Symbols:
1084 self.symbol_key_generator = KeyGenerator()
1086 self.revision_recorder.start()
1088 def record_fatal_error(self, err):
1089 """Record that fatal error ERR was found.
1091 ERR is a string (without trailing newline) describing the error.
1092 Output the error to stderr immediately, and record a copy to be
1093 output again in a summary at the end of CollectRevsPass."""
1095 err = '%s: %s' % (error_prefix, err,)
1096 Log().error(err + '\n')
1097 self.fatal_errors.append(err)
1099 def add_cvs_directory(self, cvs_directory):
1100 """Record CVS_DIRECTORY."""
1102 Ctx()._cvs_file_db.log_file(cvs_directory)
1104 def add_cvs_file_items(self, cvs_file_items):
1105 """Record the information from CVS_FILE_ITEMS.
1107 Store the CVSFile to _cvs_file_db under its persistent id, store
1108 the CVSItems, and record the CVSItems to self.stats_keeper."""
1110 Ctx()._cvs_file_db.log_file(cvs_file_items.cvs_file)
1111 self._cvs_item_store.add(cvs_file_items)
1113 self.stats_keeper.record_cvs_file(cvs_file_items.cvs_file)
1114 for cvs_item in cvs_file_items.values():
1115 self.stats_keeper.record_cvs_item(cvs_item)
1117 def _get_cvs_file(
1118 self, parent_directory, basename, file_in_attic, leave_in_attic=False
1120 """Return a CVSFile describing the file with name BASENAME.
1122 PARENT_DIRECTORY is the CVSDirectory instance describing the
1123 directory that physically holds this file in the filesystem.
1124 BASENAME must be the base name of a *,v file within
1125 PARENT_DIRECTORY.
1127 FILE_IN_ATTIC is a boolean telling whether the specified file is
1128 in an Attic subdirectory. If FILE_IN_ATTIC is True, then:
1130 - If LEAVE_IN_ATTIC is True, then leave the 'Attic' component in
1131 the filename.
1133 - Otherwise, raise FileInAndOutOfAtticException if a file with the
1134 same filename appears outside of Attic.
1136 The CVSFile is assigned a new unique id. All of the CVSFile
1137 information is filled in except mode (which can only be determined
1138 by parsing the file).
1140 Raise FatalError if the resulting filename would not be legal in
1141 SVN."""
1143 filename = os.path.join(parent_directory.filename, basename)
1144 try:
1145 verify_svn_filename_legal(basename[:-2])
1146 except IllegalSVNPathError, e:
1147 raise FatalError(
1148 'File %r would result in an illegal SVN filename: %s'
1149 % (filename, e,)
1152 if file_in_attic and not leave_in_attic:
1153 in_attic = True
1154 logical_parent_directory = parent_directory.parent_directory
1156 # If this file also exists outside of the attic, it's a fatal
1157 # error:
1158 non_attic_filename = os.path.join(
1159 logical_parent_directory.filename, basename,
1161 if os.path.exists(non_attic_filename):
1162 raise FileInAndOutOfAtticException(non_attic_filename, filename)
1163 else:
1164 in_attic = False
1165 logical_parent_directory = parent_directory
1167 file_stat = os.stat(filename)
1169 # The size of the file in bytes:
1170 file_size = file_stat[stat.ST_SIZE]
1172 # Whether or not the executable bit is set:
1173 file_executable = bool(file_stat[0] & stat.S_IXUSR)
1175 # mode is not known, so we temporarily set it to None.
1176 return CVSFile(
1177 self.file_key_generator.gen_id(),
1178 parent_directory.project, logical_parent_directory, basename[:-2],
1179 in_attic, file_executable, file_size, None
1182 def _get_attic_file(self, parent_directory, basename):
1183 """Return a CVSFile object for the Attic file at BASENAME.
1185 PARENT_DIRECTORY is the CVSDirectory that physically contains the
1186 file on the filesystem (i.e., the Attic directory). It is not
1187 necessarily the parent_directory of the CVSFile that will be
1188 returned.
1190 Return CVSFile, whose parent directory is usually
1191 PARENT_DIRECTORY.parent_directory, but might be PARENT_DIRECTORY
1192 iff CVSFile will remain in the Attic directory."""
1194 try:
1195 return self._get_cvs_file(parent_directory, basename, True)
1196 except FileInAndOutOfAtticException, e:
1197 if Ctx().retain_conflicting_attic_files:
1198 Log().warn(
1199 "%s: %s;\n"
1200 " storing the latter into 'Attic' subdirectory.\n"
1201 % (warning_prefix, e)
1203 else:
1204 self.record_fatal_error(str(e))
1206 # Either way, return a CVSFile object so that the rest of the
1207 # file processing can proceed:
1208 return self._get_cvs_file(
1209 parent_directory, basename, True, leave_in_attic=True
1212 def _generate_attic_cvs_files(self, cvs_directory):
1213 """Generate CVSFiles for the files in Attic directory CVS_DIRECTORY.
1215 Also add CVS_DIRECTORY to self if any files are being retained in
1216 that directory."""
1218 retained_attic_file = False
1220 fnames = os.listdir(cvs_directory.filename)
1221 fnames.sort()
1222 for fname in fnames:
1223 pathname = os.path.join(cvs_directory.filename, fname)
1224 if os.path.isdir(pathname):
1225 Log().warn("Directory %s found within Attic; ignoring" % (pathname,))
1226 elif fname.endswith(',v'):
1227 cvs_file = self._get_attic_file(cvs_directory, fname)
1228 if cvs_file.parent_directory == cvs_directory:
1229 # This file will be retained in the Attic directory.
1230 retained_attic_file = True
1231 yield cvs_file
1233 if retained_attic_file:
1234 # If any files were retained in the Attic directory, then write
1235 # the Attic directory to CVSFileDatabase:
1236 self.add_cvs_directory(cvs_directory)
1238 def _get_non_attic_file(self, parent_directory, basename):
1239 """Return a CVSFile object for the non-Attic file at BASENAME."""
1241 return self._get_cvs_file(parent_directory, basename, False)
1243 def _generate_cvs_files(self, cvs_directory):
1244 """Generate the CVSFiles under non-Attic directory CVS_DIRECTORY.
1246 Process directories recursively, including Attic directories.
1247 Also create and register CVSDirectories as they are found, and
1248 look for conflicts between the filenames that will result from
1249 files, attic files, and subdirectories."""
1251 self.add_cvs_directory(cvs_directory)
1253 # Map {cvs_file.basename : cvs_file.filename} for files directly
1254 # in cvs_directory:
1255 rcsfiles = {}
1257 attic_dir = None
1259 # Non-Attic subdirectories of cvs_directory (to be recursed into):
1260 dirs = []
1262 fnames = os.listdir(cvs_directory.filename)
1263 fnames.sort()
1264 for fname in fnames:
1265 pathname = os.path.join(cvs_directory.filename, fname)
1266 if os.path.isdir(pathname):
1267 if fname == 'Attic':
1268 attic_dir = fname
1269 else:
1270 dirs.append(fname)
1271 elif fname.endswith(',v'):
1272 cvs_file = self._get_non_attic_file(cvs_directory, fname)
1273 rcsfiles[cvs_file.basename] = cvs_file.filename
1274 yield cvs_file
1275 else:
1276 # Silently ignore other files:
1277 pass
1279 # Map {cvs_file.basename : cvs_file.filename} for files in an
1280 # Attic directory within cvs_directory:
1281 attic_rcsfiles = {}
1283 if attic_dir is not None:
1284 attic_directory = CVSDirectory(
1285 self.file_key_generator.gen_id(),
1286 cvs_directory.project, cvs_directory, 'Attic',
1289 for cvs_file in self._generate_attic_cvs_files(attic_directory):
1290 if cvs_file.parent_directory == cvs_directory:
1291 attic_rcsfiles[cvs_file.basename] = cvs_file.filename
1292 yield cvs_file
1294 alldirs = dirs + [attic_dir]
1295 else:
1296 alldirs = dirs
1298 # Check for conflicts between directory names and the filenames
1299 # that will result from the rcs files (both in this directory and
1300 # in attic). (We recurse into the subdirectories nevertheless, to
1301 # try to detect more problems.)
1302 for fname in alldirs:
1303 pathname = os.path.join(cvs_directory.filename, fname)
1304 for rcsfile_list in [rcsfiles, attic_rcsfiles]:
1305 if fname in rcsfile_list:
1306 self.record_fatal_error(
1307 'Directory name conflicts with filename. Please remove or '
1308 'rename one\n'
1309 'of the following:\n'
1310 ' "%s"\n'
1311 ' "%s"'
1312 % (pathname, rcsfile_list[fname],)
1315 # Now recurse into the other subdirectories:
1316 for fname in dirs:
1317 dirname = os.path.join(cvs_directory.filename, fname)
1319 # Verify that the directory name does not contain any illegal
1320 # characters:
1321 try:
1322 verify_svn_filename_legal(fname)
1323 except IllegalSVNPathError, e:
1324 raise FatalError(
1325 'Directory %r would result in an illegal SVN path name: %s'
1326 % (dirname, e,)
1329 sub_directory = CVSDirectory(
1330 self.file_key_generator.gen_id(),
1331 cvs_directory.project, cvs_directory, fname,
1334 for cvs_file in self._generate_cvs_files(sub_directory):
1335 yield cvs_file
1337 def process_project(self, project):
1338 Ctx()._projects[project.id] = project
1340 root_cvs_directory = CVSDirectory(
1341 self.file_key_generator.gen_id(), project, None, ''
1343 project.root_cvs_directory_id = root_cvs_directory.id
1344 pdc = _ProjectDataCollector(self, project)
1346 found_rcs_file = False
1347 for cvs_file in self._generate_cvs_files(root_cvs_directory):
1348 pdc.process_file(cvs_file)
1349 found_rcs_file = True
1351 if not found_rcs_file:
1352 self.record_fatal_error(
1353 'No RCS files found under %r!\n'
1354 'Are you absolutely certain you are pointing cvs2svn\n'
1355 'at a CVS repository?\n'
1356 % (project.project_cvs_repos_path,)
1359 pdc.summarize_symbol_transforms()
1361 self.num_files += pdc.num_files
1362 Log().verbose('Processed', self.num_files, 'files')
1364 def _set_cvs_path_ordinals(self):
1365 cvs_files = list(Ctx()._cvs_file_db.itervalues())
1366 cvs_files.sort(CVSPath.slow_compare)
1367 for (i, cvs_file) in enumerate(cvs_files):
1368 cvs_file.ordinal = i
1370 def close(self):
1371 """Close the data structures associated with this instance.
1373 Return a list of fatal errors encountered while processing input.
1374 Each list entry is a string describing one fatal error."""
1376 self.revision_recorder.finish()
1377 self.symbol_stats.purge_ghost_symbols()
1378 self.symbol_stats.close()
1379 self.symbol_stats = None
1380 self.metadata_logger = None
1381 self.metadata_db.close()
1382 self.metadata_db = None
1383 self._cvs_item_store.close()
1384 self._cvs_item_store = None
1385 self._set_cvs_path_ordinals()
1386 self.revision_recorder = None
1387 retval = self.fatal_errors
1388 self.fatal_errors = None
1389 return retval