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 duplicates 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 set_description(self
, description
):
613 """This is a callback method declared in Sink."""
615 self
.cvs_file
.description
= description
617 def define_tag(self
, name
, revision
):
618 """Remember the symbol name and revision, but don't process them yet.
620 This is a callback method declared in Sink."""
622 self
.sdc
.define_symbol(name
, revision
)
624 def admin_completed(self
):
625 """This is a callback method declared in Sink."""
627 self
.sdc
.process_symbols()
629 def define_revision(self
, revision
, timestamp
, author
, state
,
631 """This is a callback method declared in Sink."""
633 for branch
in branches
:
635 branch_data
= self
.sdc
.rev_to_branch_data(branch
)
637 # Normally we learn about the branches from the branch names
638 # and numbers parsed from the symbolic name header. But this
639 # must have been an unlabeled branch that slipped through the
640 # net. Generate a name for it and create a _BranchData record
642 branch_data
= self
.sdc
._add
_unlabeled
_branch
(
643 self
.sdc
.rev_to_branch_number(branch
))
645 assert branch_data
.child
is None
646 branch_data
.child
= branch
648 if revision
in self
._rev
_data
:
649 # This revision has already been seen.
650 Log().error('File %r contains duplicate definitions of revision %s.'
651 % (self
.cvs_file
.filename
, revision
,))
654 # Record basic information about the revision:
655 rev_data
= _RevisionData(
656 self
.collect_data
.item_key_generator
.gen_id(),
657 revision
, int(timestamp
), author
, state
)
658 self
._rev
_data
[revision
] = rev_data
660 # When on trunk, the RCS 'next' revision number points to what
661 # humans might consider to be the 'previous' revision number. For
662 # example, 1.3's RCS 'next' is 1.2.
664 # However, on a branch, the RCS 'next' revision number really does
665 # point to what humans would consider to be the 'next' revision
666 # number. For example, 1.1.2.1's RCS 'next' would be 1.1.2.2.
668 # In other words, in RCS, 'next' always means "where to find the next
669 # deltatext that you need this revision to retrieve.
671 # That said, we don't *want* RCS's behavior here, so we determine
672 # whether we're on trunk or a branch and set the dependencies
675 if is_trunk_revision(revision
):
676 self
._primary
_dependencies
.append( (next
, revision
,) )
678 self
._primary
_dependencies
.append( (revision
, next
,) )
680 def _resolve_primary_dependencies(self
):
681 """Resolve the dependencies listed in self._primary_dependencies."""
683 for (parent
, child
,) in self
._primary
_dependencies
:
684 parent_data
= self
._rev
_data
[parent
]
685 assert parent_data
.child
is None
686 parent_data
.child
= child
688 child_data
= self
._rev
_data
[child
]
689 assert child_data
.parent
is None
690 child_data
.parent
= parent
692 def _resolve_branch_dependencies(self
):
693 """Resolve dependencies involving branches."""
695 for branch_data
in self
.sdc
.branches_data
.values():
696 # The branch_data's parent has the branch as a child regardless
697 # of whether the branch had any subsequent commits:
699 parent_data
= self
._rev
_data
[branch_data
.parent
]
703 ' branch %r references non-existing revision %s\n'
704 ' and will be ignored.'
705 % (self
.cvs_file
.filename
, branch_data
.symbol
.name
,
706 branch_data
.parent
,))
707 del self
.sdc
.branches_data
[branch_data
.branch_number
]
709 parent_data
.branches_data
.append(branch_data
)
711 # If the branch has a child (i.e., something was committed on
712 # the branch), then we store a reference to the branch_data
713 # there, define the child's parent to be the branch's parent,
714 # and list the child in the branch parent's branches_revs_data:
715 if branch_data
.child
is not None:
716 child_data
= self
._rev
_data
[branch_data
.child
]
717 assert child_data
.parent_branch_data
is None
718 child_data
.parent_branch_data
= branch_data
719 assert child_data
.parent
is None
720 child_data
.parent
= branch_data
.parent
721 parent_data
.branches_revs_data
.append(branch_data
.child
)
723 def _sort_branches(self
):
724 """Sort the branches sprouting from each revision in creation order.
726 Creation order is taken to be the reverse of the order that they
727 are listed in the symbols part of the RCS file. (If a branch is
728 created then deleted, a later branch can be assigned the recycled
729 branch number; therefore branch numbers are not an indication of
732 for rev_data
in self
._rev
_data
.values():
733 rev_data
.branches_data
.sort(lambda a
, b
: - cmp(a
.id, b
.id))
735 def _resolve_tag_dependencies(self
):
736 """Resolve dependencies involving tags."""
738 for (rev
, tag_data_list
) in self
.sdc
.tags_data
.items():
740 parent_data
= self
._rev
_data
[rev
]
744 ' the following tag(s) reference non-existing revision %s\n'
745 ' and will be ignored:\n'
747 self
.cvs_file
.filename
, rev
,
748 ', '.join([repr(tag_data
.symbol
.name
)
749 for tag_data
in tag_data_list
]),))
750 del self
.sdc
.tags_data
[rev
]
752 for tag_data
in tag_data_list
:
753 assert tag_data
.rev
== rev
754 # The tag_data's rev has the tag as a child:
755 parent_data
.tags_data
.append(tag_data
)
757 def _determine_operation(self
, rev_data
):
758 prev_rev_data
= self
._rev
_data
.get(rev_data
.parent
)
759 return cvs_revision_type_map
[(
760 rev_data
.state
!= 'dead',
761 prev_rev_data
is not None and prev_rev_data
.state
!= 'dead',
764 def _get_cvs_revision(self
, rev_data
):
765 """Create and return a CVSRevision for REV_DATA."""
769 for branch_data
in rev_data
.branches_data
772 branch_commit_ids
= [
773 self
._get
_rev
_id
(rev
)
774 for rev
in rev_data
.branches_revs_data
779 for tag_data
in rev_data
.tags_data
782 revision_type
= self
._determine
_operation
(rev_data
)
784 return revision_type(
785 self
._get
_rev
_id
(rev_data
.rev
), self
.cvs_file
,
786 rev_data
.timestamp
, None,
787 self
._get
_rev
_id
(rev_data
.parent
),
788 self
._get
_rev
_id
(rev_data
.child
),
791 self
.sdc
.rev_to_lod(rev_data
.rev
),
792 rev_data
.get_first_on_branch_id(),
794 tag_ids
, branch_ids
, branch_commit_ids
,
795 rev_data
.revision_recorder_token
)
797 def _get_cvs_revisions(self
):
798 """Generate the CVSRevisions present in this file."""
800 for rev_data
in self
._rev
_data
.itervalues():
801 yield self
._get
_cvs
_revision
(rev_data
)
803 def _get_cvs_branches(self
):
804 """Generate the CVSBranches present in this file."""
806 for branch_data
in self
.sdc
.branches_data
.values():
808 branch_data
.id, self
.cvs_file
, branch_data
.symbol
,
809 branch_data
.branch_number
,
810 self
.sdc
.rev_to_lod(branch_data
.parent
),
811 self
._get
_rev
_id
(branch_data
.parent
),
812 self
._get
_rev
_id
(branch_data
.child
),
816 def _get_cvs_tags(self
):
817 """Generate the CVSTags present in this file."""
819 for tags_data
in self
.sdc
.tags_data
.values():
820 for tag_data
in tags_data
:
822 tag_data
.id, self
.cvs_file
, tag_data
.symbol
,
823 self
.sdc
.rev_to_lod(tag_data
.rev
),
824 self
._get
_rev
_id
(tag_data
.rev
),
828 def tree_completed(self
):
829 """The revision tree has been parsed.
831 Analyze it for consistency and connect some loose ends.
833 This is a callback method declared in Sink."""
835 self
._resolve
_primary
_dependencies
()
836 self
._resolve
_branch
_dependencies
()
837 self
._sort
_branches
()
838 self
._resolve
_tag
_dependencies
()
840 # Compute the preliminary CVSFileItems for this file:
842 cvs_items
.extend(self
._get
_cvs
_revisions
())
843 cvs_items
.extend(self
._get
_cvs
_branches
())
844 cvs_items
.extend(self
._get
_cvs
_tags
())
845 self
._cvs
_file
_items
= CVSFileItems(
846 self
.cvs_file
, self
.pdc
.trunk
, cvs_items
849 self
._cvs
_file
_items
.check_link_consistency()
851 # Tell the revision recorder about the file dependency tree.
852 self
.collect_data
.revision_recorder
.start_file(self
._cvs
_file
_items
)
854 def set_revision_info(self
, revision
, log
, text
):
855 """This is a callback method declared in Sink."""
857 rev_data
= self
._rev
_data
[revision
]
858 cvs_rev
= self
._cvs
_file
_items
[rev_data
.cvs_rev_id
]
860 if cvs_rev
.metadata_id
is not None:
861 # Users have reported problems with repositories in which the
862 # deltatext block for revision 1.1 appears twice. It is not
863 # known whether this results from a CVS/RCS bug, or from botched
864 # hand-editing of the repository. In any case, empirically, cvs
865 # and rcs both use the first version when checking out data, so
866 # that's what we will do. (For the record: "cvs log" fails on
867 # such a file; "rlog" prints the log message from the first
868 # block and ignores the second one.)
871 " Deltatext block for revision %s appeared twice;\n"
872 " ignoring the second occurrence.\n"
873 % (warning_prefix
, self
.cvs_file
.filename
, revision
,)
877 if is_trunk_revision(revision
):
880 branch_name
= self
.sdc
.rev_to_branch_data(revision
).symbol
.name
882 cvs_rev
.metadata_id
= self
.collect_data
.metadata_logger
.store(
883 self
.project
, branch_name
, rev_data
.author
, log
885 cvs_rev
.deltatext_exists
= bool(text
)
887 # If this is revision 1.1, determine whether the file appears to
888 # have been created via 'cvs add' instead of 'cvs import'. The
889 # test is that the log message CVS uses for 1.1 in imports is
890 # "Initial revision\n" with no period. (This fact helps determine
891 # whether this file might have had a default branch in the past.)
892 if revision
== '1.1':
893 self
._file
_imported
= (log
== 'Initial revision\n')
895 cvs_rev
.revision_recorder_token
= \
896 self
.collect_data
.revision_recorder
.record_text(cvs_rev
, log
, text
)
898 def parse_completed(self
):
899 """Finish the processing of this file.
901 This is a callback method declared in Sink."""
903 # Make sure that there was an info section for each revision:
904 for cvs_item
in self
._cvs
_file
_items
.values():
905 if isinstance(cvs_item
, CVSRevision
) and cvs_item
.metadata_id
is None:
906 self
.collect_data
.record_fatal_error(
907 '%r has no deltatext section for revision %s'
908 % (self
.cvs_file
.filename
, cvs_item
.rev
,)
911 def _process_ntdbrs(self
):
912 """Fix up any non-trunk default branch revisions (if present).
914 If a non-trunk default branch is determined to have existed, yield
915 the _RevisionData.ids for all revisions that were once non-trunk
916 default revisions, in dependency order.
918 There are two cases to handle:
920 One case is simple. The RCS file lists a default branch
921 explicitly in its header, such as '1.1.1'. In this case, we know
922 that every revision on the vendor branch is to be treated as head
923 of trunk at that point in time.
925 But there's also a degenerate case. The RCS file does not
926 currently have a default branch, yet we can deduce that for some
927 period in the past it probably *did* have one. For example, the
928 file has vendor revisions 1.1.1.1 -> 1.1.1.96, all of which are
929 dated before 1.2, and then it has 1.1.1.97 -> 1.1.1.100 dated
930 after 1.2. In this case, we should record 1.1.1.96 as the last
931 vendor revision to have been the head of the default branch.
933 If any non-trunk default branch revisions are found:
935 - Set their ntdbr members to True.
937 - Connect the last one with revision 1.2.
939 - Remove revision 1.1 if it is not needed.
944 if self
.default_branch
:
945 vendor_cvs_branch_id
= self
.sdc
.branches_data
[self
.default_branch
].id
946 vendor_lod_items
= self
._cvs
_file
_items
.get_lod_items(
947 self
._cvs
_file
_items
[vendor_cvs_branch_id
]
949 if not self
._cvs
_file
_items
.process_live_ntdb(vendor_lod_items
):
951 elif self
._file
_imported
:
952 vendor_branch_data
= self
.sdc
.branches_data
.get('1.1.1')
953 if vendor_branch_data
is None:
956 vendor_lod_items
= self
._cvs
_file
_items
.get_lod_items(
957 self
._cvs
_file
_items
[vendor_branch_data
.id]
959 if not self
._cvs
_file
_items
.process_historical_ntdb(
965 except VendorBranchError
, e
:
966 self
.collect_data
.record_fatal_error(str(e
))
969 if self
._file
_imported
:
970 self
._cvs
_file
_items
.imported_remove_1_1(vendor_lod_items
)
972 self
._cvs
_file
_items
.check_link_consistency()
974 def get_cvs_file_items(self
):
975 """Finish up and return a CVSFileItems instance for this file.
977 This method must only be called once."""
979 self
._process
_ntdbrs
()
981 # Break a circular reference loop, allowing the memory for self
982 # and sdc to be freed.
985 return self
._cvs
_file
_items
988 class _ProjectDataCollector
:
989 def __init__(self
, collect_data
, project
):
990 self
.collect_data
= collect_data
991 self
.project
= project
994 # The Trunk LineOfDevelopment object for this project:
996 self
.collect_data
.symbol_key_generator
.gen_id(), self
.project
998 self
.project
.trunk_id
= self
.trunk
.id
1000 # This causes a record for self.trunk to spring into existence:
1001 self
.collect_data
.symbol_stats
[self
.trunk
]
1003 # A map { name -> Symbol } for all known symbols in this project.
1004 # The symbols listed here are undifferentiated into Branches and
1005 # Tags because the same name might appear as a branch in one file
1006 # and a tag in another.
1009 # A map { (old_name, new_name) : count } indicating how many files
1010 # were affected by each each symbol name transformation:
1011 self
.symbol_transform_counts
= {}
1013 def get_symbol(self
, name
):
1014 """Return the Symbol object for the symbol named NAME in this project.
1016 If such a symbol does not yet exist, allocate a new symbol_id,
1017 create a Symbol instance, store it in self.symbols, and return it."""
1019 symbol
= self
.symbols
.get(name
)
1022 self
.collect_data
.symbol_key_generator
.gen_id(),
1024 self
.symbols
[name
] = symbol
1027 def log_symbol_transform(self
, old_name
, new_name
):
1028 """Record that OLD_NAME was transformed to NEW_NAME in one file.
1030 This information is used to generated a statistical summary of
1031 symbol transforms."""
1034 self
.symbol_transform_counts
[old_name
, new_name
] += 1
1036 self
.symbol_transform_counts
[old_name
, new_name
] = 1
1038 def summarize_symbol_transforms(self
):
1039 if self
.symbol_transform_counts
and Log().is_on(Log
.NORMAL
):
1041 log
.normal('Summary of symbol transforms:')
1042 transforms
= self
.symbol_transform_counts
.items()
1044 for ((old_name
, new_name
), count
) in transforms
:
1045 if new_name
is None:
1046 log
.normal(' "%s" ignored in %d files' % (old_name
, count
,))
1049 ' "%s" transformed to "%s" in %d files'
1050 % (old_name
, new_name
, count
,)
1053 def _process_cvs_file_items(self
, cvs_file_items
):
1054 """Process the CVSFileItems from one CVSFile."""
1056 # Remove an initial delete on trunk if it is not needed:
1057 cvs_file_items
.remove_unneeded_initial_trunk_delete(
1058 self
.collect_data
.metadata_db
1061 # Remove initial branch deletes that are not needed:
1062 cvs_file_items
.remove_initial_branch_deletes(
1063 self
.collect_data
.metadata_db
1066 # If this is a --trunk-only conversion, discard all branches and
1067 # tags, then draft any non-trunk default branch revisions to
1069 if Ctx().trunk_only
:
1070 cvs_file_items
.exclude_non_trunk()
1072 cvs_file_items
.check_link_consistency()
1074 self
.collect_data
.revision_recorder
.finish_file(cvs_file_items
)
1075 self
.collect_data
.add_cvs_file_items(cvs_file_items
)
1076 self
.collect_data
.symbol_stats
.register(cvs_file_items
)
1078 def process_file(self
, cvs_file
):
1079 Log().normal(cvs_file
.filename
)
1080 fdc
= _FileDataCollector(self
, cvs_file
)
1082 cvs2svn_rcsparse
.parse(open(cvs_file
.filename
, 'rb'), fdc
)
1083 except (cvs2svn_rcsparse
.common
.RCSParseError
, ValueError, RuntimeError):
1084 self
.collect_data
.record_fatal_error(
1085 "%r is not a valid ,v file" % (cvs_file
.filename
,)
1087 # Abort the processing of this file, but let the pass continue
1091 Log().warn("Exception occurred while parsing %s" % cvs_file
.filename
)
1096 cvs_file_items
= fdc
.get_cvs_file_items()
1100 self
._process
_cvs
_file
_items
(cvs_file_items
)
1104 """Repository for data collected by parsing the CVS repository files.
1106 This class manages the databases into which information collected
1107 from the CVS repository is stored. The data are stored into this
1108 class by _FileDataCollector instances, one of which is created for
1109 each file to be parsed."""
1111 def __init__(self
, revision_recorder
, stats_keeper
):
1112 self
.revision_recorder
= revision_recorder
1113 self
._cvs
_item
_store
= NewCVSItemStore(
1114 artifact_manager
.get_temp_file(config
.CVS_ITEMS_STORE
))
1115 self
.metadata_db
= MetadataDatabase(
1116 artifact_manager
.get_temp_file(config
.METADATA_STORE
),
1117 artifact_manager
.get_temp_file(config
.METADATA_INDEX_TABLE
),
1120 self
.metadata_logger
= MetadataLogger(self
.metadata_db
)
1121 self
.fatal_errors
= []
1123 self
.symbol_stats
= SymbolStatisticsCollector()
1124 self
.stats_keeper
= stats_keeper
1126 # Key generator for CVSFiles:
1127 self
.file_key_generator
= KeyGenerator()
1129 # Key generator for CVSItems:
1130 self
.item_key_generator
= KeyGenerator()
1132 # Key generator for Symbols:
1133 self
.symbol_key_generator
= KeyGenerator()
1135 self
.revision_recorder
.start()
1137 def record_fatal_error(self
, err
):
1138 """Record that fatal error ERR was found.
1140 ERR is a string (without trailing newline) describing the error.
1141 Output the error to stderr immediately, and record a copy to be
1142 output again in a summary at the end of CollectRevsPass."""
1144 err
= '%s: %s' % (error_prefix
, err
,)
1145 Log().error(err
+ '\n')
1146 self
.fatal_errors
.append(err
)
1148 def add_cvs_directory(self
, cvs_directory
):
1149 """Record CVS_DIRECTORY."""
1151 Ctx()._cvs
_file
_db
.log_file(cvs_directory
)
1153 def add_cvs_file_items(self
, cvs_file_items
):
1154 """Record the information from CVS_FILE_ITEMS.
1156 Store the CVSFile to _cvs_file_db under its persistent id, store
1157 the CVSItems, and record the CVSItems to self.stats_keeper."""
1159 Ctx()._cvs
_file
_db
.log_file(cvs_file_items
.cvs_file
)
1160 self
._cvs
_item
_store
.add(cvs_file_items
)
1162 self
.stats_keeper
.record_cvs_file(cvs_file_items
.cvs_file
)
1163 for cvs_item
in cvs_file_items
.values():
1164 self
.stats_keeper
.record_cvs_item(cvs_item
)
1167 self
, parent_directory
, basename
, file_in_attic
, leave_in_attic
=False
1169 """Return a CVSFile describing the file with name BASENAME.
1171 PARENT_DIRECTORY is the CVSDirectory instance describing the
1172 directory that physically holds this file in the filesystem.
1173 BASENAME must be the base name of a *,v file within
1176 FILE_IN_ATTIC is a boolean telling whether the specified file is
1177 in an Attic subdirectory. If FILE_IN_ATTIC is True, then:
1179 - If LEAVE_IN_ATTIC is True, then leave the 'Attic' component in
1182 - Otherwise, raise FileInAndOutOfAtticException if a file with the
1183 same filename appears outside of Attic.
1185 The CVSFile is assigned a new unique id. All of the CVSFile
1186 information is filled in except mode (which can only be determined
1187 by parsing the file).
1189 Raise FatalError if the resulting filename would not be legal in
1192 filename
= os
.path
.join(parent_directory
.filename
, basename
)
1194 verify_svn_filename_legal(basename
[:-2])
1195 except IllegalSVNPathError
, e
:
1197 'File %r would result in an illegal SVN filename: %s'
1201 if file_in_attic
and not leave_in_attic
:
1203 logical_parent_directory
= parent_directory
.parent_directory
1205 # If this file also exists outside of the attic, it's a fatal
1207 non_attic_filename
= os
.path
.join(
1208 logical_parent_directory
.filename
, basename
,
1210 if os
.path
.exists(non_attic_filename
):
1211 raise FileInAndOutOfAtticException(non_attic_filename
, filename
)
1214 logical_parent_directory
= parent_directory
1216 file_stat
= os
.stat(filename
)
1218 # The size of the file in bytes:
1219 file_size
= file_stat
[stat
.ST_SIZE
]
1221 # Whether or not the executable bit is set:
1222 file_executable
= bool(file_stat
[0] & stat
.S_IXUSR
)
1224 # mode is not known, so we temporarily set it to None.
1226 self
.file_key_generator
.gen_id(),
1227 parent_directory
.project
, logical_parent_directory
, basename
[:-2],
1228 in_attic
, file_executable
, file_size
, None, None
1231 def _get_attic_file(self
, parent_directory
, basename
):
1232 """Return a CVSFile object for the Attic file at BASENAME.
1234 PARENT_DIRECTORY is the CVSDirectory that physically contains the
1235 file on the filesystem (i.e., the Attic directory). It is not
1236 necessarily the parent_directory of the CVSFile that will be
1239 Return CVSFile, whose parent directory is usually
1240 PARENT_DIRECTORY.parent_directory, but might be PARENT_DIRECTORY
1241 iff CVSFile will remain in the Attic directory."""
1244 return self
._get
_cvs
_file
(parent_directory
, basename
, True)
1245 except FileInAndOutOfAtticException
, e
:
1246 if Ctx().retain_conflicting_attic_files
:
1249 " storing the latter into 'Attic' subdirectory.\n"
1250 % (warning_prefix
, e
)
1253 self
.record_fatal_error(str(e
))
1255 # Either way, return a CVSFile object so that the rest of the
1256 # file processing can proceed:
1257 return self
._get
_cvs
_file
(
1258 parent_directory
, basename
, True, leave_in_attic
=True
1261 def _generate_attic_cvs_files(self
, cvs_directory
):
1262 """Generate CVSFiles for the files in Attic directory CVS_DIRECTORY.
1264 Also add CVS_DIRECTORY to self if any files are being retained in
1267 retained_attic_file
= False
1269 fnames
= os
.listdir(cvs_directory
.filename
)
1271 for fname
in fnames
:
1272 pathname
= os
.path
.join(cvs_directory
.filename
, fname
)
1273 if os
.path
.isdir(pathname
):
1274 Log().warn("Directory %s found within Attic; ignoring" % (pathname
,))
1275 elif fname
.endswith(',v'):
1276 cvs_file
= self
._get
_attic
_file
(cvs_directory
, fname
)
1277 if cvs_file
.parent_directory
== cvs_directory
:
1278 # This file will be retained in the Attic directory.
1279 retained_attic_file
= True
1282 if retained_attic_file
:
1283 # If any files were retained in the Attic directory, then write
1284 # the Attic directory to CVSFileDatabase:
1285 self
.add_cvs_directory(cvs_directory
)
1287 def _get_non_attic_file(self
, parent_directory
, basename
):
1288 """Return a CVSFile object for the non-Attic file at BASENAME."""
1290 return self
._get
_cvs
_file
(parent_directory
, basename
, False)
1292 def _generate_cvs_files(self
, cvs_directory
):
1293 """Generate the CVSFiles under non-Attic directory CVS_DIRECTORY.
1295 Process directories recursively, including Attic directories.
1296 Also create and register CVSDirectories as they are found, and
1297 look for conflicts between the filenames that will result from
1298 files, attic files, and subdirectories."""
1300 self
.add_cvs_directory(cvs_directory
)
1302 # Map {cvs_file.basename : cvs_file.filename} for files directly
1308 # Non-Attic subdirectories of cvs_directory (to be recursed into):
1311 fnames
= os
.listdir(cvs_directory
.filename
)
1313 for fname
in fnames
:
1314 pathname
= os
.path
.join(cvs_directory
.filename
, fname
)
1315 if os
.path
.isdir(pathname
):
1316 if fname
== 'Attic':
1320 elif fname
.endswith(',v'):
1321 cvs_file
= self
._get
_non
_attic
_file
(cvs_directory
, fname
)
1322 rcsfiles
[cvs_file
.basename
] = cvs_file
.filename
1325 # Silently ignore other files:
1328 # Map {cvs_file.basename : cvs_file.filename} for files in an
1329 # Attic directory within cvs_directory:
1332 if attic_dir
is not None:
1333 attic_directory
= CVSDirectory(
1334 self
.file_key_generator
.gen_id(),
1335 cvs_directory
.project
, cvs_directory
, 'Attic',
1338 for cvs_file
in self
._generate
_attic
_cvs
_files
(attic_directory
):
1339 if cvs_file
.parent_directory
== cvs_directory
:
1340 attic_rcsfiles
[cvs_file
.basename
] = cvs_file
.filename
1343 alldirs
= dirs
+ [attic_dir
]
1347 # Check for conflicts between directory names and the filenames
1348 # that will result from the rcs files (both in this directory and
1349 # in attic). (We recurse into the subdirectories nevertheless, to
1350 # try to detect more problems.)
1351 for fname
in alldirs
:
1352 pathname
= os
.path
.join(cvs_directory
.filename
, fname
)
1353 for rcsfile_list
in [rcsfiles
, attic_rcsfiles
]:
1354 if fname
in rcsfile_list
:
1355 self
.record_fatal_error(
1356 'Directory name conflicts with filename. Please remove or '
1358 'of the following:\n'
1361 % (pathname
, rcsfile_list
[fname
],)
1364 # Now recurse into the other subdirectories:
1366 dirname
= os
.path
.join(cvs_directory
.filename
, fname
)
1368 # Verify that the directory name does not contain any illegal
1371 verify_svn_filename_legal(fname
)
1372 except IllegalSVNPathError
, e
:
1374 'Directory %r would result in an illegal SVN path name: %s'
1378 sub_directory
= CVSDirectory(
1379 self
.file_key_generator
.gen_id(),
1380 cvs_directory
.project
, cvs_directory
, fname
,
1383 for cvs_file
in self
._generate
_cvs
_files
(sub_directory
):
1386 def process_project(self
, project
):
1387 Ctx()._projects
[project
.id] = project
1389 root_cvs_directory
= CVSDirectory(
1390 self
.file_key_generator
.gen_id(), project
, None, ''
1392 project
.root_cvs_directory_id
= root_cvs_directory
.id
1393 pdc
= _ProjectDataCollector(self
, project
)
1395 found_rcs_file
= False
1396 for cvs_file
in self
._generate
_cvs
_files
(root_cvs_directory
):
1397 pdc
.process_file(cvs_file
)
1398 found_rcs_file
= True
1400 if not found_rcs_file
:
1401 self
.record_fatal_error(
1402 'No RCS files found under %r!\n'
1403 'Are you absolutely certain you are pointing cvs2svn\n'
1404 'at a CVS repository?\n'
1405 % (project
.project_cvs_repos_path
,)
1408 pdc
.summarize_symbol_transforms()
1410 self
.num_files
+= pdc
.num_files
1411 Log().verbose('Processed', self
.num_files
, 'files')
1413 def _set_cvs_path_ordinals(self
):
1414 cvs_files
= list(Ctx()._cvs
_file
_db
.itervalues())
1415 cvs_files
.sort(CVSPath
.slow_compare
)
1416 for (i
, cvs_file
) in enumerate(cvs_files
):
1417 cvs_file
.ordinal
= i
1420 """Close the data structures associated with this instance.
1422 Return a list of fatal errors encountered while processing input.
1423 Each list entry is a string describing one fatal error."""
1425 self
.revision_recorder
.finish()
1426 self
.symbol_stats
.purge_ghost_symbols()
1427 self
.symbol_stats
.close()
1428 self
.symbol_stats
= None
1429 self
.metadata_logger
= None
1430 self
.metadata_db
.close()
1431 self
.metadata_db
= None
1432 self
._cvs
_item
_store
.close()
1433 self
._cvs
_item
_store
= None
1434 self
._set
_cvs
_path
_ordinals
()
1435 self
.revision_recorder
= None
1436 retval
= self
.fatal_errors
1437 self
.fatal_errors
= None