1 # (Be in -*- python -*- mode.)
3 # ====================================================================
4 # Copyright (c) 2000-2009 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
38 _RevisionData -> CVSRevision
40 _BranchData -> CVSBranch
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
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.
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
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:
139 if rev1
.count('.') == 1 and rev2
.count('.') == 1:
141 if rev1
[0:rev1
.rfind('.')] == rev2
[0:rev2
.rfind('.')]:
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
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
159 self
.timestamp
= timestamp
161 self
.original_timestamp
= timestamp
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.
178 # The revision number of the primary child of this revision (the
179 # child along the same line of development), if any; otherwise,
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
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
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.
226 # An instance of 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.
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').
258 class _SymbolDataCollector(object):
259 """Collect information about symbols in a single CVSFile."""
261 def __init__(self
, fdc
, cvs_file
):
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
274 self
._symbol
_defs
= []
276 # A set containing the transformed names of symbols in this file
277 # (used to detect duplicats during processing of unlabeled
279 self
._defined
_symbols
= set()
281 # Map { branch_number : _BranchData }, where branch_number has an
282 # odd number of digits.
283 self
.branches_data
= { }
285 # Map { revision : [ tag_data ] }, where revision has an even
286 # number of digits, and the value is a list of _TagData objects
287 # for tags that apply to that revision.
290 def _add_branch(self
, name
, branch_number
):
291 """Record that BRANCH_NUMBER is the branch number for branch NAME,
292 and derive and record the revision from which NAME sprouts.
293 BRANCH_NUMBER is an RCS branch number with an odd number of
294 components, for example '1.7.2' (never '1.7.0.2'). Return the
295 _BranchData instance (which is usually newly-created)."""
297 branch_data
= self
.branches_data
.get(branch_number
)
299 if branch_data
is not None:
302 " branch '%s' already has name '%s',\n"
303 " cannot also have name '%s', ignoring the latter\n"
305 self
.cvs_file
.filename
, branch_number
,
306 branch_data
.symbol
.name
, name
)
310 symbol
= self
.pdc
.get_symbol(name
)
311 branch_data
= _BranchData(
312 self
.collect_data
.item_key_generator
.gen_id(), symbol
, branch_number
314 self
.branches_data
[branch_number
] = branch_data
317 def _construct_distinct_name(self
, name
, original_name
):
318 """Construct a distinct symbol name from NAME.
320 If NAME is distinct, return it. If it is already used in this
321 file (as determined from its presence in self._defined_symbols),
322 construct and return a new name that is not already used."""
324 if name
not in self
._defined
_symbols
:
329 dup_name
= '%s-DUPLICATE-%d' % (name
, index
,)
330 if dup_name
not in self
._defined
_symbols
:
331 self
.collect_data
.record_fatal_error(
332 "Symbol name '%s' is already used in '%s'.\n"
333 "The unlabeled branch '%s' must be renamed using "
334 "--symbol-transform."
335 % (name
, self
.cvs_file
.filename
, original_name
,)
339 def _add_unlabeled_branch(self
, branch_number
):
340 original_name
= "unlabeled-" + branch_number
341 name
= self
.transform_symbol(original_name
, branch_number
)
343 self
.collect_data
.record_fatal_error(
344 "The unlabeled branch '%s' in '%s' contains commits.\n"
345 "It may not be ignored via a symbol transform. (Use --exclude "
347 % (original_name
, self
.cvs_file
.filename
,)
349 # Retain the original name to allow the conversion to continue:
352 distinct_name
= self
._construct
_distinct
_name
(name
, original_name
)
353 self
._defined
_symbols
.add(distinct_name
)
354 return self
._add
_branch
(distinct_name
, branch_number
)
356 def _add_tag(self
, name
, revision
):
357 """Record that tag NAME refers to the specified REVISION."""
359 symbol
= self
.pdc
.get_symbol(name
)
361 self
.collect_data
.item_key_generator
.gen_id(), symbol
, revision
363 self
.tags_data
.setdefault(revision
, []).append(tag_data
)
366 def transform_symbol(self
, name
, revision
):
367 """Transform a symbol according to the project's symbol transforms.
369 Transform the symbol with the original name NAME and canonicalized
370 revision number REVISION. Return the new symbol name or None if
371 the symbol should be ignored entirely.
373 Log the results of the symbol transform if necessary."""
376 # Apply any user-defined symbol transforms to the symbol name:
377 name
= self
.cvs_file
.project
.transform_symbol(
378 self
.cvs_file
, name
, revision
383 self
.pdc
.log_symbol_transform(old_name
, None)
385 " symbol '%s'=%s ignored in %s"
386 % (old_name
, revision
, self
.cvs_file
.filename
,)
390 self
.pdc
.log_symbol_transform(old_name
, name
)
392 " symbol '%s'=%s transformed to '%s' in %s"
393 % (old_name
, revision
, name
, self
.cvs_file
.filename
,)
398 def define_symbol(self
, name
, revision
):
399 """Record a symbol definition for later processing."""
401 # Canonicalize the revision number:
402 revision
= _branch_revision_re
.sub(r
'\1\2', revision
)
404 # Apply any user-defined symbol transforms to the symbol name:
405 name
= self
.transform_symbol(name
, revision
)
408 # Verify that the revision number is valid:
409 if _valid_revision_re
.match(revision
):
410 # The revision number is valid; record it for later processing:
411 self
._symbol
_defs
.append( (name
, revision
) )
415 ' branch %r references invalid revision %s\n'
416 ' and will be ignored.'
417 % (self
.cvs_file
.filename
, name
, revision
,)
420 def _eliminate_trivial_duplicate_defs(self
, symbol_defs
):
421 """Iterate through SYMBOL_DEFS, Removing identical duplicate definitions.
423 Duplicate definitions of symbol names have been seen in the wild,
424 and they can also happen when --symbol-transform is used. If a
425 symbol is defined to the same revision number repeatedly, then
426 ignore all but the last definition."""
428 # Make a copy, since we have to iterate through the definitions
430 symbol_defs
= list(symbol_defs
)
432 # A map { (name, revision) : [index,...] } of the indexes where
433 # symbol definitions name=revision were found:
434 known_definitions
= {}
435 for (i
, symbol_def
) in enumerate(symbol_defs
):
436 known_definitions
.setdefault(symbol_def
, []).append(i
)
438 # A set of the indexes of entries that have to be removed from
441 for ((name
, revision
), indexes
) in known_definitions
.iteritems():
445 " symbol %s:%s defined multiple times; ignoring duplicates\n"
446 % (self
.cvs_file
.filename
, name
, revision
,)
448 dup_indexes
.update(indexes
[:-1])
450 for (i
, symbol_def
) in enumerate(symbol_defs
):
451 if i
not in dup_indexes
:
454 def _process_duplicate_defs(self
, symbol_defs
):
455 """Iterate through SYMBOL_DEFS, processing duplicate names.
457 Duplicate definitions of symbol names have been seen in the wild,
458 and they can also happen when --symbol-transform is used. If a
459 symbol is defined multiple times, then it is a fatal error. This
460 method should be called after _eliminate_trivial_duplicate_defs()."""
462 # Make a copy, since we have to access multiple times:
463 symbol_defs
= list(symbol_defs
)
465 # A map {name : [index,...]} mapping the names of symbols to a
466 # list of their definitions' indexes in symbol_defs:
468 for (i
, (name
, revision
)) in enumerate(symbol_defs
):
469 known_symbols
.setdefault(name
, []).append(i
)
471 known_symbols
= known_symbols
.items()
474 for (name
, indexes
) in known_symbols
:
476 # This symbol was defined multiple times.
477 self
.collect_data
.record_fatal_error(
478 "Multiple definitions of the symbol '%s' in '%s': %s" % (
479 name
, self
.cvs_file
.filename
,
480 ' '.join([symbol_defs
[i
][1] for i
in indexes
]),
483 # Ignore all but the last definition for now, to allow the
484 # conversion to proceed:
485 dup_indexes
.update(indexes
[:-1])
487 for (i
, symbol_def
) in enumerate(symbol_defs
):
488 if i
not in dup_indexes
:
491 def _process_symbol(self
, name
, revision
):
492 """Process a symbol called NAME, which is associated with REVISON.
494 REVISION is a canonical revision number with zeros removed, for
495 example: '1.7', '1.7.2', or '1.1.1' or '1.1.1.1'. NAME is a
496 transformed branch or tag name."""
498 # Add symbol to our records:
499 if is_branch_revision_number(revision
):
500 self
._add
_branch
(name
, revision
)
502 self
._add
_tag
(name
, revision
)
504 def process_symbols(self
):
505 """Process the symbol definitions from SELF._symbol_defs."""
507 symbol_defs
= self
._symbol
_defs
508 del self
._symbol
_defs
510 symbol_defs
= self
._eliminate
_trivial
_duplicate
_defs
(symbol_defs
)
511 symbol_defs
= self
._process
_duplicate
_defs
(symbol_defs
)
513 for (name
, revision
) in symbol_defs
:
514 self
._defined
_symbols
.add(name
)
515 self
._process
_symbol
(name
, revision
)
518 def rev_to_branch_number(revision
):
519 """Return the branch_number of the branch on which REVISION lies.
521 REVISION is a branch revision number with an even number of
522 components; for example '1.7.2.1' (never '1.7.2' nor '1.7.0.2').
523 The return value is the branch number (for example, '1.7.2').
524 Return none iff REVISION is a trunk revision such as '1.2'."""
526 if is_trunk_revision(revision
):
528 return revision
[:revision
.rindex(".")]
530 def rev_to_branch_data(self
, revision
):
531 """Return the branch_data of the branch on which REVISION lies.
533 REVISION must be a branch revision number with an even number of
534 components; for example '1.7.2.1' (never '1.7.2' nor '1.7.0.2').
535 Raise KeyError iff REVISION is unknown."""
537 assert not is_trunk_revision(revision
)
539 return self
.branches_data
[self
.rev_to_branch_number(revision
)]
541 def rev_to_lod(self
, revision
):
542 """Return the line of development on which REVISION lies.
544 REVISION must be a revision number with an even number of
545 components. Raise KeyError iff REVISION is unknown."""
547 if is_trunk_revision(revision
):
548 return self
.pdc
.trunk
550 return self
.rev_to_branch_data(revision
).symbol
553 class _FileDataCollector(cvs2svn_rcsparse
.Sink
):
554 """Class responsible for collecting RCS data for a particular file.
556 Any collected data that need to be remembered are stored into the
557 referenced CollectData instance."""
559 def __init__(self
, pdc
, cvs_file
):
560 """Create an object that is prepared to receive data for CVS_FILE.
561 CVS_FILE is a CVSFile instance. COLLECT_DATA is used to store the
562 information collected about the file."""
565 self
.cvs_file
= cvs_file
567 self
.collect_data
= self
.pdc
.collect_data
568 self
.project
= self
.cvs_file
.project
570 # A place to store information about the symbols in this file:
571 self
.sdc
= _SymbolDataCollector(self
, self
.cvs_file
)
573 # { revision : _RevisionData instance }
576 # Lists [ (parent, child) ] of revision number pairs indicating
577 # that revision child depends on revision parent along the main
578 # line of development.
579 self
._primary
_dependencies
= []
581 # If set, this is an RCS branch number -- rcsparse calls this the
582 # "principal branch", but CVS and RCS refer to it as the "default
583 # branch", so that's what we call it, even though the rcsparse API
584 # setter method is still 'set_principal_branch'.
585 self
.default_branch
= None
587 # True iff revision 1.1 of the file appears to have been imported
588 # (as opposed to added normally).
589 self
._file
_imported
= False
591 def _get_rev_id(self
, revision
):
594 return self
._rev
_data
[revision
].cvs_rev_id
596 def set_principal_branch(self
, branch
):
597 """This is a callback method declared in Sink."""
599 if branch
.find('.') == -1:
600 # This just sets the default branch to trunk. Normally this
601 # shouldn't occur, but it has been seen in at least one CVS
602 # repository. Just ignore it.
605 self
.default_branch
= branch
607 def set_expansion(self
, mode
):
608 """This is a callback method declared in Sink."""
610 self
.cvs_file
.mode
= mode
612 def define_tag(self
, name
, revision
):
613 """Remember the symbol name and revision, but don't process them yet.
615 This is a callback method declared in Sink."""
617 self
.sdc
.define_symbol(name
, revision
)
619 def admin_completed(self
):
620 """This is a callback method declared in Sink."""
622 self
.sdc
.process_symbols()
624 def define_revision(self
, revision
, timestamp
, author
, state
,
626 """This is a callback method declared in Sink."""
628 for branch
in branches
:
630 branch_data
= self
.sdc
.rev_to_branch_data(branch
)
632 # Normally we learn about the branches from the branch names
633 # and numbers parsed from the symbolic name header. But this
634 # must have been an unlabeled branch that slipped through the
635 # net. Generate a name for it and create a _BranchData record
637 branch_data
= self
.sdc
._add
_unlabeled
_branch
(
638 self
.sdc
.rev_to_branch_number(branch
))
640 assert branch_data
.child
is None
641 branch_data
.child
= branch
643 if revision
in self
._rev
_data
:
644 # This revision has already been seen.
645 Log().error('File %r contains duplicate definitions of revision %s.'
646 % (self
.cvs_file
.filename
, revision
,))
649 # Record basic information about the revision:
650 rev_data
= _RevisionData(
651 self
.collect_data
.item_key_generator
.gen_id(),
652 revision
, int(timestamp
), author
, state
)
653 self
._rev
_data
[revision
] = rev_data
655 # When on trunk, the RCS 'next' revision number points to what
656 # humans might consider to be the 'previous' revision number. For
657 # example, 1.3's RCS 'next' is 1.2.
659 # However, on a branch, the RCS 'next' revision number really does
660 # point to what humans would consider to be the 'next' revision
661 # number. For example, 1.1.2.1's RCS 'next' would be 1.1.2.2.
663 # In other words, in RCS, 'next' always means "where to find the next
664 # deltatext that you need this revision to retrieve.
666 # That said, we don't *want* RCS's behavior here, so we determine
667 # whether we're on trunk or a branch and set the dependencies
670 if is_trunk_revision(revision
):
671 self
._primary
_dependencies
.append( (next
, revision
,) )
673 self
._primary
_dependencies
.append( (revision
, next
,) )
675 def _resolve_primary_dependencies(self
):
676 """Resolve the dependencies listed in self._primary_dependencies."""
678 for (parent
, child
,) in self
._primary
_dependencies
:
679 parent_data
= self
._rev
_data
[parent
]
680 assert parent_data
.child
is None
681 parent_data
.child
= child
683 child_data
= self
._rev
_data
[child
]
684 assert child_data
.parent
is None
685 child_data
.parent
= parent
687 def _resolve_branch_dependencies(self
):
688 """Resolve dependencies involving branches."""
690 for branch_data
in self
.sdc
.branches_data
.values():
691 # The branch_data's parent has the branch as a child regardless
692 # of whether the branch had any subsequent commits:
694 parent_data
= self
._rev
_data
[branch_data
.parent
]
698 ' branch %r references non-existing revision %s\n'
699 ' and will be ignored.'
700 % (self
.cvs_file
.filename
, branch_data
.symbol
.name
,
701 branch_data
.parent
,))
702 del self
.sdc
.branches_data
[branch_data
.branch_number
]
704 parent_data
.branches_data
.append(branch_data
)
706 # If the branch has a child (i.e., something was committed on
707 # the branch), then we store a reference to the branch_data
708 # there, define the child's parent to be the branch's parent,
709 # and list the child in the branch parent's branches_revs_data:
710 if branch_data
.child
is not None:
711 child_data
= self
._rev
_data
[branch_data
.child
]
712 assert child_data
.parent_branch_data
is None
713 child_data
.parent_branch_data
= branch_data
714 assert child_data
.parent
is None
715 child_data
.parent
= branch_data
.parent
716 parent_data
.branches_revs_data
.append(branch_data
.child
)
718 def _sort_branches(self
):
719 """Sort the branches sprouting from each revision in creation order.
721 Creation order is taken to be the reverse of the order that they
722 are listed in the symbols part of the RCS file. (If a branch is
723 created then deleted, a later branch can be assigned the recycled
724 branch number; therefore branch numbers are not an indication of
727 for rev_data
in self
._rev
_data
.values():
728 rev_data
.branches_data
.sort(lambda a
, b
: - cmp(a
.id, b
.id))
730 def _resolve_tag_dependencies(self
):
731 """Resolve dependencies involving tags."""
733 for (rev
, tag_data_list
) in self
.sdc
.tags_data
.items():
735 parent_data
= self
._rev
_data
[rev
]
739 ' the following tag(s) reference non-existing revision %s\n'
740 ' and will be ignored:\n'
742 self
.cvs_file
.filename
, rev
,
743 ', '.join([repr(tag_data
.symbol
.name
)
744 for tag_data
in tag_data_list
]),))
745 del self
.sdc
.tags_data
[rev
]
747 for tag_data
in tag_data_list
:
748 assert tag_data
.rev
== rev
749 # The tag_data's rev has the tag as a child:
750 parent_data
.tags_data
.append(tag_data
)
752 def _determine_operation(self
, rev_data
):
753 prev_rev_data
= self
._rev
_data
.get(rev_data
.parent
)
754 return cvs_revision_type_map
[(
755 rev_data
.state
!= 'dead',
756 prev_rev_data
is not None and prev_rev_data
.state
!= 'dead',
759 def _get_cvs_revision(self
, rev_data
):
760 """Create and return a CVSRevision for REV_DATA."""
764 for branch_data
in rev_data
.branches_data
767 branch_commit_ids
= [
768 self
._get
_rev
_id
(rev
)
769 for rev
in rev_data
.branches_revs_data
774 for tag_data
in rev_data
.tags_data
777 revision_type
= self
._determine
_operation
(rev_data
)
779 return revision_type(
780 self
._get
_rev
_id
(rev_data
.rev
), self
.cvs_file
,
781 rev_data
.timestamp
, None,
782 self
._get
_rev
_id
(rev_data
.parent
),
783 self
._get
_rev
_id
(rev_data
.child
),
786 self
.sdc
.rev_to_lod(rev_data
.rev
),
787 rev_data
.get_first_on_branch_id(),
789 tag_ids
, branch_ids
, branch_commit_ids
,
790 rev_data
.revision_recorder_token
)
792 def _get_cvs_revisions(self
):
793 """Generate the CVSRevisions present in this file."""
795 for rev_data
in self
._rev
_data
.itervalues():
796 yield self
._get
_cvs
_revision
(rev_data
)
798 def _get_cvs_branches(self
):
799 """Generate the CVSBranches present in this file."""
801 for branch_data
in self
.sdc
.branches_data
.values():
803 branch_data
.id, self
.cvs_file
, branch_data
.symbol
,
804 branch_data
.branch_number
,
805 self
.sdc
.rev_to_lod(branch_data
.parent
),
806 self
._get
_rev
_id
(branch_data
.parent
),
807 self
._get
_rev
_id
(branch_data
.child
),
811 def _get_cvs_tags(self
):
812 """Generate the CVSTags present in this file."""
814 for tags_data
in self
.sdc
.tags_data
.values():
815 for tag_data
in tags_data
:
817 tag_data
.id, self
.cvs_file
, tag_data
.symbol
,
818 self
.sdc
.rev_to_lod(tag_data
.rev
),
819 self
._get
_rev
_id
(tag_data
.rev
),
823 def tree_completed(self
):
824 """The revision tree has been parsed.
826 Analyze it for consistency and connect some loose ends.
828 This is a callback method declared in Sink."""
830 self
._resolve
_primary
_dependencies
()
831 self
._resolve
_branch
_dependencies
()
832 self
._sort
_branches
()
833 self
._resolve
_tag
_dependencies
()
835 # Compute the preliminary CVSFileItems for this file:
837 cvs_items
.extend(self
._get
_cvs
_revisions
())
838 cvs_items
.extend(self
._get
_cvs
_branches
())
839 cvs_items
.extend(self
._get
_cvs
_tags
())
840 self
._cvs
_file
_items
= CVSFileItems(
841 self
.cvs_file
, self
.pdc
.trunk
, cvs_items
844 self
._cvs
_file
_items
.check_link_consistency()
846 # Tell the revision recorder about the file dependency tree.
847 self
.collect_data
.revision_recorder
.start_file(self
._cvs
_file
_items
)
849 def set_revision_info(self
, revision
, log
, text
):
850 """This is a callback method declared in Sink."""
852 rev_data
= self
._rev
_data
[revision
]
853 cvs_rev
= self
._cvs
_file
_items
[rev_data
.cvs_rev_id
]
855 if cvs_rev
.metadata_id
is not None:
856 # Users have reported problems with repositories in which the
857 # deltatext block for revision 1.1 appears twice. It is not
858 # known whether this results from a CVS/RCS bug, or from botched
859 # hand-editing of the repository. In any case, empirically, cvs
860 # and rcs both use the first version when checking out data, so
861 # that's what we will do. (For the record: "cvs log" fails on
862 # such a file; "rlog" prints the log message from the first
863 # block and ignores the second one.)
866 " Deltatext block for revision %s appeared twice;\n"
867 " ignoring the second occurrence.\n"
868 % (warning_prefix
, self
.cvs_file
.filename
, revision
,)
872 if is_trunk_revision(revision
):
875 branch_name
= self
.sdc
.rev_to_branch_data(revision
).symbol
.name
877 cvs_rev
.metadata_id
= self
.collect_data
.metadata_logger
.store(
878 self
.project
, branch_name
, rev_data
.author
, log
880 cvs_rev
.deltatext_exists
= bool(text
)
882 # If this is revision 1.1, determine whether the file appears to
883 # have been created via 'cvs add' instead of 'cvs import'. The
884 # test is that the log message CVS uses for 1.1 in imports is
885 # "Initial revision\n" with no period. (This fact helps determine
886 # whether this file might have had a default branch in the past.)
887 if revision
== '1.1':
888 self
._file
_imported
= (log
== 'Initial revision\n')
890 cvs_rev
.revision_recorder_token
= \
891 self
.collect_data
.revision_recorder
.record_text(cvs_rev
, log
, text
)
893 def parse_completed(self
):
894 """Finish the processing of this file.
896 This is a callback method declared in Sink."""
898 # Make sure that there was an info section for each revision:
899 for cvs_item
in self
._cvs
_file
_items
.values():
900 if isinstance(cvs_item
, CVSRevision
) and cvs_item
.metadata_id
is None:
901 self
.collect_data
.record_fatal_error(
902 '%r has no deltatext section for revision %s'
903 % (self
.cvs_file
.filename
, cvs_item
.rev
,)
906 def _process_ntdbrs(self
):
907 """Fix up any non-trunk default branch revisions (if present).
909 If a non-trunk default branch is determined to have existed, yield
910 the _RevisionData.ids for all revisions that were once non-trunk
911 default revisions, in dependency order.
913 There are two cases to handle:
915 One case is simple. The RCS file lists a default branch
916 explicitly in its header, such as '1.1.1'. In this case, we know
917 that every revision on the vendor branch is to be treated as head
918 of trunk at that point in time.
920 But there's also a degenerate case. The RCS file does not
921 currently have a default branch, yet we can deduce that for some
922 period in the past it probably *did* have one. For example, the
923 file has vendor revisions 1.1.1.1 -> 1.1.1.96, all of which are
924 dated before 1.2, and then it has 1.1.1.97 -> 1.1.1.100 dated
925 after 1.2. In this case, we should record 1.1.1.96 as the last
926 vendor revision to have been the head of the default branch.
928 If any non-trunk default branch revisions are found:
930 - Set their ntdbr members to True.
932 - Connect the last one with revision 1.2.
934 - Remove revision 1.1 if it is not needed.
939 if self
.default_branch
:
940 vendor_cvs_branch_id
= self
.sdc
.branches_data
[self
.default_branch
].id
941 vendor_lod_items
= self
._cvs
_file
_items
.get_lod_items(
942 self
._cvs
_file
_items
[vendor_cvs_branch_id
]
944 if not self
._cvs
_file
_items
.process_live_ntdb(vendor_lod_items
):
946 elif self
._file
_imported
:
947 vendor_branch_data
= self
.sdc
.branches_data
.get('1.1.1')
948 if vendor_branch_data
is None:
951 vendor_lod_items
= self
._cvs
_file
_items
.get_lod_items(
952 self
._cvs
_file
_items
[vendor_branch_data
.id]
954 if not self
._cvs
_file
_items
.process_historical_ntdb(
960 except VendorBranchError
, e
:
961 self
.collect_data
.record_fatal_error(str(e
))
964 if self
._file
_imported
:
965 self
._cvs
_file
_items
.imported_remove_1_1(vendor_lod_items
)
967 self
._cvs
_file
_items
.check_link_consistency()
969 def get_cvs_file_items(self
):
970 """Finish up and return a CVSFileItems instance for this file.
972 This method must only be called once."""
974 self
._process
_ntdbrs
()
976 # Break a circular reference loop, allowing the memory for self
977 # and sdc to be freed.
980 return self
._cvs
_file
_items
983 class _ProjectDataCollector
:
984 def __init__(self
, collect_data
, project
):
985 self
.collect_data
= collect_data
986 self
.project
= project
989 # The Trunk LineOfDevelopment object for this project:
991 self
.collect_data
.symbol_key_generator
.gen_id(), self
.project
993 self
.project
.trunk_id
= self
.trunk
.id
995 # This causes a record for self.trunk to spring into existence:
996 self
.collect_data
.symbol_stats
[self
.trunk
]
998 # A map { name -> Symbol } for all known symbols in this project.
999 # The symbols listed here are undifferentiated into Branches and
1000 # Tags because the same name might appear as a branch in one file
1001 # and a tag in another.
1004 # A map { (old_name, new_name) : count } indicating how many files
1005 # were affected by each each symbol name transformation:
1006 self
.symbol_transform_counts
= {}
1008 def get_symbol(self
, name
):
1009 """Return the Symbol object for the symbol named NAME in this project.
1011 If such a symbol does not yet exist, allocate a new symbol_id,
1012 create a Symbol instance, store it in self.symbols, and return it."""
1014 symbol
= self
.symbols
.get(name
)
1017 self
.collect_data
.symbol_key_generator
.gen_id(),
1019 self
.symbols
[name
] = symbol
1022 def log_symbol_transform(self
, old_name
, new_name
):
1023 """Record that OLD_NAME was transformed to NEW_NAME in one file.
1025 This information is used to generated a statistical summary of
1026 symbol transforms."""
1029 self
.symbol_transform_counts
[old_name
, new_name
] += 1
1031 self
.symbol_transform_counts
[old_name
, new_name
] = 1
1033 def summarize_symbol_transforms(self
):
1034 if self
.symbol_transform_counts
and Log().is_on(Log
.NORMAL
):
1036 log
.normal('Summary of symbol transforms:')
1037 transforms
= self
.symbol_transform_counts
.items()
1039 for ((old_name
, new_name
), count
) in transforms
:
1040 if new_name
is None:
1041 log
.normal(' "%s" ignored in %d files' % (old_name
, count
,))
1044 ' "%s" transformed to "%s" in %d files'
1045 % (old_name
, new_name
, count
,)
1048 def _process_cvs_file_items(self
, cvs_file_items
):
1049 """Process the CVSFileItems from one CVSFile."""
1051 # Remove an initial delete on trunk if it is not needed:
1052 cvs_file_items
.remove_unneeded_initial_trunk_delete(
1053 self
.collect_data
.metadata_db
1056 # Remove initial branch deletes that are not needed:
1057 cvs_file_items
.remove_initial_branch_deletes(
1058 self
.collect_data
.metadata_db
1061 # If this is a --trunk-only conversion, discard all branches and
1062 # tags, then draft any non-trunk default branch revisions to
1064 if Ctx().trunk_only
:
1065 cvs_file_items
.exclude_non_trunk()
1067 cvs_file_items
.check_link_consistency()
1069 self
.collect_data
.revision_recorder
.finish_file(cvs_file_items
)
1070 self
.collect_data
.add_cvs_file_items(cvs_file_items
)
1071 self
.collect_data
.symbol_stats
.register(cvs_file_items
)
1073 def process_file(self
, cvs_file
):
1074 Log().normal(cvs_file
.filename
)
1075 fdc
= _FileDataCollector(self
, cvs_file
)
1077 cvs2svn_rcsparse
.parse(open(cvs_file
.filename
, 'rb'), fdc
)
1078 except (cvs2svn_rcsparse
.common
.RCSParseError
, ValueError, RuntimeError):
1079 self
.collect_data
.record_fatal_error(
1080 "%r is not a valid ,v file" % (cvs_file
.filename
,)
1082 # Abort the processing of this file, but let the pass continue
1086 Log().warn("Exception occurred while parsing %s" % cvs_file
.filename
)
1091 cvs_file_items
= fdc
.get_cvs_file_items()
1095 self
._process
_cvs
_file
_items
(cvs_file_items
)
1099 """Repository for data collected by parsing the CVS repository files.
1101 This class manages the databases into which information collected
1102 from the CVS repository is stored. The data are stored into this
1103 class by _FileDataCollector instances, one of which is created for
1104 each file to be parsed."""
1106 def __init__(self
, revision_recorder
, stats_keeper
):
1107 self
.revision_recorder
= revision_recorder
1108 self
._cvs
_item
_store
= NewCVSItemStore(
1109 artifact_manager
.get_temp_file(config
.CVS_ITEMS_STORE
))
1110 self
.metadata_db
= MetadataDatabase(
1111 artifact_manager
.get_temp_file(config
.METADATA_STORE
),
1112 artifact_manager
.get_temp_file(config
.METADATA_INDEX_TABLE
),
1115 self
.metadata_logger
= MetadataLogger(self
.metadata_db
)
1116 self
.fatal_errors
= []
1118 self
.symbol_stats
= SymbolStatisticsCollector()
1119 self
.stats_keeper
= stats_keeper
1121 # Key generator for CVSFiles:
1122 self
.file_key_generator
= KeyGenerator()
1124 # Key generator for CVSItems:
1125 self
.item_key_generator
= KeyGenerator()
1127 # Key generator for Symbols:
1128 self
.symbol_key_generator
= KeyGenerator()
1130 self
.revision_recorder
.start()
1132 def record_fatal_error(self
, err
):
1133 """Record that fatal error ERR was found.
1135 ERR is a string (without trailing newline) describing the error.
1136 Output the error to stderr immediately, and record a copy to be
1137 output again in a summary at the end of CollectRevsPass."""
1139 err
= '%s: %s' % (error_prefix
, err
,)
1140 Log().error(err
+ '\n')
1141 self
.fatal_errors
.append(err
)
1143 def add_cvs_directory(self
, cvs_directory
):
1144 """Record CVS_DIRECTORY."""
1146 Ctx()._cvs
_file
_db
.log_file(cvs_directory
)
1148 def add_cvs_file_items(self
, cvs_file_items
):
1149 """Record the information from CVS_FILE_ITEMS.
1151 Store the CVSFile to _cvs_file_db under its persistent id, store
1152 the CVSItems, and record the CVSItems to self.stats_keeper."""
1154 Ctx()._cvs
_file
_db
.log_file(cvs_file_items
.cvs_file
)
1155 self
._cvs
_item
_store
.add(cvs_file_items
)
1157 self
.stats_keeper
.record_cvs_file(cvs_file_items
.cvs_file
)
1158 for cvs_item
in cvs_file_items
.values():
1159 self
.stats_keeper
.record_cvs_item(cvs_item
)
1162 self
, parent_directory
, basename
, file_in_attic
, leave_in_attic
=False
1164 """Return a CVSFile describing the file with name BASENAME.
1166 PARENT_DIRECTORY is the CVSDirectory instance describing the
1167 directory that physically holds this file in the filesystem.
1168 BASENAME must be the base name of a *,v file within
1171 FILE_IN_ATTIC is a boolean telling whether the specified file is
1172 in an Attic subdirectory. If FILE_IN_ATTIC is True, then:
1174 - If LEAVE_IN_ATTIC is True, then leave the 'Attic' component in
1177 - Otherwise, raise FileInAndOutOfAtticException if a file with the
1178 same filename appears outside of Attic.
1180 The CVSFile is assigned a new unique id. All of the CVSFile
1181 information is filled in except mode (which can only be determined
1182 by parsing the file).
1184 Raise FatalError if the resulting filename would not be legal in
1187 filename
= os
.path
.join(parent_directory
.filename
, basename
)
1189 verify_svn_filename_legal(basename
[:-2])
1190 except IllegalSVNPathError
, e
:
1192 'File %r would result in an illegal SVN filename: %s'
1196 if file_in_attic
and not leave_in_attic
:
1198 logical_parent_directory
= parent_directory
.parent_directory
1200 # If this file also exists outside of the attic, it's a fatal
1202 non_attic_filename
= os
.path
.join(
1203 logical_parent_directory
.filename
, basename
,
1205 if os
.path
.exists(non_attic_filename
):
1206 raise FileInAndOutOfAtticException(non_attic_filename
, filename
)
1209 logical_parent_directory
= parent_directory
1211 file_stat
= os
.stat(filename
)
1213 # The size of the file in bytes:
1214 file_size
= file_stat
[stat
.ST_SIZE
]
1216 # Whether or not the executable bit is set:
1217 file_executable
= bool(file_stat
[0] & stat
.S_IXUSR
)
1219 # mode is not known, so we temporarily set it to None.
1221 self
.file_key_generator
.gen_id(),
1222 parent_directory
.project
, logical_parent_directory
, basename
[:-2],
1223 in_attic
, file_executable
, file_size
, None
1226 def _get_attic_file(self
, parent_directory
, basename
):
1227 """Return a CVSFile object for the Attic file at BASENAME.
1229 PARENT_DIRECTORY is the CVSDirectory that physically contains the
1230 file on the filesystem (i.e., the Attic directory). It is not
1231 necessarily the parent_directory of the CVSFile that will be
1234 Return CVSFile, whose parent directory is usually
1235 PARENT_DIRECTORY.parent_directory, but might be PARENT_DIRECTORY
1236 iff CVSFile will remain in the Attic directory."""
1239 return self
._get
_cvs
_file
(parent_directory
, basename
, True)
1240 except FileInAndOutOfAtticException
, e
:
1241 if Ctx().retain_conflicting_attic_files
:
1244 " storing the latter into 'Attic' subdirectory.\n"
1245 % (warning_prefix
, e
)
1248 self
.record_fatal_error(str(e
))
1250 # Either way, return a CVSFile object so that the rest of the
1251 # file processing can proceed:
1252 return self
._get
_cvs
_file
(
1253 parent_directory
, basename
, True, leave_in_attic
=True
1256 def _generate_attic_cvs_files(self
, cvs_directory
):
1257 """Generate CVSFiles for the files in Attic directory CVS_DIRECTORY.
1259 Also add CVS_DIRECTORY to self if any files are being retained in
1262 retained_attic_file
= False
1264 fnames
= os
.listdir(cvs_directory
.filename
)
1266 for fname
in fnames
:
1267 pathname
= os
.path
.join(cvs_directory
.filename
, fname
)
1268 if os
.path
.isdir(pathname
):
1269 Log().warn("Directory %s found within Attic; ignoring" % (pathname
,))
1270 elif fname
.endswith(',v'):
1271 cvs_file
= self
._get
_attic
_file
(cvs_directory
, fname
)
1272 if cvs_file
.parent_directory
== cvs_directory
:
1273 # This file will be retained in the Attic directory.
1274 retained_attic_file
= True
1277 if retained_attic_file
:
1278 # If any files were retained in the Attic directory, then write
1279 # the Attic directory to CVSFileDatabase:
1280 self
.add_cvs_directory(cvs_directory
)
1282 def _get_non_attic_file(self
, parent_directory
, basename
):
1283 """Return a CVSFile object for the non-Attic file at BASENAME."""
1285 return self
._get
_cvs
_file
(parent_directory
, basename
, False)
1287 def _generate_cvs_files(self
, cvs_directory
):
1288 """Generate the CVSFiles under non-Attic directory CVS_DIRECTORY.
1290 Process directories recursively, including Attic directories.
1291 Also create and register CVSDirectories as they are found, and
1292 look for conflicts between the filenames that will result from
1293 files, attic files, and subdirectories."""
1295 self
.add_cvs_directory(cvs_directory
)
1297 # Map {cvs_file.basename : cvs_file.filename} for files directly
1303 # Non-Attic subdirectories of cvs_directory (to be recursed into):
1306 fnames
= os
.listdir(cvs_directory
.filename
)
1308 for fname
in fnames
:
1309 pathname
= os
.path
.join(cvs_directory
.filename
, fname
)
1310 if os
.path
.isdir(pathname
):
1311 if fname
== 'Attic':
1315 elif fname
.endswith(',v'):
1316 cvs_file
= self
._get
_non
_attic
_file
(cvs_directory
, fname
)
1317 rcsfiles
[cvs_file
.basename
] = cvs_file
.filename
1320 # Silently ignore other files:
1323 # Map {cvs_file.basename : cvs_file.filename} for files in an
1324 # Attic directory within cvs_directory:
1327 if attic_dir
is not None:
1328 attic_directory
= CVSDirectory(
1329 self
.file_key_generator
.gen_id(),
1330 cvs_directory
.project
, cvs_directory
, 'Attic',
1333 for cvs_file
in self
._generate
_attic
_cvs
_files
(attic_directory
):
1334 if cvs_file
.parent_directory
== cvs_directory
:
1335 attic_rcsfiles
[cvs_file
.basename
] = cvs_file
.filename
1338 alldirs
= dirs
+ [attic_dir
]
1342 # Check for conflicts between directory names and the filenames
1343 # that will result from the rcs files (both in this directory and
1344 # in attic). (We recurse into the subdirectories nevertheless, to
1345 # try to detect more problems.)
1346 for fname
in alldirs
:
1347 pathname
= os
.path
.join(cvs_directory
.filename
, fname
)
1348 for rcsfile_list
in [rcsfiles
, attic_rcsfiles
]:
1349 if fname
in rcsfile_list
:
1350 self
.record_fatal_error(
1351 'Directory name conflicts with filename. Please remove or '
1353 'of the following:\n'
1356 % (pathname
, rcsfile_list
[fname
],)
1359 # Now recurse into the other subdirectories:
1361 dirname
= os
.path
.join(cvs_directory
.filename
, fname
)
1363 # Verify that the directory name does not contain any illegal
1366 verify_svn_filename_legal(fname
)
1367 except IllegalSVNPathError
, e
:
1369 'Directory %r would result in an illegal SVN path name: %s'
1373 sub_directory
= CVSDirectory(
1374 self
.file_key_generator
.gen_id(),
1375 cvs_directory
.project
, cvs_directory
, fname
,
1378 for cvs_file
in self
._generate
_cvs
_files
(sub_directory
):
1381 def process_project(self
, project
):
1382 Ctx()._projects
[project
.id] = project
1384 root_cvs_directory
= CVSDirectory(
1385 self
.file_key_generator
.gen_id(), project
, None, ''
1387 project
.root_cvs_directory_id
= root_cvs_directory
.id
1388 pdc
= _ProjectDataCollector(self
, project
)
1390 found_rcs_file
= False
1391 for cvs_file
in self
._generate
_cvs
_files
(root_cvs_directory
):
1392 pdc
.process_file(cvs_file
)
1393 found_rcs_file
= True
1395 if not found_rcs_file
:
1396 self
.record_fatal_error(
1397 'No RCS files found under %r!\n'
1398 'Are you absolutely certain you are pointing cvs2svn\n'
1399 'at a CVS repository?\n'
1400 % (project
.project_cvs_repos_path
,)
1403 pdc
.summarize_symbol_transforms()
1405 self
.num_files
+= pdc
.num_files
1406 Log().verbose('Processed', self
.num_files
, 'files')
1408 def _set_cvs_path_ordinals(self
):
1409 cvs_files
= list(Ctx()._cvs
_file
_db
.itervalues())
1410 cvs_files
.sort(CVSPath
.slow_compare
)
1411 for (i
, cvs_file
) in enumerate(cvs_files
):
1412 cvs_file
.ordinal
= i
1415 """Close the data structures associated with this instance.
1417 Return a list of fatal errors encountered while processing input.
1418 Each list entry is a string describing one fatal error."""
1420 self
.revision_recorder
.finish()
1421 self
.symbol_stats
.purge_ghost_symbols()
1422 self
.symbol_stats
.close()
1423 self
.symbol_stats
= None
1424 self
.metadata_logger
= None
1425 self
.metadata_db
.close()
1426 self
.metadata_db
= None
1427 self
._cvs
_item
_store
.close()
1428 self
._cvs
_item
_store
= None
1429 self
._set
_cvs
_path
_ordinals
()
1430 self
.revision_recorder
= None
1431 retval
= self
.fatal_errors
1432 self
.fatal_errors
= None