Use enumerate() where appropriate.
[cvs2svn.git] / cvs2svn_lib / collect_data.py
blob699e0738fb852840944d49ecedec171f7a721d0e
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 define_symbol(self, name, revision):
327 """Record a symbol definition for later processing."""
329 # Canonicalize the revision number:
330 revision = _branch_revision_re.sub(r'\1\2', revision)
332 old_name = name
333 # Apply any user-defined symbol transforms to the symbol name:
334 name = self.cvs_file.project.transform_symbol(
335 self.cvs_file, name, revision
338 if name is None:
339 # Ignore symbol:
340 self.pdc.log_symbol_transform(old_name, None)
341 Log().verbose(
342 " symbol '%s'=%s ignored in %s"
343 % (old_name, revision, self.cvs_file.filename,)
345 else:
346 if name != old_name:
347 self.pdc.log_symbol_transform(old_name, name)
348 Log().verbose(
349 " symbol '%s'=%s transformed to '%s' in %s"
350 % (old_name, revision, name, self.cvs_file.filename,)
353 # Verify that the revision number is valid:
354 if _valid_revision_re.match(revision):
355 # The revision number is valid; record it for later processing:
356 self._symbol_defs.append( (name, revision) )
357 else:
358 Log().warn(
359 'In %r:\n'
360 ' branch %r references invalid revision %s\n'
361 ' and will be ignored.'
362 % (self.cvs_file.filename, name, revision,)
365 def _eliminate_trivial_duplicate_defs(self):
366 """Remove identical duplicate definitions in SELF._symbol_defs.
368 Duplicate definitions of symbol names have been seen in the wild,
369 and they can also happen when --symbol-transform is used. If a
370 symbol is defined to the same revision number repeatedly, then
371 ignore all but the last definition."""
373 # A map { (name, revision) : [index,...] } of the indexes where
374 # symbol definitions name=revision were found:
375 known_definitions = {}
377 # A set of the indexes of entries that have to be removed from
378 # _symbol_defs:
379 dup_indexes = set()
381 for (i, (name, revision)) in enumerate(self._symbol_defs):
382 if (name, revision) in known_definitions:
383 if len(known_definitions[name, revision]) == 1:
384 Log().verbose(
385 "in %r:\n"
386 " symbol %s:%s defined multiple times;\n"
387 " ignoring all but first definition\n"
388 % (self.cvs_file.filename, name, revision,)
390 dup_indexes.add(known_definitions[name, revision][-1])
391 known_definitions[name, revision].append(i)
392 else:
393 known_definitions[name, revision] = [i]
395 self._symbol_defs = [
396 symbol_def
397 for (i, symbol_def) in enumerate(self._symbol_defs)
398 if i not in dup_indexes
401 def _process_duplicate_defs(self):
402 """Look for and process duplicate names in SELF._symbol_defs.
404 Duplicate definitions of symbol names have been seen in the wild,
405 and they can also happen when --symbol-transform is used. If a
406 symbol is defined multiple times, then it is a fatal error. This
407 method should be called after _eliminate_trivial_duplicate_defs()."""
409 # A map {name : [index,...]} mapping the names of symbols to a
410 # list of their definitions' indexes in self._symbol_defs:
411 known_symbols = {}
413 for (i, (name, revision)) in enumerate(self._symbol_defs):
414 if name in known_symbols:
415 known_symbols[name].append(i)
416 else:
417 known_symbols[name] = [i]
419 names = known_symbols.keys()
420 names.sort()
421 dup_indexes = set()
422 for name in names:
423 indexes = known_symbols[name]
424 if len(indexes) > 1:
425 # This symbol was defined multiple times.
426 self.collect_data.record_fatal_error(
427 "Multiple definitions of the symbol '%s' in '%s': %s" % (
428 name, self.cvs_file.filename,
429 ' '.join([self._symbol_defs[i][1] for i in indexes]),
432 # Ignore all but the last definition for now, to allow the
433 # conversion to proceed:
434 dup_indexes.update(indexes[:-1])
436 self._symbol_defs = [
437 symbol_def
438 for (i, symbol_def) in enumerate(self._symbol_defs)
439 if i not in dup_indexes
442 def _process_symbol(self, name, revision):
443 """Process a symbol called NAME, which is associated with REVISON.
445 REVISION is a canonical revision number with zeros removed, for
446 example: '1.7', '1.7.2', or '1.1.1' or '1.1.1.1'. NAME is a
447 transformed branch or tag name."""
449 # Add symbol to our records:
450 if is_branch_revision_number(revision):
451 self._add_branch(name, revision)
452 else:
453 self._add_tag(name, revision)
455 def process_symbols(self):
456 """Process the symbol definitions from SELF._symbol_defs."""
458 self._eliminate_trivial_duplicate_defs()
459 self._process_duplicate_defs()
461 for (name, revision) in self._symbol_defs:
462 self._process_symbol(name, revision)
464 del self._symbol_defs
466 @staticmethod
467 def rev_to_branch_number(revision):
468 """Return the branch_number of the branch on which REVISION lies.
470 REVISION is a branch revision number with an even number of
471 components; for example '1.7.2.1' (never '1.7.2' nor '1.7.0.2').
472 The return value is the branch number (for example, '1.7.2').
473 Return none iff REVISION is a trunk revision such as '1.2'."""
475 if is_trunk_revision(revision):
476 return None
477 return revision[:revision.rindex(".")]
479 def rev_to_branch_data(self, revision):
480 """Return the branch_data of the branch on which REVISION lies.
482 REVISION must be a branch revision number with an even number of
483 components; for example '1.7.2.1' (never '1.7.2' nor '1.7.0.2').
484 Raise KeyError iff REVISION is unknown."""
486 assert not is_trunk_revision(revision)
488 return self.branches_data[self.rev_to_branch_number(revision)]
490 def rev_to_lod(self, revision):
491 """Return the line of development on which REVISION lies.
493 REVISION must be a revision number with an even number of
494 components. Raise KeyError iff REVISION is unknown."""
496 if is_trunk_revision(revision):
497 return self.pdc.trunk
498 else:
499 return self.rev_to_branch_data(revision).symbol
502 class _FileDataCollector(cvs2svn_rcsparse.Sink):
503 """Class responsible for collecting RCS data for a particular file.
505 Any collected data that need to be remembered are stored into the
506 referenced CollectData instance."""
508 def __init__(self, pdc, cvs_file):
509 """Create an object that is prepared to receive data for CVS_FILE.
510 CVS_FILE is a CVSFile instance. COLLECT_DATA is used to store the
511 information collected about the file."""
513 self.pdc = pdc
514 self.cvs_file = cvs_file
516 self.collect_data = self.pdc.collect_data
517 self.project = self.cvs_file.project
519 # A place to store information about the symbols in this file:
520 self.sdc = _SymbolDataCollector(self, self.cvs_file)
522 # { revision : _RevisionData instance }
523 self._rev_data = { }
525 # Lists [ (parent, child) ] of revision number pairs indicating
526 # that revision child depends on revision parent along the main
527 # line of development.
528 self._primary_dependencies = []
530 # If set, this is an RCS branch number -- rcsparse calls this the
531 # "principal branch", but CVS and RCS refer to it as the "default
532 # branch", so that's what we call it, even though the rcsparse API
533 # setter method is still 'set_principal_branch'.
534 self.default_branch = None
536 # True iff revision 1.1 of the file appears to have been imported
537 # (as opposed to added normally).
538 self._file_imported = False
540 def _get_rev_id(self, revision):
541 if revision is None:
542 return None
543 return self._rev_data[revision].cvs_rev_id
545 def set_principal_branch(self, branch):
546 """This is a callback method declared in Sink."""
548 if branch.find('.') == -1:
549 # This just sets the default branch to trunk. Normally this
550 # shouldn't occur, but it has been seen in at least one CVS
551 # repository. Just ignore it.
552 pass
553 else:
554 self.default_branch = branch
556 def set_expansion(self, mode):
557 """This is a callback method declared in Sink."""
559 self.cvs_file.mode = mode
561 def define_tag(self, name, revision):
562 """Remember the symbol name and revision, but don't process them yet.
564 This is a callback method declared in Sink."""
566 self.sdc.define_symbol(name, revision)
568 def admin_completed(self):
569 """This is a callback method declared in Sink."""
571 self.sdc.process_symbols()
573 def define_revision(self, revision, timestamp, author, state,
574 branches, next):
575 """This is a callback method declared in Sink."""
577 for branch in branches:
578 try:
579 branch_data = self.sdc.rev_to_branch_data(branch)
580 except KeyError:
581 # Normally we learn about the branches from the branch names
582 # and numbers parsed from the symbolic name header. But this
583 # must have been an unlabeled branch that slipped through the
584 # net. Generate a name for it and create a _BranchData record
585 # for it now.
586 branch_data = self.sdc._add_unlabeled_branch(
587 self.sdc.rev_to_branch_number(branch))
589 assert branch_data.child is None
590 branch_data.child = branch
592 if revision in self._rev_data:
593 # This revision has already been seen.
594 Log().error('File %r contains duplicate definitions of revision %s.'
595 % (self.cvs_file.filename, revision,))
596 raise RuntimeError
598 # Record basic information about the revision:
599 rev_data = _RevisionData(
600 self.collect_data.item_key_generator.gen_id(),
601 revision, int(timestamp), author, state)
602 self._rev_data[revision] = rev_data
604 # When on trunk, the RCS 'next' revision number points to what
605 # humans might consider to be the 'previous' revision number. For
606 # example, 1.3's RCS 'next' is 1.2.
608 # However, on a branch, the RCS 'next' revision number really does
609 # point to what humans would consider to be the 'next' revision
610 # number. For example, 1.1.2.1's RCS 'next' would be 1.1.2.2.
612 # In other words, in RCS, 'next' always means "where to find the next
613 # deltatext that you need this revision to retrieve.
615 # That said, we don't *want* RCS's behavior here, so we determine
616 # whether we're on trunk or a branch and set the dependencies
617 # accordingly.
618 if next:
619 if is_trunk_revision(revision):
620 self._primary_dependencies.append( (next, revision,) )
621 else:
622 self._primary_dependencies.append( (revision, next,) )
624 def _resolve_primary_dependencies(self):
625 """Resolve the dependencies listed in self._primary_dependencies."""
627 for (parent, child,) in self._primary_dependencies:
628 parent_data = self._rev_data[parent]
629 assert parent_data.child is None
630 parent_data.child = child
632 child_data = self._rev_data[child]
633 assert child_data.parent is None
634 child_data.parent = parent
636 def _resolve_branch_dependencies(self):
637 """Resolve dependencies involving branches."""
639 for branch_data in self.sdc.branches_data.values():
640 # The branch_data's parent has the branch as a child regardless
641 # of whether the branch had any subsequent commits:
642 try:
643 parent_data = self._rev_data[branch_data.parent]
644 except KeyError:
645 Log().warn(
646 'In %r:\n'
647 ' branch %r references non-existing revision %s\n'
648 ' and will be ignored.'
649 % (self.cvs_file.filename, branch_data.symbol.name,
650 branch_data.parent,))
651 del self.sdc.branches_data[branch_data.branch_number]
652 else:
653 parent_data.branches_data.append(branch_data)
655 # If the branch has a child (i.e., something was committed on
656 # the branch), then we store a reference to the branch_data
657 # there, define the child's parent to be the branch's parent,
658 # and list the child in the branch parent's branches_revs_data:
659 if branch_data.child is not None:
660 child_data = self._rev_data[branch_data.child]
661 assert child_data.parent_branch_data is None
662 child_data.parent_branch_data = branch_data
663 assert child_data.parent is None
664 child_data.parent = branch_data.parent
665 parent_data.branches_revs_data.append(branch_data.child)
667 def _sort_branches(self):
668 """Sort the branches sprouting from each revision in creation order.
670 Creation order is taken to be the reverse of the order that they
671 are listed in the symbols part of the RCS file. (If a branch is
672 created then deleted, a later branch can be assigned the recycled
673 branch number; therefore branch numbers are not an indication of
674 creation order.)"""
676 for rev_data in self._rev_data.values():
677 rev_data.branches_data.sort(lambda a, b: - cmp(a.id, b.id))
679 def _resolve_tag_dependencies(self):
680 """Resolve dependencies involving tags."""
682 for (rev, tag_data_list) in self.sdc.tags_data.items():
683 try:
684 parent_data = self._rev_data[rev]
685 except KeyError:
686 Log().warn(
687 'In %r:\n'
688 ' the following tag(s) reference non-existing revision %s\n'
689 ' and will be ignored:\n'
690 ' %s' % (
691 self.cvs_file.filename, rev,
692 ', '.join([repr(tag_data.symbol.name)
693 for tag_data in tag_data_list]),))
694 del self.sdc.tags_data[rev]
695 else:
696 for tag_data in tag_data_list:
697 assert tag_data.rev == rev
698 # The tag_data's rev has the tag as a child:
699 parent_data.tags_data.append(tag_data)
701 def _determine_operation(self, rev_data):
702 prev_rev_data = self._rev_data.get(rev_data.parent)
703 return cvs_revision_type_map[(
704 rev_data.state != 'dead',
705 prev_rev_data is not None and prev_rev_data.state != 'dead',
708 def _get_cvs_revision(self, rev_data):
709 """Create and return a CVSRevision for REV_DATA."""
711 branch_ids = [
712 branch_data.id
713 for branch_data in rev_data.branches_data
716 branch_commit_ids = [
717 self._get_rev_id(rev)
718 for rev in rev_data.branches_revs_data
721 tag_ids = [
722 tag_data.id
723 for tag_data in rev_data.tags_data
726 revision_type = self._determine_operation(rev_data)
728 return revision_type(
729 self._get_rev_id(rev_data.rev), self.cvs_file,
730 rev_data.timestamp, None,
731 self._get_rev_id(rev_data.parent),
732 self._get_rev_id(rev_data.child),
733 rev_data.rev,
734 True,
735 self.sdc.rev_to_lod(rev_data.rev),
736 rev_data.get_first_on_branch_id(),
737 False, None, None,
738 tag_ids, branch_ids, branch_commit_ids,
739 rev_data.revision_recorder_token)
741 def _get_cvs_revisions(self):
742 """Generate the CVSRevisions present in this file."""
744 for rev_data in self._rev_data.itervalues():
745 yield self._get_cvs_revision(rev_data)
747 def _get_cvs_branches(self):
748 """Generate the CVSBranches present in this file."""
750 for branch_data in self.sdc.branches_data.values():
751 yield CVSBranch(
752 branch_data.id, self.cvs_file, branch_data.symbol,
753 branch_data.branch_number,
754 self.sdc.rev_to_lod(branch_data.parent),
755 self._get_rev_id(branch_data.parent),
756 self._get_rev_id(branch_data.child),
757 None,
760 def _get_cvs_tags(self):
761 """Generate the CVSTags present in this file."""
763 for tags_data in self.sdc.tags_data.values():
764 for tag_data in tags_data:
765 yield CVSTag(
766 tag_data.id, self.cvs_file, tag_data.symbol,
767 self.sdc.rev_to_lod(tag_data.rev),
768 self._get_rev_id(tag_data.rev),
769 None,
772 def tree_completed(self):
773 """The revision tree has been parsed.
775 Analyze it for consistency and connect some loose ends.
777 This is a callback method declared in Sink."""
779 self._resolve_primary_dependencies()
780 self._resolve_branch_dependencies()
781 self._sort_branches()
782 self._resolve_tag_dependencies()
784 # Compute the preliminary CVSFileItems for this file:
785 cvs_items = []
786 cvs_items.extend(self._get_cvs_revisions())
787 cvs_items.extend(self._get_cvs_branches())
788 cvs_items.extend(self._get_cvs_tags())
789 self._cvs_file_items = CVSFileItems(
790 self.cvs_file, self.pdc.trunk, cvs_items
793 self._cvs_file_items.check_link_consistency()
795 # Tell the revision recorder about the file dependency tree.
796 self.collect_data.revision_recorder.start_file(self._cvs_file_items)
798 def set_revision_info(self, revision, log, text):
799 """This is a callback method declared in Sink."""
801 rev_data = self._rev_data[revision]
802 cvs_rev = self._cvs_file_items[rev_data.cvs_rev_id]
804 if cvs_rev.metadata_id is not None:
805 # Users have reported problems with repositories in which the
806 # deltatext block for revision 1.1 appears twice. It is not
807 # known whether this results from a CVS/RCS bug, or from botched
808 # hand-editing of the repository. In any case, empirically, cvs
809 # and rcs both use the first version when checking out data, so
810 # that's what we will do. (For the record: "cvs log" fails on
811 # such a file; "rlog" prints the log message from the first
812 # block and ignores the second one.)
813 Log().warn(
814 "%s: in '%s':\n"
815 " Deltatext block for revision %s appeared twice;\n"
816 " ignoring the second occurrence.\n"
817 % (warning_prefix, self.cvs_file.filename, revision,)
819 return
821 if is_trunk_revision(revision):
822 branch_name = None
823 else:
824 branch_name = self.sdc.rev_to_branch_data(revision).symbol.name
826 cvs_rev.metadata_id = self.collect_data.metadata_logger.store(
827 self.project, branch_name, rev_data.author, log
829 cvs_rev.deltatext_exists = bool(text)
831 # If this is revision 1.1, determine whether the file appears to
832 # have been created via 'cvs add' instead of 'cvs import'. The
833 # test is that the log message CVS uses for 1.1 in imports is
834 # "Initial revision\n" with no period. (This fact helps determine
835 # whether this file might have had a default branch in the past.)
836 if revision == '1.1':
837 self._file_imported = (log == 'Initial revision\n')
839 cvs_rev.revision_recorder_token = \
840 self.collect_data.revision_recorder.record_text(cvs_rev, log, text)
842 def parse_completed(self):
843 """Finish the processing of this file.
845 This is a callback method declared in Sink."""
847 # Make sure that there was an info section for each revision:
848 for cvs_item in self._cvs_file_items.values():
849 if isinstance(cvs_item, CVSRevision) and cvs_item.metadata_id is None:
850 self.collect_data.record_fatal_error(
851 '%r has no deltatext section for revision %s'
852 % (self.cvs_file.filename, cvs_item.rev,)
855 def _process_ntdbrs(self):
856 """Fix up any non-trunk default branch revisions (if present).
858 If a non-trunk default branch is determined to have existed, yield
859 the _RevisionData.ids for all revisions that were once non-trunk
860 default revisions, in dependency order.
862 There are two cases to handle:
864 One case is simple. The RCS file lists a default branch
865 explicitly in its header, such as '1.1.1'. In this case, we know
866 that every revision on the vendor branch is to be treated as head
867 of trunk at that point in time.
869 But there's also a degenerate case. The RCS file does not
870 currently have a default branch, yet we can deduce that for some
871 period in the past it probably *did* have one. For example, the
872 file has vendor revisions 1.1.1.1 -> 1.1.1.96, all of which are
873 dated before 1.2, and then it has 1.1.1.97 -> 1.1.1.100 dated
874 after 1.2. In this case, we should record 1.1.1.96 as the last
875 vendor revision to have been the head of the default branch.
877 If any non-trunk default branch revisions are found:
879 - Set their ntdbr members to True.
881 - Connect the last one with revision 1.2.
883 - Remove revision 1.1 if it is not needed.
887 try:
888 if self.default_branch:
889 vendor_cvs_branch_id = self.sdc.branches_data[self.default_branch].id
890 vendor_lod_items = self._cvs_file_items.get_lod_items(
891 self._cvs_file_items[vendor_cvs_branch_id]
893 if not self._cvs_file_items.process_live_ntdb(vendor_lod_items):
894 return
895 elif self._file_imported:
896 vendor_branch_data = self.sdc.branches_data.get('1.1.1')
897 if vendor_branch_data is None:
898 return
899 else:
900 vendor_lod_items = self._cvs_file_items.get_lod_items(
901 self._cvs_file_items[vendor_branch_data.id]
903 if not self._cvs_file_items.process_historical_ntdb(
904 vendor_lod_items
906 return
907 else:
908 return
909 except VendorBranchError, e:
910 self.collect_data.record_fatal_error(str(e))
911 return
913 if self._file_imported:
914 self._cvs_file_items.imported_remove_1_1(vendor_lod_items)
916 self._cvs_file_items.check_link_consistency()
918 def get_cvs_file_items(self):
919 """Finish up and return a CVSFileItems instance for this file.
921 This method must only be called once."""
923 self._process_ntdbrs()
925 # Break a circular reference loop, allowing the memory for self
926 # and sdc to be freed.
927 del self.sdc
929 return self._cvs_file_items
932 class _ProjectDataCollector:
933 def __init__(self, collect_data, project):
934 self.collect_data = collect_data
935 self.project = project
936 self.num_files = 0
938 # The Trunk LineOfDevelopment object for this project:
939 self.trunk = Trunk(
940 self.collect_data.symbol_key_generator.gen_id(), self.project
942 self.project.trunk_id = self.trunk.id
944 # This causes a record for self.trunk to spring into existence:
945 self.collect_data.symbol_stats[self.trunk]
947 # A map { name -> Symbol } for all known symbols in this project.
948 # The symbols listed here are undifferentiated into Branches and
949 # Tags because the same name might appear as a branch in one file
950 # and a tag in another.
951 self.symbols = {}
953 # A map { (old_name, new_name) : count } indicating how many files
954 # were affected by each each symbol name transformation:
955 self.symbol_transform_counts = {}
957 def get_symbol(self, name):
958 """Return the Symbol object for the symbol named NAME in this project.
960 If such a symbol does not yet exist, allocate a new symbol_id,
961 create a Symbol instance, store it in self.symbols, and return it."""
963 symbol = self.symbols.get(name)
964 if symbol is None:
965 symbol = Symbol(
966 self.collect_data.symbol_key_generator.gen_id(),
967 self.project, name)
968 self.symbols[name] = symbol
969 return symbol
971 def log_symbol_transform(self, old_name, new_name):
972 """Record that OLD_NAME was transformed to NEW_NAME in one file."""
974 try:
975 self.symbol_transform_counts[old_name, new_name] += 1
976 except KeyError:
977 self.symbol_transform_counts[old_name, new_name] = 1
979 def summarize_symbol_transforms(self):
980 if self.symbol_transform_counts and Log().is_on(Log.NORMAL):
981 log = Log()
982 log.normal('Summary of symbol transforms:')
983 transforms = self.symbol_transform_counts.items()
984 transforms.sort()
985 for ((old_name, new_name), count) in transforms:
986 if new_name is None:
987 log.normal(' "%s" ignored in %d files' % (old_name, count,))
988 else:
989 log.normal(
990 ' "%s" transformed to "%s" in %d files'
991 % (old_name, new_name, count,)
994 def _process_cvs_file_items(self, cvs_file_items):
995 """Process the CVSFileItems from one CVSFile."""
997 # Remove CVSRevisionDeletes that are not needed:
998 cvs_file_items.remove_unneeded_deletes(self.collect_data.metadata_db)
1000 # Remove initial branch deletes that are not needed:
1001 cvs_file_items.remove_initial_branch_deletes(
1002 self.collect_data.metadata_db
1005 # If this is a --trunk-only conversion, discard all branches and
1006 # tags, then draft any non-trunk default branch revisions to
1007 # trunk:
1008 if Ctx().trunk_only:
1009 cvs_file_items.exclude_non_trunk()
1011 self.collect_data.revision_recorder.finish_file(cvs_file_items)
1012 self.collect_data.add_cvs_file_items(cvs_file_items)
1013 self.collect_data.symbol_stats.register(cvs_file_items)
1015 def process_file(self, cvs_file):
1016 Log().normal(cvs_file.filename)
1017 fdc = _FileDataCollector(self, cvs_file)
1018 try:
1019 cvs2svn_rcsparse.parse(open(cvs_file.filename, 'rb'), fdc)
1020 except (cvs2svn_rcsparse.common.RCSParseError, ValueError, RuntimeError):
1021 self.collect_data.record_fatal_error(
1022 "%r is not a valid ,v file" % (cvs_file.filename,)
1024 # Abort the processing of this file, but let the pass continue
1025 # with other files:
1026 return
1027 except:
1028 Log().warn("Exception occurred while parsing %s" % cvs_file.filename)
1029 raise
1030 else:
1031 self.num_files += 1
1033 cvs_file_items = fdc.get_cvs_file_items()
1035 del fdc
1037 self._process_cvs_file_items(cvs_file_items)
1040 class CollectData:
1041 """Repository for data collected by parsing the CVS repository files.
1043 This class manages the databases into which information collected
1044 from the CVS repository is stored. The data are stored into this
1045 class by _FileDataCollector instances, one of which is created for
1046 each file to be parsed."""
1048 def __init__(self, revision_recorder, stats_keeper):
1049 self.revision_recorder = revision_recorder
1050 self._cvs_item_store = NewCVSItemStore(
1051 artifact_manager.get_temp_file(config.CVS_ITEMS_STORE))
1052 self.metadata_db = MetadataDatabase(
1053 artifact_manager.get_temp_file(config.METADATA_STORE),
1054 artifact_manager.get_temp_file(config.METADATA_INDEX_TABLE),
1055 DB_OPEN_NEW,
1057 self.metadata_logger = MetadataLogger(self.metadata_db)
1058 self.fatal_errors = []
1059 self.num_files = 0
1060 self.symbol_stats = SymbolStatisticsCollector()
1061 self.stats_keeper = stats_keeper
1063 # Key generator for CVSFiles:
1064 self.file_key_generator = KeyGenerator()
1066 # Key generator for CVSItems:
1067 self.item_key_generator = KeyGenerator()
1069 # Key generator for Symbols:
1070 self.symbol_key_generator = KeyGenerator()
1072 self.revision_recorder.start()
1074 def record_fatal_error(self, err):
1075 """Record that fatal error ERR was found.
1077 ERR is a string (without trailing newline) describing the error.
1078 Output the error to stderr immediately, and record a copy to be
1079 output again in a summary at the end of CollectRevsPass."""
1081 err = '%s: %s' % (error_prefix, err,)
1082 Log().error(err + '\n')
1083 self.fatal_errors.append(err)
1085 def add_cvs_directory(self, cvs_directory):
1086 """Record CVS_DIRECTORY."""
1088 Ctx()._cvs_file_db.log_file(cvs_directory)
1090 def add_cvs_file_items(self, cvs_file_items):
1091 """Record the information from CVS_FILE_ITEMS.
1093 Store the CVSFile to _cvs_file_db under its persistent id, store
1094 the CVSItems, and record the CVSItems to self.stats_keeper."""
1096 Ctx()._cvs_file_db.log_file(cvs_file_items.cvs_file)
1097 self._cvs_item_store.add(cvs_file_items)
1099 self.stats_keeper.record_cvs_file(cvs_file_items.cvs_file)
1100 for cvs_item in cvs_file_items.values():
1101 self.stats_keeper.record_cvs_item(cvs_item)
1103 def _get_cvs_file(
1104 self, parent_directory, basename, file_in_attic, leave_in_attic=False
1106 """Return a CVSFile describing the file with name BASENAME.
1108 PARENT_DIRECTORY is the CVSDirectory instance describing the
1109 directory that physically holds this file in the filesystem.
1110 BASENAME must be the base name of a *,v file within
1111 PARENT_DIRECTORY.
1113 FILE_IN_ATTIC is a boolean telling whether the specified file is
1114 in an Attic subdirectory. If FILE_IN_ATTIC is True, then:
1116 - If LEAVE_IN_ATTIC is True, then leave the 'Attic' component in
1117 the filename.
1119 - Otherwise, raise FileInAndOutOfAtticException if a file with the
1120 same filename appears outside of Attic.
1122 The CVSFile is assigned a new unique id. All of the CVSFile
1123 information is filled in except mode (which can only be determined
1124 by parsing the file).
1126 Raise FatalError if the resulting filename would not be legal in
1127 SVN."""
1129 filename = os.path.join(parent_directory.filename, basename)
1130 try:
1131 verify_svn_filename_legal(basename[:-2])
1132 except IllegalSVNPathError, e:
1133 raise FatalError(
1134 'File %r would result in an illegal SVN filename: %s'
1135 % (filename, e,)
1138 if file_in_attic and not leave_in_attic:
1139 in_attic = True
1140 logical_parent_directory = parent_directory.parent_directory
1142 # If this file also exists outside of the attic, it's a fatal
1143 # error:
1144 non_attic_filename = os.path.join(
1145 logical_parent_directory.filename, basename,
1147 if os.path.exists(non_attic_filename):
1148 raise FileInAndOutOfAtticException(non_attic_filename, filename)
1149 else:
1150 in_attic = False
1151 logical_parent_directory = parent_directory
1153 file_stat = os.stat(filename)
1155 # The size of the file in bytes:
1156 file_size = file_stat[stat.ST_SIZE]
1158 # Whether or not the executable bit is set:
1159 file_executable = bool(file_stat[0] & stat.S_IXUSR)
1161 # mode is not known, so we temporarily set it to None.
1162 return CVSFile(
1163 self.file_key_generator.gen_id(),
1164 parent_directory.project, logical_parent_directory, basename[:-2],
1165 in_attic, file_executable, file_size, None
1168 def _get_attic_file(self, parent_directory, basename):
1169 """Return a CVSFile object for the Attic file at BASENAME.
1171 PARENT_DIRECTORY is the CVSDirectory that physically contains the
1172 file on the filesystem (i.e., the Attic directory). It is not
1173 necessarily the parent_directory of the CVSFile that will be
1174 returned.
1176 Return CVSFile, whose parent directory is usually
1177 PARENT_DIRECTORY.parent_directory, but might be PARENT_DIRECTORY
1178 iff CVSFile will remain in the Attic directory."""
1180 try:
1181 return self._get_cvs_file(parent_directory, basename, True)
1182 except FileInAndOutOfAtticException, e:
1183 if Ctx().retain_conflicting_attic_files:
1184 Log().warn(
1185 "%s: %s;\n"
1186 " storing the latter into 'Attic' subdirectory.\n"
1187 % (warning_prefix, e)
1189 else:
1190 self.record_fatal_error(str(e))
1192 # Either way, return a CVSFile object so that the rest of the
1193 # file processing can proceed:
1194 return self._get_cvs_file(
1195 parent_directory, basename, True, leave_in_attic=True
1198 def _generate_attic_cvs_files(self, cvs_directory):
1199 """Generate CVSFiles for the files in Attic directory CVS_DIRECTORY.
1201 Also add CVS_DIRECTORY to self if any files are being retained in
1202 that directory."""
1204 retained_attic_file = False
1206 fnames = os.listdir(cvs_directory.filename)
1207 fnames.sort()
1208 for fname in fnames:
1209 pathname = os.path.join(cvs_directory.filename, fname)
1210 if os.path.isdir(pathname):
1211 Log().warn("Directory %s found within Attic; ignoring" % (pathname,))
1212 elif fname.endswith(',v'):
1213 cvs_file = self._get_attic_file(cvs_directory, fname)
1214 if cvs_file.parent_directory == cvs_directory:
1215 # This file will be retained in the Attic directory.
1216 retained_attic_file = True
1217 yield cvs_file
1219 if retained_attic_file:
1220 # If any files were retained in the Attic directory, then write
1221 # the Attic directory to CVSFileDatabase:
1222 self.add_cvs_directory(cvs_directory)
1224 def _get_non_attic_file(self, parent_directory, basename):
1225 """Return a CVSFile object for the non-Attic file at BASENAME."""
1227 return self._get_cvs_file(parent_directory, basename, False)
1229 def _generate_cvs_files(self, cvs_directory):
1230 """Generate the CVSFiles under non-Attic directory CVS_DIRECTORY.
1232 Process directories recursively, including Attic directories.
1233 Also create and register CVSDirectories as they are found, and
1234 look for conflicts between the filenames that will result from
1235 files, attic files, and subdirectories."""
1237 self.add_cvs_directory(cvs_directory)
1239 # Map {cvs_file.basename : cvs_file.filename} for files directly
1240 # in cvs_directory:
1241 rcsfiles = {}
1243 attic_dir = None
1245 # Non-Attic subdirectories of cvs_directory (to be recursed into):
1246 dirs = []
1248 fnames = os.listdir(cvs_directory.filename)
1249 fnames.sort()
1250 for fname in fnames:
1251 pathname = os.path.join(cvs_directory.filename, fname)
1252 if os.path.isdir(pathname):
1253 if fname == 'Attic':
1254 attic_dir = fname
1255 else:
1256 dirs.append(fname)
1257 elif fname.endswith(',v'):
1258 cvs_file = self._get_non_attic_file(cvs_directory, fname)
1259 rcsfiles[cvs_file.basename] = cvs_file.filename
1260 yield cvs_file
1261 else:
1262 # Silently ignore other files:
1263 pass
1265 # Map {cvs_file.basename : cvs_file.filename} for files in an
1266 # Attic directory within cvs_directory:
1267 attic_rcsfiles = {}
1269 if attic_dir is not None:
1270 attic_directory = CVSDirectory(
1271 self.file_key_generator.gen_id(),
1272 cvs_directory.project, cvs_directory, 'Attic',
1275 for cvs_file in self._generate_attic_cvs_files(attic_directory):
1276 if cvs_file.parent_directory == cvs_directory:
1277 attic_rcsfiles[cvs_file.basename] = cvs_file.filename
1278 yield cvs_file
1280 alldirs = dirs + [attic_dir]
1281 else:
1282 alldirs = dirs
1284 # Check for conflicts between directory names and the filenames
1285 # that will result from the rcs files (both in this directory and
1286 # in attic). (We recurse into the subdirectories nevertheless, to
1287 # try to detect more problems.)
1288 for fname in alldirs:
1289 pathname = os.path.join(cvs_directory.filename, fname)
1290 for rcsfile_list in [rcsfiles, attic_rcsfiles]:
1291 if fname in rcsfile_list:
1292 self.record_fatal_error(
1293 'Directory name conflicts with filename. Please remove or '
1294 'rename one\n'
1295 'of the following:\n'
1296 ' "%s"\n'
1297 ' "%s"'
1298 % (pathname, rcsfile_list[fname],)
1301 # Now recurse into the other subdirectories:
1302 for fname in dirs:
1303 dirname = os.path.join(cvs_directory.filename, fname)
1305 # Verify that the directory name does not contain any illegal
1306 # characters:
1307 try:
1308 verify_svn_filename_legal(fname)
1309 except IllegalSVNPathError, e:
1310 raise FatalError(
1311 'Directory %r would result in an illegal SVN path name: %s'
1312 % (dirname, e,)
1315 sub_directory = CVSDirectory(
1316 self.file_key_generator.gen_id(),
1317 cvs_directory.project, cvs_directory, fname,
1320 for cvs_file in self._generate_cvs_files(sub_directory):
1321 yield cvs_file
1323 def process_project(self, project):
1324 Ctx()._projects[project.id] = project
1326 root_cvs_directory = CVSDirectory(
1327 self.file_key_generator.gen_id(), project, None, ''
1329 project.root_cvs_directory_id = root_cvs_directory.id
1330 pdc = _ProjectDataCollector(self, project)
1332 found_rcs_file = False
1333 for cvs_file in self._generate_cvs_files(root_cvs_directory):
1334 pdc.process_file(cvs_file)
1335 found_rcs_file = True
1337 if not found_rcs_file:
1338 self.record_fatal_error(
1339 'No RCS files found under %r!\n'
1340 'Are you absolutely certain you are pointing cvs2svn\n'
1341 'at a CVS repository?\n'
1342 % (project.project_cvs_repos_path,)
1345 pdc.summarize_symbol_transforms()
1347 self.num_files += pdc.num_files
1348 Log().verbose('Processed', self.num_files, 'files')
1350 def _set_cvs_path_ordinals(self):
1351 cvs_files = list(Ctx()._cvs_file_db.itervalues())
1352 cvs_files.sort(CVSPath.slow_compare)
1353 for (i, cvs_file) in enumerate(cvs_files):
1354 cvs_file.ordinal = i
1356 def close(self):
1357 """Close the data structures associated with this instance.
1359 Return a list of fatal errors encountered while processing input.
1360 Each list entry is a string describing one fatal error."""
1362 self.revision_recorder.finish()
1363 self.symbol_stats.purge_ghost_symbols()
1364 self.symbol_stats.close()
1365 self.symbol_stats = None
1366 self.metadata_logger = None
1367 self.metadata_db.close()
1368 self.metadata_db = None
1369 self._cvs_item_store.close()
1370 self._cvs_item_store = None
1371 self._set_cvs_path_ordinals()
1372 self.revision_recorder = None
1373 retval = self.fatal_errors
1374 self.fatal_errors = None
1375 return retval