/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: John Arbash Meinel
  • Date: 2007-10-10 21:18:06 UTC
  • mto: This revision was merged to the branch mainline in revision 2909.
  • Revision ID: john@arbash-meinel.com-20071010211806-2j9rg6wzrqh7yy4u
Switch from __new__ to __init__ to avoid potential pyrex upgrade problems.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from cStringIO import StringIO
 
18
 
 
19
from bzrlib.lazy_import import lazy_import
 
20
lazy_import(globals(), """
 
21
import re
 
22
import time
 
23
 
 
24
from bzrlib import (
 
25
    bzrdir,
 
26
    check,
 
27
    debug,
 
28
    deprecated_graph,
 
29
    errors,
 
30
    generate_ids,
 
31
    gpg,
 
32
    graph,
 
33
    lazy_regex,
 
34
    lockable_files,
 
35
    lockdir,
 
36
    osutils,
 
37
    registry,
 
38
    remote,
 
39
    revision as _mod_revision,
 
40
    symbol_versioning,
 
41
    transactions,
 
42
    ui,
 
43
    )
 
44
from bzrlib.bundle import serializer
 
45
from bzrlib.revisiontree import RevisionTree
 
46
from bzrlib.store.versioned import VersionedFileStore
 
47
from bzrlib.store.text import TextStore
 
48
from bzrlib.testament import Testament
 
49
""")
 
50
 
 
51
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
52
from bzrlib.inter import InterObject
 
53
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
 
54
from bzrlib.symbol_versioning import (
 
55
        deprecated_method,
 
56
        )
 
57
from bzrlib.trace import mutter, mutter_callsite, note, warning
 
58
 
 
59
 
 
60
# Old formats display a warning, but only once
 
61
_deprecation_warning_done = False
 
62
 
 
63
 
 
64
class CommitBuilder(object):
 
65
    """Provides an interface to build up a commit.
 
66
 
 
67
    This allows describing a tree to be committed without needing to 
 
68
    know the internals of the format of the repository.
 
69
    """
 
70
    
 
71
    # all clients should supply tree roots.
 
72
    record_root_entry = True
 
73
    # the default CommitBuilder does not manage trees whose root is versioned.
 
74
    _versioned_root = False
 
75
 
 
76
    def __init__(self, repository, parents, config, timestamp=None, 
 
77
                 timezone=None, committer=None, revprops=None, 
 
78
                 revision_id=None):
 
79
        """Initiate a CommitBuilder.
 
80
 
 
81
        :param repository: Repository to commit to.
 
82
        :param parents: Revision ids of the parents of the new revision.
 
83
        :param config: Configuration to use.
 
84
        :param timestamp: Optional timestamp recorded for commit.
 
85
        :param timezone: Optional timezone for timestamp.
 
86
        :param committer: Optional committer to set for commit.
 
87
        :param revprops: Optional dictionary of revision properties.
 
88
        :param revision_id: Optional revision id.
 
89
        """
 
90
        self._config = config
 
91
 
 
92
        if committer is None:
 
93
            self._committer = self._config.username()
 
94
        else:
 
95
            assert isinstance(committer, basestring), type(committer)
 
96
            self._committer = committer
 
97
 
 
98
        self.new_inventory = Inventory(None)
 
99
        self._new_revision_id = revision_id
 
100
        self.parents = parents
 
101
        self.repository = repository
 
102
 
 
103
        self._revprops = {}
 
104
        if revprops is not None:
 
105
            self._revprops.update(revprops)
 
106
 
 
107
        if timestamp is None:
 
108
            timestamp = time.time()
 
109
        # Restrict resolution to 1ms
 
110
        self._timestamp = round(timestamp, 3)
 
111
 
 
112
        if timezone is None:
 
113
            self._timezone = osutils.local_time_offset()
 
114
        else:
 
115
            self._timezone = int(timezone)
 
116
 
 
117
        self._generate_revision_if_needed()
 
118
        self._repo_graph = repository.get_graph()
 
119
 
 
120
    def commit(self, message):
 
121
        """Make the actual commit.
 
122
 
 
123
        :return: The revision id of the recorded revision.
 
124
        """
 
125
        rev = _mod_revision.Revision(
 
126
                       timestamp=self._timestamp,
 
127
                       timezone=self._timezone,
 
128
                       committer=self._committer,
 
129
                       message=message,
 
130
                       inventory_sha1=self.inv_sha1,
 
131
                       revision_id=self._new_revision_id,
 
132
                       properties=self._revprops)
 
133
        rev.parent_ids = self.parents
 
134
        self.repository.add_revision(self._new_revision_id, rev,
 
135
            self.new_inventory, self._config)
 
136
        self.repository.commit_write_group()
 
137
        return self._new_revision_id
 
138
 
 
139
    def abort(self):
 
140
        """Abort the commit that is being built.
 
141
        """
 
142
        self.repository.abort_write_group()
 
143
 
 
144
    def revision_tree(self):
 
145
        """Return the tree that was just committed.
 
146
 
 
147
        After calling commit() this can be called to get a RevisionTree
 
148
        representing the newly committed tree. This is preferred to
 
149
        calling Repository.revision_tree() because that may require
 
150
        deserializing the inventory, while we already have a copy in
 
151
        memory.
 
152
        """
 
153
        return RevisionTree(self.repository, self.new_inventory,
 
154
                            self._new_revision_id)
 
155
 
 
156
    def finish_inventory(self):
 
157
        """Tell the builder that the inventory is finished."""
 
158
        if self.new_inventory.root is None:
 
159
            symbol_versioning.warn('Root entry should be supplied to'
 
160
                ' record_entry_contents, as of bzr 0.10.',
 
161
                 DeprecationWarning, stacklevel=2)
 
162
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
 
163
        self.new_inventory.revision_id = self._new_revision_id
 
164
        self.inv_sha1 = self.repository.add_inventory(
 
165
            self._new_revision_id,
 
166
            self.new_inventory,
 
167
            self.parents
 
168
            )
 
169
 
 
170
    def _gen_revision_id(self):
 
171
        """Return new revision-id."""
 
172
        return generate_ids.gen_revision_id(self._config.username(),
 
173
                                            self._timestamp)
 
174
 
 
175
    def _generate_revision_if_needed(self):
 
176
        """Create a revision id if None was supplied.
 
177
        
 
178
        If the repository can not support user-specified revision ids
 
179
        they should override this function and raise CannotSetRevisionId
 
180
        if _new_revision_id is not None.
 
181
 
 
182
        :raises: CannotSetRevisionId
 
183
        """
 
184
        if self._new_revision_id is None:
 
185
            self._new_revision_id = self._gen_revision_id()
 
186
            self.random_revid = True
 
187
        else:
 
188
            self.random_revid = False
 
189
 
 
190
    def _check_root(self, ie, parent_invs, tree):
 
191
        """Helper for record_entry_contents.
 
192
 
 
193
        :param ie: An entry being added.
 
194
        :param parent_invs: The inventories of the parent revisions of the
 
195
            commit.
 
196
        :param tree: The tree that is being committed.
 
197
        """
 
198
        # In this revision format, root entries have no knit or weave When
 
199
        # serializing out to disk and back in root.revision is always
 
200
        # _new_revision_id
 
201
        ie.revision = self._new_revision_id
 
202
 
 
203
    def _get_delta(self, ie, basis_inv, path):
 
204
        """Get a delta against the basis inventory for ie."""
 
205
        if ie.file_id not in basis_inv:
 
206
            # add
 
207
            return (None, path, ie.file_id, ie)
 
208
        elif ie != basis_inv[ie.file_id]:
 
209
            # common but altered
 
210
            # TODO: avoid tis id2path call.
 
211
            return (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
 
212
        else:
 
213
            # common, unaltered
 
214
            return None
 
215
 
 
216
    def record_entry_contents(self, ie, parent_invs, path, tree,
 
217
        content_summary):
 
218
        """Record the content of ie from tree into the commit if needed.
 
219
 
 
220
        Side effect: sets ie.revision when unchanged
 
221
 
 
222
        :param ie: An inventory entry present in the commit.
 
223
        :param parent_invs: The inventories of the parent revisions of the
 
224
            commit.
 
225
        :param path: The path the entry is at in the tree.
 
226
        :param tree: The tree which contains this entry and should be used to 
 
227
            obtain content.
 
228
        :param content_summary: Summary data from the tree about the paths
 
229
            content - stat, length, exec, sha/link target. This is only
 
230
            accessed when the entry has a revision of None - that is when it is
 
231
            a candidate to commit.
 
232
        :return: A tuple (change_delta, version_recorded). change_delta is 
 
233
            an inventory_delta change for this entry against the basis tree of
 
234
            the commit, or None if no change occured against the basis tree.
 
235
            version_recorded is True if a new version of the entry has been
 
236
            recorded. For instance, committing a merge where a file was only
 
237
            changed on the other side will return (delta, False).
 
238
        """
 
239
        if self.new_inventory.root is None:
 
240
            if ie.parent_id is not None:
 
241
                raise errors.RootMissing()
 
242
            self._check_root(ie, parent_invs, tree)
 
243
        if ie.revision is None:
 
244
            kind = content_summary[0]
 
245
        else:
 
246
            # ie is carried over from a prior commit
 
247
            kind = ie.kind
 
248
        # XXX: repository specific check for nested tree support goes here - if
 
249
        # the repo doesn't want nested trees we skip it ?
 
250
        if (kind == 'tree-reference' and
 
251
            not self.repository._format.supports_tree_reference):
 
252
            # mismatch between commit builder logic and repository:
 
253
            # this needs the entry creation pushed down into the builder.
 
254
            raise NotImplementedError('Missing repository subtree support.')
 
255
        # transitional assert only, will remove before release.
 
256
        assert ie.kind == kind
 
257
        self.new_inventory.add(ie)
 
258
 
 
259
        # TODO: slow, take it out of the inner loop.
 
260
        try:
 
261
            basis_inv = parent_invs[0]
 
262
        except IndexError:
 
263
            basis_inv = Inventory(root_id=None)
 
264
 
 
265
        # ie.revision is always None if the InventoryEntry is considered
 
266
        # for committing. We may record the previous parents revision if the
 
267
        # content is actually unchanged against a sole head.
 
268
        if ie.revision is not None:
 
269
            if self._versioned_root or path != '':
 
270
                # not considered for commit
 
271
                delta = None
 
272
            else:
 
273
                # repositories that do not version the root set the root's
 
274
                # revision to the new commit even when no change occurs, and
 
275
                # this masks when a change may have occurred against the basis,
 
276
                # so calculate if one happened.
 
277
                if ie.file_id not in basis_inv:
 
278
                    # add
 
279
                    delta = (None, path, ie.file_id, ie)
 
280
                else:
 
281
                    basis_id = basis_inv[ie.file_id]
 
282
                    if basis_id.name != '':
 
283
                        # not the root
 
284
                        delta = (basis_inv.id2path(ie.file_id), path,
 
285
                            ie.file_id, ie)
 
286
                    else:
 
287
                        # common, unaltered
 
288
                        delta = None
 
289
            # not considered for commit, OR, for non-rich-root 
 
290
            return delta, ie.revision == self._new_revision_id and (path != '' or
 
291
                self._versioned_root)
 
292
 
 
293
        # XXX: Friction: parent_candidates should return a list not a dict
 
294
        #      so that we don't have to walk the inventories again.
 
295
        parent_candiate_entries = ie.parent_candidates(parent_invs)
 
296
        head_set = self._repo_graph.heads(parent_candiate_entries.keys())
 
297
        heads = []
 
298
        for inv in parent_invs:
 
299
            if ie.file_id in inv:
 
300
                old_rev = inv[ie.file_id].revision
 
301
                if old_rev in head_set:
 
302
                    heads.append(inv[ie.file_id].revision)
 
303
                    head_set.remove(inv[ie.file_id].revision)
 
304
 
 
305
        store = False
 
306
        # now we check to see if we need to write a new record to the
 
307
        # file-graph.
 
308
        # We write a new entry unless there is one head to the ancestors, and
 
309
        # the kind-derived content is unchanged.
 
310
 
 
311
        # Cheapest check first: no ancestors, or more the one head in the
 
312
        # ancestors, we write a new node.
 
313
        if len(heads) != 1:
 
314
            store = True
 
315
        if not store:
 
316
            # There is a single head, look it up for comparison
 
317
            parent_entry = parent_candiate_entries[heads[0]]
 
318
            # if the non-content specific data has changed, we'll be writing a
 
319
            # node:
 
320
            if (parent_entry.parent_id != ie.parent_id or
 
321
                parent_entry.name != ie.name):
 
322
                store = True
 
323
        # now we need to do content specific checks:
 
324
        if not store:
 
325
            # if the kind changed the content obviously has
 
326
            if kind != parent_entry.kind:
 
327
                store = True
 
328
        if kind == 'file':
 
329
            if not store:
 
330
                if (# if the file length changed we have to store:
 
331
                    parent_entry.text_size != content_summary[1] or
 
332
                    # if the exec bit has changed we have to store:
 
333
                    parent_entry.executable != content_summary[2]):
 
334
                    store = True
 
335
                elif parent_entry.text_sha1 == content_summary[3]:
 
336
                    # all meta and content is unchanged (using a hash cache
 
337
                    # hit to check the sha)
 
338
                    ie.revision = parent_entry.revision
 
339
                    ie.text_size = parent_entry.text_size
 
340
                    ie.text_sha1 = parent_entry.text_sha1
 
341
                    ie.executable = parent_entry.executable
 
342
                    return self._get_delta(ie, basis_inv, path), False
 
343
                else:
 
344
                    # Either there is only a hash change(no hash cache entry,
 
345
                    # or same size content change), or there is no change on
 
346
                    # this file at all.
 
347
                    # Provide the parent's hash to the store layer, so that the
 
348
                    # content is unchanged we will not store a new node.
 
349
                    nostore_sha = parent_entry.text_sha1
 
350
            if store:
 
351
                # We want to record a new node regardless of the presence or
 
352
                # absence of a content change in the file.
 
353
                nostore_sha = None
 
354
            ie.executable = content_summary[2]
 
355
            lines = tree.get_file(ie.file_id, path).readlines()
 
356
            try:
 
357
                ie.text_sha1, ie.text_size = self._add_text_to_weave(
 
358
                    ie.file_id, lines, heads, nostore_sha)
 
359
            except errors.ExistingContent:
 
360
                # Turns out that the file content was unchanged, and we were
 
361
                # only going to store a new node if it was changed. Carry over
 
362
                # the entry.
 
363
                ie.revision = parent_entry.revision
 
364
                ie.text_size = parent_entry.text_size
 
365
                ie.text_sha1 = parent_entry.text_sha1
 
366
                ie.executable = parent_entry.executable
 
367
                return self._get_delta(ie, basis_inv, path), False
 
368
        elif kind == 'directory':
 
369
            if not store:
 
370
                # all data is meta here, nothing specific to directory, so
 
371
                # carry over:
 
372
                ie.revision = parent_entry.revision
 
373
                return self._get_delta(ie, basis_inv, path), False
 
374
            lines = []
 
375
            self._add_text_to_weave(ie.file_id, lines, heads, None)
 
376
        elif kind == 'symlink':
 
377
            current_link_target = content_summary[3]
 
378
            if not store:
 
379
                # symlink target is not generic metadata, check if it has
 
380
                # changed.
 
381
                if current_link_target != parent_entry.symlink_target:
 
382
                    store = True
 
383
            if not store:
 
384
                # unchanged, carry over.
 
385
                ie.revision = parent_entry.revision
 
386
                ie.symlink_target = parent_entry.symlink_target
 
387
                return self._get_delta(ie, basis_inv, path), False
 
388
            ie.symlink_target = current_link_target
 
389
            lines = []
 
390
            self._add_text_to_weave(ie.file_id, lines, heads, None)
 
391
        elif kind == 'tree-reference':
 
392
            if not store:
 
393
                if content_summary[3] != parent_entry.reference_revision:
 
394
                    store = True
 
395
            if not store:
 
396
                # unchanged, carry over.
 
397
                ie.reference_revision = parent_entry.reference_revision
 
398
                ie.revision = parent_entry.revision
 
399
                return self._get_delta(ie, basis_inv, path), False
 
400
            ie.reference_revision = content_summary[3]
 
401
            lines = []
 
402
            self._add_text_to_weave(ie.file_id, lines, heads, None)
 
403
        else:
 
404
            raise NotImplementedError('unknown kind')
 
405
        ie.revision = self._new_revision_id
 
406
        return self._get_delta(ie, basis_inv, path), True
 
407
 
 
408
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
 
409
        versionedfile = self.repository.weave_store.get_weave_or_empty(
 
410
            file_id, self.repository.get_transaction())
 
411
        # Don't change this to add_lines - add_lines_with_ghosts is cheaper
 
412
        # than add_lines, and allows committing when a parent is ghosted for
 
413
        # some reason.
 
414
        # Note: as we read the content directly from the tree, we know its not
 
415
        # been turned into unicode or badly split - but a broken tree
 
416
        # implementation could give us bad output from readlines() so this is
 
417
        # not a guarantee of safety. What would be better is always checking
 
418
        # the content during test suite execution. RBC 20070912
 
419
        try:
 
420
            return versionedfile.add_lines_with_ghosts(
 
421
                self._new_revision_id, parents, new_lines,
 
422
                nostore_sha=nostore_sha, random_id=self.random_revid,
 
423
                check_content=False)[0:2]
 
424
        finally:
 
425
            versionedfile.clear_cache()
 
426
 
 
427
 
 
428
class RootCommitBuilder(CommitBuilder):
 
429
    """This commitbuilder actually records the root id"""
 
430
    
 
431
    # the root entry gets versioned properly by this builder.
 
432
    _versioned_root = True
 
433
 
 
434
    def _check_root(self, ie, parent_invs, tree):
 
435
        """Helper for record_entry_contents.
 
436
 
 
437
        :param ie: An entry being added.
 
438
        :param parent_invs: The inventories of the parent revisions of the
 
439
            commit.
 
440
        :param tree: The tree that is being committed.
 
441
        """
 
442
 
 
443
 
 
444
######################################################################
 
445
# Repositories
 
446
 
 
447
class Repository(object):
 
448
    """Repository holding history for one or more branches.
 
449
 
 
450
    The repository holds and retrieves historical information including
 
451
    revisions and file history.  It's normally accessed only by the Branch,
 
452
    which views a particular line of development through that history.
 
453
 
 
454
    The Repository builds on top of Stores and a Transport, which respectively 
 
455
    describe the disk data format and the way of accessing the (possibly 
 
456
    remote) disk.
 
457
    """
 
458
 
 
459
    # What class to use for a CommitBuilder. Often its simpler to change this
 
460
    # in a Repository class subclass rather than to override
 
461
    # get_commit_builder.
 
462
    _commit_builder_class = CommitBuilder
 
463
    # The search regex used by xml based repositories to determine what things
 
464
    # where changed in a single commit.
 
465
    _file_ids_altered_regex = lazy_regex.lazy_compile(
 
466
        r'file_id="(?P<file_id>[^"]+)"'
 
467
        r'.* revision="(?P<revision_id>[^"]+)"'
 
468
        )
 
469
 
 
470
    def abort_write_group(self):
 
471
        """Commit the contents accrued within the current write group.
 
472
 
 
473
        :seealso: start_write_group.
 
474
        """
 
475
        if self._write_group is not self.get_transaction():
 
476
            # has an unlock or relock occured ?
 
477
            raise errors.BzrError('mismatched lock context and write group.')
 
478
        self._abort_write_group()
 
479
        self._write_group = None
 
480
 
 
481
    def _abort_write_group(self):
 
482
        """Template method for per-repository write group cleanup.
 
483
        
 
484
        This is called during abort before the write group is considered to be 
 
485
        finished and should cleanup any internal state accrued during the write
 
486
        group. There is no requirement that data handed to the repository be
 
487
        *not* made available - this is not a rollback - but neither should any
 
488
        attempt be made to ensure that data added is fully commited. Abort is
 
489
        invoked when an error has occured so futher disk or network operations
 
490
        may not be possible or may error and if possible should not be
 
491
        attempted.
 
492
        """
 
493
 
 
494
    @needs_write_lock
 
495
    def add_inventory(self, revision_id, inv, parents):
 
496
        """Add the inventory inv to the repository as revision_id.
 
497
        
 
498
        :param parents: The revision ids of the parents that revision_id
 
499
                        is known to have and are in the repository already.
 
500
 
 
501
        returns the sha1 of the serialized inventory.
 
502
        """
 
503
        _mod_revision.check_not_reserved_id(revision_id)
 
504
        assert inv.revision_id is None or inv.revision_id == revision_id, \
 
505
            "Mismatch between inventory revision" \
 
506
            " id and insertion revid (%r, %r)" % (inv.revision_id, revision_id)
 
507
        assert inv.root is not None
 
508
        inv_lines = self._serialise_inventory_to_lines(inv)
 
509
        inv_vf = self.get_inventory_weave()
 
510
        return self._inventory_add_lines(inv_vf, revision_id, parents,
 
511
            inv_lines, check_content=False)
 
512
 
 
513
    def _inventory_add_lines(self, inv_vf, revision_id, parents, lines,
 
514
        check_content=True):
 
515
        """Store lines in inv_vf and return the sha1 of the inventory."""
 
516
        final_parents = []
 
517
        for parent in parents:
 
518
            if parent in inv_vf:
 
519
                final_parents.append(parent)
 
520
        return inv_vf.add_lines(revision_id, final_parents, lines,
 
521
            check_content=check_content)[0]
 
522
 
 
523
    @needs_write_lock
 
524
    def add_revision(self, revision_id, rev, inv=None, config=None):
 
525
        """Add rev to the revision store as revision_id.
 
526
 
 
527
        :param revision_id: the revision id to use.
 
528
        :param rev: The revision object.
 
529
        :param inv: The inventory for the revision. if None, it will be looked
 
530
                    up in the inventory storer
 
531
        :param config: If None no digital signature will be created.
 
532
                       If supplied its signature_needed method will be used
 
533
                       to determine if a signature should be made.
 
534
        """
 
535
        # TODO: jam 20070210 Shouldn't we check rev.revision_id and
 
536
        #       rev.parent_ids?
 
537
        _mod_revision.check_not_reserved_id(revision_id)
 
538
        if config is not None and config.signature_needed():
 
539
            if inv is None:
 
540
                inv = self.get_inventory(revision_id)
 
541
            plaintext = Testament(rev, inv).as_short_text()
 
542
            self.store_revision_signature(
 
543
                gpg.GPGStrategy(config), plaintext, revision_id)
 
544
        if not revision_id in self.get_inventory_weave():
 
545
            if inv is None:
 
546
                raise errors.WeaveRevisionNotPresent(revision_id,
 
547
                                                     self.get_inventory_weave())
 
548
            else:
 
549
                # yes, this is not suitable for adding with ghosts.
 
550
                self.add_inventory(revision_id, inv, rev.parent_ids)
 
551
        self._revision_store.add_revision(rev, self.get_transaction())
 
552
 
 
553
    def _add_revision_text(self, revision_id, text):
 
554
        revision = self._revision_store._serializer.read_revision_from_string(
 
555
            text)
 
556
        self._revision_store._add_revision(revision, StringIO(text),
 
557
                                           self.get_transaction())
 
558
 
 
559
    def all_revision_ids(self):
 
560
        """Returns a list of all the revision ids in the repository. 
 
561
 
 
562
        This is deprecated because code should generally work on the graph
 
563
        reachable from a particular revision, and ignore any other revisions
 
564
        that might be present.  There is no direct replacement method.
 
565
        """
 
566
        if 'evil' in debug.debug_flags:
 
567
            mutter_callsite(2, "all_revision_ids is linear with history.")
 
568
        return self._all_revision_ids()
 
569
 
 
570
    def _all_revision_ids(self):
 
571
        """Returns a list of all the revision ids in the repository. 
 
572
 
 
573
        These are in as much topological order as the underlying store can 
 
574
        present.
 
575
        """
 
576
        raise NotImplementedError(self._all_revision_ids)
 
577
 
 
578
    def break_lock(self):
 
579
        """Break a lock if one is present from another instance.
 
580
 
 
581
        Uses the ui factory to ask for confirmation if the lock may be from
 
582
        an active process.
 
583
        """
 
584
        self.control_files.break_lock()
 
585
 
 
586
    @needs_read_lock
 
587
    def _eliminate_revisions_not_present(self, revision_ids):
 
588
        """Check every revision id in revision_ids to see if we have it.
 
589
 
 
590
        Returns a set of the present revisions.
 
591
        """
 
592
        result = []
 
593
        for id in revision_ids:
 
594
            if self.has_revision(id):
 
595
               result.append(id)
 
596
        return result
 
597
 
 
598
    @staticmethod
 
599
    def create(a_bzrdir):
 
600
        """Construct the current default format repository in a_bzrdir."""
 
601
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
 
602
 
 
603
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
604
        """instantiate a Repository.
 
605
 
 
606
        :param _format: The format of the repository on disk.
 
607
        :param a_bzrdir: The BzrDir of the repository.
 
608
 
 
609
        In the future we will have a single api for all stores for
 
610
        getting file texts, inventories and revisions, then
 
611
        this construct will accept instances of those things.
 
612
        """
 
613
        super(Repository, self).__init__()
 
614
        self._format = _format
 
615
        # the following are part of the public API for Repository:
 
616
        self.bzrdir = a_bzrdir
 
617
        self.control_files = control_files
 
618
        self._revision_store = _revision_store
 
619
        # backwards compatibility
 
620
        self.weave_store = text_store
 
621
        # for tests
 
622
        self._reconcile_does_inventory_gc = True
 
623
        # not right yet - should be more semantically clear ? 
 
624
        # 
 
625
        self.control_store = control_store
 
626
        self.control_weaves = control_store
 
627
        # TODO: make sure to construct the right store classes, etc, depending
 
628
        # on whether escaping is required.
 
629
        self._warn_if_deprecated()
 
630
        self._write_group = None
 
631
        self.base = control_files._transport.base
 
632
 
 
633
    def __repr__(self):
 
634
        return '%s(%r)' % (self.__class__.__name__,
 
635
                           self.base)
 
636
 
 
637
    def has_same_location(self, other):
 
638
        """Returns a boolean indicating if this repository is at the same
 
639
        location as another repository.
 
640
 
 
641
        This might return False even when two repository objects are accessing
 
642
        the same physical repository via different URLs.
 
643
        """
 
644
        if self.__class__ is not other.__class__:
 
645
            return False
 
646
        return (self.control_files._transport.base ==
 
647
                other.control_files._transport.base)
 
648
 
 
649
    def is_in_write_group(self):
 
650
        """Return True if there is an open write group.
 
651
 
 
652
        :seealso: start_write_group.
 
653
        """
 
654
        return self._write_group is not None
 
655
 
 
656
    def is_locked(self):
 
657
        return self.control_files.is_locked()
 
658
 
 
659
    def lock_write(self, token=None):
 
660
        """Lock this repository for writing.
 
661
 
 
662
        This causes caching within the repository obejct to start accumlating
 
663
        data during reads, and allows a 'write_group' to be obtained. Write
 
664
        groups must be used for actual data insertion.
 
665
        
 
666
        :param token: if this is already locked, then lock_write will fail
 
667
            unless the token matches the existing lock.
 
668
        :returns: a token if this instance supports tokens, otherwise None.
 
669
        :raises TokenLockingNotSupported: when a token is given but this
 
670
            instance doesn't support using token locks.
 
671
        :raises MismatchedToken: if the specified token doesn't match the token
 
672
            of the existing lock.
 
673
        :seealso: start_write_group.
 
674
 
 
675
        A token should be passed in if you know that you have locked the object
 
676
        some other way, and need to synchronise this object's state with that
 
677
        fact.
 
678
 
 
679
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
 
680
        """
 
681
        result = self.control_files.lock_write(token=token)
 
682
        self._refresh_data()
 
683
        return result
 
684
 
 
685
    def lock_read(self):
 
686
        self.control_files.lock_read()
 
687
        self._refresh_data()
 
688
 
 
689
    def get_physical_lock_status(self):
 
690
        return self.control_files.get_physical_lock_status()
 
691
 
 
692
    def leave_lock_in_place(self):
 
693
        """Tell this repository not to release the physical lock when this
 
694
        object is unlocked.
 
695
        
 
696
        If lock_write doesn't return a token, then this method is not supported.
 
697
        """
 
698
        self.control_files.leave_in_place()
 
699
 
 
700
    def dont_leave_lock_in_place(self):
 
701
        """Tell this repository to release the physical lock when this
 
702
        object is unlocked, even if it didn't originally acquire it.
 
703
 
 
704
        If lock_write doesn't return a token, then this method is not supported.
 
705
        """
 
706
        self.control_files.dont_leave_in_place()
 
707
 
 
708
    @needs_read_lock
 
709
    def gather_stats(self, revid=None, committers=None):
 
710
        """Gather statistics from a revision id.
 
711
 
 
712
        :param revid: The revision id to gather statistics from, if None, then
 
713
            no revision specific statistics are gathered.
 
714
        :param committers: Optional parameter controlling whether to grab
 
715
            a count of committers from the revision specific statistics.
 
716
        :return: A dictionary of statistics. Currently this contains:
 
717
            committers: The number of committers if requested.
 
718
            firstrev: A tuple with timestamp, timezone for the penultimate left
 
719
                most ancestor of revid, if revid is not the NULL_REVISION.
 
720
            latestrev: A tuple with timestamp, timezone for revid, if revid is
 
721
                not the NULL_REVISION.
 
722
            revisions: The total revision count in the repository.
 
723
            size: An estimate disk size of the repository in bytes.
 
724
        """
 
725
        result = {}
 
726
        if revid and committers:
 
727
            result['committers'] = 0
 
728
        if revid and revid != _mod_revision.NULL_REVISION:
 
729
            if committers:
 
730
                all_committers = set()
 
731
            revisions = self.get_ancestry(revid)
 
732
            # pop the leading None
 
733
            revisions.pop(0)
 
734
            first_revision = None
 
735
            if not committers:
 
736
                # ignore the revisions in the middle - just grab first and last
 
737
                revisions = revisions[0], revisions[-1]
 
738
            for revision in self.get_revisions(revisions):
 
739
                if not first_revision:
 
740
                    first_revision = revision
 
741
                if committers:
 
742
                    all_committers.add(revision.committer)
 
743
            last_revision = revision
 
744
            if committers:
 
745
                result['committers'] = len(all_committers)
 
746
            result['firstrev'] = (first_revision.timestamp,
 
747
                first_revision.timezone)
 
748
            result['latestrev'] = (last_revision.timestamp,
 
749
                last_revision.timezone)
 
750
 
 
751
        # now gather global repository information
 
752
        if self.bzrdir.root_transport.listable():
 
753
            c, t = self._revision_store.total_size(self.get_transaction())
 
754
            result['revisions'] = c
 
755
            result['size'] = t
 
756
        return result
 
757
 
 
758
    @needs_read_lock
 
759
    def missing_revision_ids(self, other, revision_id=None):
 
760
        """Return the revision ids that other has that this does not.
 
761
        
 
762
        These are returned in topological order.
 
763
 
 
764
        revision_id: only return revision ids included by revision_id.
 
765
        """
 
766
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
 
767
 
 
768
    @staticmethod
 
769
    def open(base):
 
770
        """Open the repository rooted at base.
 
771
 
 
772
        For instance, if the repository is at URL/.bzr/repository,
 
773
        Repository.open(URL) -> a Repository instance.
 
774
        """
 
775
        control = bzrdir.BzrDir.open(base)
 
776
        return control.open_repository()
 
777
 
 
778
    def copy_content_into(self, destination, revision_id=None):
 
779
        """Make a complete copy of the content in self into destination.
 
780
        
 
781
        This is a destructive operation! Do not use it on existing 
 
782
        repositories.
 
783
        """
 
784
        return InterRepository.get(self, destination).copy_content(revision_id)
 
785
 
 
786
    def commit_write_group(self):
 
787
        """Commit the contents accrued within the current write group.
 
788
 
 
789
        :seealso: start_write_group.
 
790
        """
 
791
        if self._write_group is not self.get_transaction():
 
792
            # has an unlock or relock occured ?
 
793
            raise errors.BzrError('mismatched lock context %r and '
 
794
                'write group %r.' %
 
795
                (self.get_transaction(), self._write_group))
 
796
        self._commit_write_group()
 
797
        self._write_group = None
 
798
 
 
799
    def _commit_write_group(self):
 
800
        """Template method for per-repository write group cleanup.
 
801
        
 
802
        This is called before the write group is considered to be 
 
803
        finished and should ensure that all data handed to the repository
 
804
        for writing during the write group is safely committed (to the 
 
805
        extent possible considering file system caching etc).
 
806
        """
 
807
 
 
808
    def fetch(self, source, revision_id=None, pb=None):
 
809
        """Fetch the content required to construct revision_id from source.
 
810
 
 
811
        If revision_id is None all content is copied.
 
812
        """
 
813
        # fast path same-url fetch operations
 
814
        if self.has_same_location(source):
 
815
            # check that last_revision is in 'from' and then return a
 
816
            # no-operation.
 
817
            if (revision_id is not None and
 
818
                not _mod_revision.is_null(revision_id)):
 
819
                self.get_revision(revision_id)
 
820
            return 0, []
 
821
        inter = InterRepository.get(source, self)
 
822
        try:
 
823
            return inter.fetch(revision_id=revision_id, pb=pb)
 
824
        except NotImplementedError:
 
825
            raise errors.IncompatibleRepositories(source, self)
 
826
 
 
827
    def create_bundle(self, target, base, fileobj, format=None):
 
828
        return serializer.write_bundle(self, target, base, fileobj, format)
 
829
 
 
830
    def get_commit_builder(self, branch, parents, config, timestamp=None,
 
831
                           timezone=None, committer=None, revprops=None,
 
832
                           revision_id=None):
 
833
        """Obtain a CommitBuilder for this repository.
 
834
        
 
835
        :param branch: Branch to commit to.
 
836
        :param parents: Revision ids of the parents of the new revision.
 
837
        :param config: Configuration to use.
 
838
        :param timestamp: Optional timestamp recorded for commit.
 
839
        :param timezone: Optional timezone for timestamp.
 
840
        :param committer: Optional committer to set for commit.
 
841
        :param revprops: Optional dictionary of revision properties.
 
842
        :param revision_id: Optional revision id.
 
843
        """
 
844
        result = self._commit_builder_class(self, parents, config,
 
845
            timestamp, timezone, committer, revprops, revision_id)
 
846
        self.start_write_group()
 
847
        return result
 
848
 
 
849
    def unlock(self):
 
850
        if (self.control_files._lock_count == 1 and
 
851
            self.control_files._lock_mode == 'w'):
 
852
            if self._write_group is not None:
 
853
                raise errors.BzrError(
 
854
                    'Must end write groups before releasing write locks.')
 
855
        self.control_files.unlock()
 
856
 
 
857
    @needs_read_lock
 
858
    def clone(self, a_bzrdir, revision_id=None):
 
859
        """Clone this repository into a_bzrdir using the current format.
 
860
 
 
861
        Currently no check is made that the format of this repository and
 
862
        the bzrdir format are compatible. FIXME RBC 20060201.
 
863
 
 
864
        :return: The newly created destination repository.
 
865
        """
 
866
        # TODO: deprecate after 0.16; cloning this with all its settings is
 
867
        # probably not very useful -- mbp 20070423
 
868
        dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
 
869
        self.copy_content_into(dest_repo, revision_id)
 
870
        return dest_repo
 
871
 
 
872
    def start_write_group(self):
 
873
        """Start a write group in the repository.
 
874
 
 
875
        Write groups are used by repositories which do not have a 1:1 mapping
 
876
        between file ids and backend store to manage the insertion of data from
 
877
        both fetch and commit operations.
 
878
 
 
879
        A write lock is required around the start_write_group/commit_write_group
 
880
        for the support of lock-requiring repository formats.
 
881
 
 
882
        One can only insert data into a repository inside a write group.
 
883
 
 
884
        :return: None.
 
885
        """
 
886
        if not self.is_locked() or self.control_files._lock_mode != 'w':
 
887
            raise errors.NotWriteLocked(self)
 
888
        if self._write_group:
 
889
            raise errors.BzrError('already in a write group')
 
890
        self._start_write_group()
 
891
        # so we can detect unlock/relock - the write group is now entered.
 
892
        self._write_group = self.get_transaction()
 
893
 
 
894
    def _start_write_group(self):
 
895
        """Template method for per-repository write group startup.
 
896
        
 
897
        This is called before the write group is considered to be 
 
898
        entered.
 
899
        """
 
900
 
 
901
    @needs_read_lock
 
902
    def sprout(self, to_bzrdir, revision_id=None):
 
903
        """Create a descendent repository for new development.
 
904
 
 
905
        Unlike clone, this does not copy the settings of the repository.
 
906
        """
 
907
        dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
 
908
        dest_repo.fetch(self, revision_id=revision_id)
 
909
        return dest_repo
 
910
 
 
911
    def _create_sprouting_repo(self, a_bzrdir, shared):
 
912
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
 
913
            # use target default format.
 
914
            dest_repo = a_bzrdir.create_repository()
 
915
        else:
 
916
            # Most control formats need the repository to be specifically
 
917
            # created, but on some old all-in-one formats it's not needed
 
918
            try:
 
919
                dest_repo = self._format.initialize(a_bzrdir, shared=shared)
 
920
            except errors.UninitializableFormat:
 
921
                dest_repo = a_bzrdir.open_repository()
 
922
        return dest_repo
 
923
 
 
924
    @needs_read_lock
 
925
    def has_revision(self, revision_id):
 
926
        """True if this repository has a copy of the revision."""
 
927
        if 'evil' in debug.debug_flags:
 
928
            mutter_callsite(3, "has_revision is a LBYL symptom.")
 
929
        return self._revision_store.has_revision_id(revision_id,
 
930
                                                    self.get_transaction())
 
931
 
 
932
    @needs_read_lock
 
933
    def get_revision(self, revision_id):
 
934
        """Return the Revision object for a named revision."""
 
935
        return self.get_revisions([revision_id])[0]
 
936
 
 
937
    @needs_read_lock
 
938
    def get_revision_reconcile(self, revision_id):
 
939
        """'reconcile' helper routine that allows access to a revision always.
 
940
        
 
941
        This variant of get_revision does not cross check the weave graph
 
942
        against the revision one as get_revision does: but it should only
 
943
        be used by reconcile, or reconcile-alike commands that are correcting
 
944
        or testing the revision graph.
 
945
        """
 
946
        return self._get_revisions([revision_id])[0]
 
947
 
 
948
    @needs_read_lock
 
949
    def get_revisions(self, revision_ids):
 
950
        """Get many revisions at once."""
 
951
        return self._get_revisions(revision_ids)
 
952
 
 
953
    @needs_read_lock
 
954
    def _get_revisions(self, revision_ids):
 
955
        """Core work logic to get many revisions without sanity checks."""
 
956
        for rev_id in revision_ids:
 
957
            if not rev_id or not isinstance(rev_id, basestring):
 
958
                raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
 
959
        revs = self._revision_store.get_revisions(revision_ids,
 
960
                                                  self.get_transaction())
 
961
        for rev in revs:
 
962
            assert not isinstance(rev.revision_id, unicode)
 
963
            for parent_id in rev.parent_ids:
 
964
                assert not isinstance(parent_id, unicode)
 
965
        return revs
 
966
 
 
967
    @needs_read_lock
 
968
    def get_revision_xml(self, revision_id):
 
969
        # TODO: jam 20070210 This shouldn't be necessary since get_revision
 
970
        #       would have already do it.
 
971
        # TODO: jam 20070210 Just use _serializer.write_revision_to_string()
 
972
        rev = self.get_revision(revision_id)
 
973
        rev_tmp = StringIO()
 
974
        # the current serializer..
 
975
        self._revision_store._serializer.write_revision(rev, rev_tmp)
 
976
        rev_tmp.seek(0)
 
977
        return rev_tmp.getvalue()
 
978
 
 
979
    @needs_read_lock
 
980
    def get_deltas_for_revisions(self, revisions):
 
981
        """Produce a generator of revision deltas.
 
982
        
 
983
        Note that the input is a sequence of REVISIONS, not revision_ids.
 
984
        Trees will be held in memory until the generator exits.
 
985
        Each delta is relative to the revision's lefthand predecessor.
 
986
        """
 
987
        required_trees = set()
 
988
        for revision in revisions:
 
989
            required_trees.add(revision.revision_id)
 
990
            required_trees.update(revision.parent_ids[:1])
 
991
        trees = dict((t.get_revision_id(), t) for 
 
992
                     t in self.revision_trees(required_trees))
 
993
        for revision in revisions:
 
994
            if not revision.parent_ids:
 
995
                old_tree = self.revision_tree(None)
 
996
            else:
 
997
                old_tree = trees[revision.parent_ids[0]]
 
998
            yield trees[revision.revision_id].changes_from(old_tree)
 
999
 
 
1000
    @needs_read_lock
 
1001
    def get_revision_delta(self, revision_id):
 
1002
        """Return the delta for one revision.
 
1003
 
 
1004
        The delta is relative to the left-hand predecessor of the
 
1005
        revision.
 
1006
        """
 
1007
        r = self.get_revision(revision_id)
 
1008
        return list(self.get_deltas_for_revisions([r]))[0]
 
1009
 
 
1010
    @needs_write_lock
 
1011
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
1012
        signature = gpg_strategy.sign(plaintext)
 
1013
        self._revision_store.add_revision_signature_text(revision_id,
 
1014
                                                         signature,
 
1015
                                                         self.get_transaction())
 
1016
 
 
1017
    def fileids_altered_by_revision_ids(self, revision_ids):
 
1018
        """Find the file ids and versions affected by revisions.
 
1019
 
 
1020
        :param revisions: an iterable containing revision ids.
 
1021
        :return: a dictionary mapping altered file-ids to an iterable of
 
1022
        revision_ids. Each altered file-ids has the exact revision_ids that
 
1023
        altered it listed explicitly.
 
1024
        """
 
1025
        assert self._serializer.support_altered_by_hack, \
 
1026
            ("fileids_altered_by_revision_ids only supported for branches " 
 
1027
             "which store inventory as unnested xml, not on %r" % self)
 
1028
        selected_revision_ids = set(revision_ids)
 
1029
        w = self.get_inventory_weave()
 
1030
        result = {}
 
1031
 
 
1032
        # this code needs to read every new line in every inventory for the
 
1033
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
 
1034
        # not present in one of those inventories is unnecessary but not 
 
1035
        # harmful because we are filtering by the revision id marker in the
 
1036
        # inventory lines : we only select file ids altered in one of those  
 
1037
        # revisions. We don't need to see all lines in the inventory because
 
1038
        # only those added in an inventory in rev X can contain a revision=X
 
1039
        # line.
 
1040
        unescape_revid_cache = {}
 
1041
        unescape_fileid_cache = {}
 
1042
 
 
1043
        # jam 20061218 In a big fetch, this handles hundreds of thousands
 
1044
        # of lines, so it has had a lot of inlining and optimizing done.
 
1045
        # Sorry that it is a little bit messy.
 
1046
        # Move several functions to be local variables, since this is a long
 
1047
        # running loop.
 
1048
        search = self._file_ids_altered_regex.search
 
1049
        unescape = _unescape_xml
 
1050
        setdefault = result.setdefault
 
1051
        pb = ui.ui_factory.nested_progress_bar()
 
1052
        try:
 
1053
            for line in w.iter_lines_added_or_present_in_versions(
 
1054
                                        selected_revision_ids, pb=pb):
 
1055
                match = search(line)
 
1056
                if match is None:
 
1057
                    continue
 
1058
                # One call to match.group() returning multiple items is quite a
 
1059
                # bit faster than 2 calls to match.group() each returning 1
 
1060
                file_id, revision_id = match.group('file_id', 'revision_id')
 
1061
 
 
1062
                # Inlining the cache lookups helps a lot when you make 170,000
 
1063
                # lines and 350k ids, versus 8.4 unique ids.
 
1064
                # Using a cache helps in 2 ways:
 
1065
                #   1) Avoids unnecessary decoding calls
 
1066
                #   2) Re-uses cached strings, which helps in future set and
 
1067
                #      equality checks.
 
1068
                # (2) is enough that removing encoding entirely along with
 
1069
                # the cache (so we are using plain strings) results in no
 
1070
                # performance improvement.
 
1071
                try:
 
1072
                    revision_id = unescape_revid_cache[revision_id]
 
1073
                except KeyError:
 
1074
                    unescaped = unescape(revision_id)
 
1075
                    unescape_revid_cache[revision_id] = unescaped
 
1076
                    revision_id = unescaped
 
1077
 
 
1078
                if revision_id in selected_revision_ids:
 
1079
                    try:
 
1080
                        file_id = unescape_fileid_cache[file_id]
 
1081
                    except KeyError:
 
1082
                        unescaped = unescape(file_id)
 
1083
                        unescape_fileid_cache[file_id] = unescaped
 
1084
                        file_id = unescaped
 
1085
                    setdefault(file_id, set()).add(revision_id)
 
1086
        finally:
 
1087
            pb.finished()
 
1088
        return result
 
1089
 
 
1090
    def iter_files_bytes(self, desired_files):
 
1091
        """Iterate through file versions.
 
1092
 
 
1093
        Files will not necessarily be returned in the order they occur in
 
1094
        desired_files.  No specific order is guaranteed.
 
1095
 
 
1096
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
 
1097
        value supplied by the caller as part of desired_files.  It should
 
1098
        uniquely identify the file version in the caller's context.  (Examples:
 
1099
        an index number or a TreeTransform trans_id.)
 
1100
 
 
1101
        bytes_iterator is an iterable of bytestrings for the file.  The
 
1102
        kind of iterable and length of the bytestrings are unspecified, but for
 
1103
        this implementation, it is a list of lines produced by
 
1104
        VersionedFile.get_lines().
 
1105
 
 
1106
        :param desired_files: a list of (file_id, revision_id, identifier)
 
1107
            triples
 
1108
        """
 
1109
        transaction = self.get_transaction()
 
1110
        for file_id, revision_id, callable_data in desired_files:
 
1111
            try:
 
1112
                weave = self.weave_store.get_weave(file_id, transaction)
 
1113
            except errors.NoSuchFile:
 
1114
                raise errors.NoSuchIdInRepository(self, file_id)
 
1115
            yield callable_data, weave.get_lines(revision_id)
 
1116
 
 
1117
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
 
1118
        """Get an iterable listing the keys of all the data introduced by a set
 
1119
        of revision IDs.
 
1120
 
 
1121
        The keys will be ordered so that the corresponding items can be safely
 
1122
        fetched and inserted in that order.
 
1123
 
 
1124
        :returns: An iterable producing tuples of (knit-kind, file-id,
 
1125
            versions).  knit-kind is one of 'file', 'inventory', 'signatures',
 
1126
            'revisions'.  file-id is None unless knit-kind is 'file'.
 
1127
        """
 
1128
        # XXX: it's a bit weird to control the inventory weave caching in this
 
1129
        # generator.  Ideally the caching would be done in fetch.py I think.  Or
 
1130
        # maybe this generator should explicitly have the contract that it
 
1131
        # should not be iterated until the previously yielded item has been
 
1132
        # processed?
 
1133
        inv_w = self.get_inventory_weave()
 
1134
        inv_w.enable_cache()
 
1135
 
 
1136
        # file ids that changed
 
1137
        file_ids = self.fileids_altered_by_revision_ids(revision_ids)
 
1138
        count = 0
 
1139
        num_file_ids = len(file_ids)
 
1140
        for file_id, altered_versions in file_ids.iteritems():
 
1141
            if _files_pb is not None:
 
1142
                _files_pb.update("fetch texts", count, num_file_ids)
 
1143
            count += 1
 
1144
            yield ("file", file_id, altered_versions)
 
1145
        # We're done with the files_pb.  Note that it finished by the caller,
 
1146
        # just as it was created by the caller.
 
1147
        del _files_pb
 
1148
 
 
1149
        # inventory
 
1150
        yield ("inventory", None, revision_ids)
 
1151
        inv_w.clear_cache()
 
1152
 
 
1153
        # signatures
 
1154
        revisions_with_signatures = set()
 
1155
        for rev_id in revision_ids:
 
1156
            try:
 
1157
                self.get_signature_text(rev_id)
 
1158
            except errors.NoSuchRevision:
 
1159
                # not signed.
 
1160
                pass
 
1161
            else:
 
1162
                revisions_with_signatures.add(rev_id)
 
1163
        yield ("signatures", None, revisions_with_signatures)
 
1164
 
 
1165
        # revisions
 
1166
        yield ("revisions", None, revision_ids)
 
1167
 
 
1168
    @needs_read_lock
 
1169
    def get_inventory_weave(self):
 
1170
        return self.control_weaves.get_weave('inventory',
 
1171
            self.get_transaction())
 
1172
 
 
1173
    @needs_read_lock
 
1174
    def get_inventory(self, revision_id):
 
1175
        """Get Inventory object by hash."""
 
1176
        return self.deserialise_inventory(
 
1177
            revision_id, self.get_inventory_xml(revision_id))
 
1178
 
 
1179
    def deserialise_inventory(self, revision_id, xml):
 
1180
        """Transform the xml into an inventory object. 
 
1181
 
 
1182
        :param revision_id: The expected revision id of the inventory.
 
1183
        :param xml: A serialised inventory.
 
1184
        """
 
1185
        return self._serializer.read_inventory_from_string(xml, revision_id)
 
1186
 
 
1187
    def serialise_inventory(self, inv):
 
1188
        return self._serializer.write_inventory_to_string(inv)
 
1189
 
 
1190
    def _serialise_inventory_to_lines(self, inv):
 
1191
        return self._serializer.write_inventory_to_lines(inv)
 
1192
 
 
1193
    def get_serializer_format(self):
 
1194
        return self._serializer.format_num
 
1195
 
 
1196
    @needs_read_lock
 
1197
    def get_inventory_xml(self, revision_id):
 
1198
        """Get inventory XML as a file object."""
 
1199
        try:
 
1200
            assert isinstance(revision_id, str), type(revision_id)
 
1201
            iw = self.get_inventory_weave()
 
1202
            return iw.get_text(revision_id)
 
1203
        except IndexError:
 
1204
            raise errors.HistoryMissing(self, 'inventory', revision_id)
 
1205
 
 
1206
    @needs_read_lock
 
1207
    def get_inventory_sha1(self, revision_id):
 
1208
        """Return the sha1 hash of the inventory entry
 
1209
        """
 
1210
        return self.get_revision(revision_id).inventory_sha1
 
1211
 
 
1212
    @needs_read_lock
 
1213
    def get_revision_graph(self, revision_id=None):
 
1214
        """Return a dictionary containing the revision graph.
 
1215
 
 
1216
        NB: This method should not be used as it accesses the entire graph all
 
1217
        at once, which is much more data than most operations should require.
 
1218
 
 
1219
        :param revision_id: The revision_id to get a graph from. If None, then
 
1220
        the entire revision graph is returned. This is a deprecated mode of
 
1221
        operation and will be removed in the future.
 
1222
        :return: a dictionary of revision_id->revision_parents_list.
 
1223
        """
 
1224
        raise NotImplementedError(self.get_revision_graph)
 
1225
 
 
1226
    @needs_read_lock
 
1227
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
1228
        """Return a graph of the revisions with ghosts marked as applicable.
 
1229
 
 
1230
        :param revision_ids: an iterable of revisions to graph or None for all.
 
1231
        :return: a Graph object with the graph reachable from revision_ids.
 
1232
        """
 
1233
        if 'evil' in debug.debug_flags:
 
1234
            mutter_callsite(3,
 
1235
                "get_revision_graph_with_ghosts scales with size of history.")
 
1236
        result = deprecated_graph.Graph()
 
1237
        if not revision_ids:
 
1238
            pending = set(self.all_revision_ids())
 
1239
            required = set([])
 
1240
        else:
 
1241
            pending = set(revision_ids)
 
1242
            # special case NULL_REVISION
 
1243
            if _mod_revision.NULL_REVISION in pending:
 
1244
                pending.remove(_mod_revision.NULL_REVISION)
 
1245
            required = set(pending)
 
1246
        done = set([])
 
1247
        while len(pending):
 
1248
            revision_id = pending.pop()
 
1249
            try:
 
1250
                rev = self.get_revision(revision_id)
 
1251
            except errors.NoSuchRevision:
 
1252
                if revision_id in required:
 
1253
                    raise
 
1254
                # a ghost
 
1255
                result.add_ghost(revision_id)
 
1256
                continue
 
1257
            for parent_id in rev.parent_ids:
 
1258
                # is this queued or done ?
 
1259
                if (parent_id not in pending and
 
1260
                    parent_id not in done):
 
1261
                    # no, queue it.
 
1262
                    pending.add(parent_id)
 
1263
            result.add_node(revision_id, rev.parent_ids)
 
1264
            done.add(revision_id)
 
1265
        return result
 
1266
 
 
1267
    def _get_history_vf(self):
 
1268
        """Get a versionedfile whose history graph reflects all revisions.
 
1269
 
 
1270
        For weave repositories, this is the inventory weave.
 
1271
        """
 
1272
        return self.get_inventory_weave()
 
1273
 
 
1274
    def iter_reverse_revision_history(self, revision_id):
 
1275
        """Iterate backwards through revision ids in the lefthand history
 
1276
 
 
1277
        :param revision_id: The revision id to start with.  All its lefthand
 
1278
            ancestors will be traversed.
 
1279
        """
 
1280
        if revision_id in (None, _mod_revision.NULL_REVISION):
 
1281
            return
 
1282
        next_id = revision_id
 
1283
        versionedfile = self._get_history_vf()
 
1284
        while True:
 
1285
            yield next_id
 
1286
            parents = versionedfile.get_parents(next_id)
 
1287
            if len(parents) == 0:
 
1288
                return
 
1289
            else:
 
1290
                next_id = parents[0]
 
1291
 
 
1292
    @needs_read_lock
 
1293
    def get_revision_inventory(self, revision_id):
 
1294
        """Return inventory of a past revision."""
 
1295
        # TODO: Unify this with get_inventory()
 
1296
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
 
1297
        # must be the same as its revision, so this is trivial.
 
1298
        if revision_id is None:
 
1299
            # This does not make sense: if there is no revision,
 
1300
            # then it is the current tree inventory surely ?!
 
1301
            # and thus get_root_id() is something that looks at the last
 
1302
            # commit on the branch, and the get_root_id is an inventory check.
 
1303
            raise NotImplementedError
 
1304
            # return Inventory(self.get_root_id())
 
1305
        else:
 
1306
            return self.get_inventory(revision_id)
 
1307
 
 
1308
    @needs_read_lock
 
1309
    def is_shared(self):
 
1310
        """Return True if this repository is flagged as a shared repository."""
 
1311
        raise NotImplementedError(self.is_shared)
 
1312
 
 
1313
    @needs_write_lock
 
1314
    def reconcile(self, other=None, thorough=False):
 
1315
        """Reconcile this repository."""
 
1316
        from bzrlib.reconcile import RepoReconciler
 
1317
        reconciler = RepoReconciler(self, thorough=thorough)
 
1318
        reconciler.reconcile()
 
1319
        return reconciler
 
1320
 
 
1321
    def _refresh_data(self):
 
1322
        """Helper called from lock_* to ensure coherency with disk.
 
1323
 
 
1324
        The default implementation does nothing; it is however possible
 
1325
        for repositories to maintain loaded indices across multiple locks
 
1326
        by checking inside their implementation of this method to see
 
1327
        whether their indices are still valid. This depends of course on
 
1328
        the disk format being validatable in this manner.
 
1329
        """
 
1330
 
 
1331
    @needs_read_lock
 
1332
    def revision_tree(self, revision_id):
 
1333
        """Return Tree for a revision on this branch.
 
1334
 
 
1335
        `revision_id` may be None for the empty tree revision.
 
1336
        """
 
1337
        # TODO: refactor this to use an existing revision object
 
1338
        # so we don't need to read it in twice.
 
1339
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
 
1340
            return RevisionTree(self, Inventory(root_id=None), 
 
1341
                                _mod_revision.NULL_REVISION)
 
1342
        else:
 
1343
            inv = self.get_revision_inventory(revision_id)
 
1344
            return RevisionTree(self, inv, revision_id)
 
1345
 
 
1346
    @needs_read_lock
 
1347
    def revision_trees(self, revision_ids):
 
1348
        """Return Tree for a revision on this branch.
 
1349
 
 
1350
        `revision_id` may not be None or 'null:'"""
 
1351
        assert None not in revision_ids
 
1352
        assert _mod_revision.NULL_REVISION not in revision_ids
 
1353
        texts = self.get_inventory_weave().get_texts(revision_ids)
 
1354
        for text, revision_id in zip(texts, revision_ids):
 
1355
            inv = self.deserialise_inventory(revision_id, text)
 
1356
            yield RevisionTree(self, inv, revision_id)
 
1357
 
 
1358
    @needs_read_lock
 
1359
    def get_ancestry(self, revision_id, topo_sorted=True):
 
1360
        """Return a list of revision-ids integrated by a revision.
 
1361
 
 
1362
        The first element of the list is always None, indicating the origin 
 
1363
        revision.  This might change when we have history horizons, or 
 
1364
        perhaps we should have a new API.
 
1365
        
 
1366
        This is topologically sorted.
 
1367
        """
 
1368
        if _mod_revision.is_null(revision_id):
 
1369
            return [None]
 
1370
        if not self.has_revision(revision_id):
 
1371
            raise errors.NoSuchRevision(self, revision_id)
 
1372
        w = self.get_inventory_weave()
 
1373
        candidates = w.get_ancestry(revision_id, topo_sorted)
 
1374
        return [None] + candidates # self._eliminate_revisions_not_present(candidates)
 
1375
 
 
1376
    def pack(self):
 
1377
        """Compress the data within the repository.
 
1378
 
 
1379
        This operation only makes sense for some repository types. For other
 
1380
        types it should be a no-op that just returns.
 
1381
 
 
1382
        This stub method does not require a lock, but subclasses should use
 
1383
        @needs_write_lock as this is a long running call its reasonable to 
 
1384
        implicitly lock for the user.
 
1385
        """
 
1386
 
 
1387
    @needs_read_lock
 
1388
    def print_file(self, file, revision_id):
 
1389
        """Print `file` to stdout.
 
1390
        
 
1391
        FIXME RBC 20060125 as John Meinel points out this is a bad api
 
1392
        - it writes to stdout, it assumes that that is valid etc. Fix
 
1393
        by creating a new more flexible convenience function.
 
1394
        """
 
1395
        tree = self.revision_tree(revision_id)
 
1396
        # use inventory as it was in that revision
 
1397
        file_id = tree.inventory.path2id(file)
 
1398
        if not file_id:
 
1399
            # TODO: jam 20060427 Write a test for this code path
 
1400
            #       it had a bug in it, and was raising the wrong
 
1401
            #       exception.
 
1402
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
 
1403
        tree.print_file(file_id)
 
1404
 
 
1405
    def get_transaction(self):
 
1406
        return self.control_files.get_transaction()
 
1407
 
 
1408
    def revision_parents(self, revision_id):
 
1409
        return self.get_inventory_weave().parent_names(revision_id)
 
1410
 
 
1411
    def get_parents(self, revision_ids):
 
1412
        """See StackedParentsProvider.get_parents"""
 
1413
        parents_list = []
 
1414
        for revision_id in revision_ids:
 
1415
            if revision_id == _mod_revision.NULL_REVISION:
 
1416
                parents = []
 
1417
            else:
 
1418
                try:
 
1419
                    parents = self.get_revision(revision_id).parent_ids
 
1420
                except errors.NoSuchRevision:
 
1421
                    parents = None
 
1422
                else:
 
1423
                    if len(parents) == 0:
 
1424
                        parents = [_mod_revision.NULL_REVISION]
 
1425
            parents_list.append(parents)
 
1426
        return parents_list
 
1427
 
 
1428
    def _make_parents_provider(self):
 
1429
        return self
 
1430
 
 
1431
    def get_graph(self, other_repository=None):
 
1432
        """Return the graph walker for this repository format"""
 
1433
        parents_provider = self._make_parents_provider()
 
1434
        if (other_repository is not None and
 
1435
            other_repository.bzrdir.transport.base !=
 
1436
            self.bzrdir.transport.base):
 
1437
            parents_provider = graph._StackedParentsProvider(
 
1438
                [parents_provider, other_repository._make_parents_provider()])
 
1439
        return graph.Graph(parents_provider)
 
1440
 
 
1441
    @needs_write_lock
 
1442
    def set_make_working_trees(self, new_value):
 
1443
        """Set the policy flag for making working trees when creating branches.
 
1444
 
 
1445
        This only applies to branches that use this repository.
 
1446
 
 
1447
        The default is 'True'.
 
1448
        :param new_value: True to restore the default, False to disable making
 
1449
                          working trees.
 
1450
        """
 
1451
        raise NotImplementedError(self.set_make_working_trees)
 
1452
    
 
1453
    def make_working_trees(self):
 
1454
        """Returns the policy for making working trees on new branches."""
 
1455
        raise NotImplementedError(self.make_working_trees)
 
1456
 
 
1457
    @needs_write_lock
 
1458
    def sign_revision(self, revision_id, gpg_strategy):
 
1459
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
 
1460
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
 
1461
 
 
1462
    @needs_read_lock
 
1463
    def has_signature_for_revision_id(self, revision_id):
 
1464
        """Query for a revision signature for revision_id in the repository."""
 
1465
        return self._revision_store.has_signature(revision_id,
 
1466
                                                  self.get_transaction())
 
1467
 
 
1468
    @needs_read_lock
 
1469
    def get_signature_text(self, revision_id):
 
1470
        """Return the text for a signature."""
 
1471
        return self._revision_store.get_signature_text(revision_id,
 
1472
                                                       self.get_transaction())
 
1473
 
 
1474
    @needs_read_lock
 
1475
    def check(self, revision_ids):
 
1476
        """Check consistency of all history of given revision_ids.
 
1477
 
 
1478
        Different repository implementations should override _check().
 
1479
 
 
1480
        :param revision_ids: A non-empty list of revision_ids whose ancestry
 
1481
             will be checked.  Typically the last revision_id of a branch.
 
1482
        """
 
1483
        if not revision_ids:
 
1484
            raise ValueError("revision_ids must be non-empty in %s.check" 
 
1485
                    % (self,))
 
1486
        return self._check(revision_ids)
 
1487
 
 
1488
    def _check(self, revision_ids):
 
1489
        result = check.Check(self)
 
1490
        result.check()
 
1491
        return result
 
1492
 
 
1493
    def _warn_if_deprecated(self):
 
1494
        global _deprecation_warning_done
 
1495
        if _deprecation_warning_done:
 
1496
            return
 
1497
        _deprecation_warning_done = True
 
1498
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
 
1499
                % (self._format, self.bzrdir.transport.base))
 
1500
 
 
1501
    def supports_rich_root(self):
 
1502
        return self._format.rich_root_data
 
1503
 
 
1504
    def _check_ascii_revisionid(self, revision_id, method):
 
1505
        """Private helper for ascii-only repositories."""
 
1506
        # weave repositories refuse to store revisionids that are non-ascii.
 
1507
        if revision_id is not None:
 
1508
            # weaves require ascii revision ids.
 
1509
            if isinstance(revision_id, unicode):
 
1510
                try:
 
1511
                    revision_id.encode('ascii')
 
1512
                except UnicodeEncodeError:
 
1513
                    raise errors.NonAsciiRevisionId(method, self)
 
1514
            else:
 
1515
                try:
 
1516
                    revision_id.decode('ascii')
 
1517
                except UnicodeDecodeError:
 
1518
                    raise errors.NonAsciiRevisionId(method, self)
 
1519
 
 
1520
 
 
1521
 
 
1522
# remove these delegates a while after bzr 0.15
 
1523
def __make_delegated(name, from_module):
 
1524
    def _deprecated_repository_forwarder():
 
1525
        symbol_versioning.warn('%s moved to %s in bzr 0.15'
 
1526
            % (name, from_module),
 
1527
            DeprecationWarning,
 
1528
            stacklevel=2)
 
1529
        m = __import__(from_module, globals(), locals(), [name])
 
1530
        try:
 
1531
            return getattr(m, name)
 
1532
        except AttributeError:
 
1533
            raise AttributeError('module %s has no name %s'
 
1534
                    % (m, name))
 
1535
    globals()[name] = _deprecated_repository_forwarder
 
1536
 
 
1537
for _name in [
 
1538
        'AllInOneRepository',
 
1539
        'WeaveMetaDirRepository',
 
1540
        'PreSplitOutRepositoryFormat',
 
1541
        'RepositoryFormat4',
 
1542
        'RepositoryFormat5',
 
1543
        'RepositoryFormat6',
 
1544
        'RepositoryFormat7',
 
1545
        ]:
 
1546
    __make_delegated(_name, 'bzrlib.repofmt.weaverepo')
 
1547
 
 
1548
for _name in [
 
1549
        'KnitRepository',
 
1550
        'RepositoryFormatKnit',
 
1551
        'RepositoryFormatKnit1',
 
1552
        ]:
 
1553
    __make_delegated(_name, 'bzrlib.repofmt.knitrepo')
 
1554
 
 
1555
 
 
1556
def install_revision(repository, rev, revision_tree):
 
1557
    """Install all revision data into a repository."""
 
1558
    present_parents = []
 
1559
    parent_trees = {}
 
1560
    for p_id in rev.parent_ids:
 
1561
        if repository.has_revision(p_id):
 
1562
            present_parents.append(p_id)
 
1563
            parent_trees[p_id] = repository.revision_tree(p_id)
 
1564
        else:
 
1565
            parent_trees[p_id] = repository.revision_tree(None)
 
1566
 
 
1567
    inv = revision_tree.inventory
 
1568
    entries = inv.iter_entries()
 
1569
    # backwards compatibility hack: skip the root id.
 
1570
    if not repository.supports_rich_root():
 
1571
        path, root = entries.next()
 
1572
        if root.revision != rev.revision_id:
 
1573
            raise errors.IncompatibleRevision(repr(repository))
 
1574
    # Add the texts that are not already present
 
1575
    for path, ie in entries:
 
1576
        w = repository.weave_store.get_weave_or_empty(ie.file_id,
 
1577
                repository.get_transaction())
 
1578
        if ie.revision not in w:
 
1579
            text_parents = []
 
1580
            # FIXME: TODO: The following loop *may* be overlapping/duplicate
 
1581
            # with InventoryEntry.find_previous_heads(). if it is, then there
 
1582
            # is a latent bug here where the parents may have ancestors of each
 
1583
            # other. RBC, AB
 
1584
            for revision, tree in parent_trees.iteritems():
 
1585
                if ie.file_id not in tree:
 
1586
                    continue
 
1587
                parent_id = tree.inventory[ie.file_id].revision
 
1588
                if parent_id in text_parents:
 
1589
                    continue
 
1590
                text_parents.append(parent_id)
 
1591
                    
 
1592
            vfile = repository.weave_store.get_weave_or_empty(ie.file_id, 
 
1593
                repository.get_transaction())
 
1594
            lines = revision_tree.get_file(ie.file_id).readlines()
 
1595
            vfile.add_lines(rev.revision_id, text_parents, lines)
 
1596
    try:
 
1597
        # install the inventory
 
1598
        repository.add_inventory(rev.revision_id, inv, present_parents)
 
1599
    except errors.RevisionAlreadyPresent:
 
1600
        pass
 
1601
    repository.add_revision(rev.revision_id, rev, inv)
 
1602
 
 
1603
 
 
1604
class MetaDirRepository(Repository):
 
1605
    """Repositories in the new meta-dir layout."""
 
1606
 
 
1607
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
1608
        super(MetaDirRepository, self).__init__(_format,
 
1609
                                                a_bzrdir,
 
1610
                                                control_files,
 
1611
                                                _revision_store,
 
1612
                                                control_store,
 
1613
                                                text_store)
 
1614
        dir_mode = self.control_files._dir_mode
 
1615
        file_mode = self.control_files._file_mode
 
1616
 
 
1617
    @needs_read_lock
 
1618
    def is_shared(self):
 
1619
        """Return True if this repository is flagged as a shared repository."""
 
1620
        return self.control_files._transport.has('shared-storage')
 
1621
 
 
1622
    @needs_write_lock
 
1623
    def set_make_working_trees(self, new_value):
 
1624
        """Set the policy flag for making working trees when creating branches.
 
1625
 
 
1626
        This only applies to branches that use this repository.
 
1627
 
 
1628
        The default is 'True'.
 
1629
        :param new_value: True to restore the default, False to disable making
 
1630
                          working trees.
 
1631
        """
 
1632
        if new_value:
 
1633
            try:
 
1634
                self.control_files._transport.delete('no-working-trees')
 
1635
            except errors.NoSuchFile:
 
1636
                pass
 
1637
        else:
 
1638
            self.control_files.put_utf8('no-working-trees', '')
 
1639
    
 
1640
    def make_working_trees(self):
 
1641
        """Returns the policy for making working trees on new branches."""
 
1642
        return not self.control_files._transport.has('no-working-trees')
 
1643
 
 
1644
 
 
1645
class RepositoryFormatRegistry(registry.Registry):
 
1646
    """Registry of RepositoryFormats."""
 
1647
 
 
1648
    def get(self, format_string):
 
1649
        r = registry.Registry.get(self, format_string)
 
1650
        if callable(r):
 
1651
            r = r()
 
1652
        return r
 
1653
    
 
1654
 
 
1655
format_registry = RepositoryFormatRegistry()
 
1656
"""Registry of formats, indexed by their identifying format string.
 
1657
 
 
1658
This can contain either format instances themselves, or classes/factories that
 
1659
can be called to obtain one.
 
1660
"""
 
1661
 
 
1662
 
 
1663
#####################################################################
 
1664
# Repository Formats
 
1665
 
 
1666
class RepositoryFormat(object):
 
1667
    """A repository format.
 
1668
 
 
1669
    Formats provide three things:
 
1670
     * An initialization routine to construct repository data on disk.
 
1671
     * a format string which is used when the BzrDir supports versioned
 
1672
       children.
 
1673
     * an open routine which returns a Repository instance.
 
1674
 
 
1675
    There is one and only one Format subclass for each on-disk format. But
 
1676
    there can be one Repository subclass that is used for several different
 
1677
    formats. The _format attribute on a Repository instance can be used to
 
1678
    determine the disk format.
 
1679
 
 
1680
    Formats are placed in an dict by their format string for reference 
 
1681
    during opening. These should be subclasses of RepositoryFormat
 
1682
    for consistency.
 
1683
 
 
1684
    Once a format is deprecated, just deprecate the initialize and open
 
1685
    methods on the format class. Do not deprecate the object, as the 
 
1686
    object will be created every system load.
 
1687
 
 
1688
    Common instance attributes:
 
1689
    _matchingbzrdir - the bzrdir format that the repository format was
 
1690
    originally written to work with. This can be used if manually
 
1691
    constructing a bzrdir and repository, or more commonly for test suite
 
1692
    parameterisation.
 
1693
    """
 
1694
 
 
1695
    def __str__(self):
 
1696
        return "<%s>" % self.__class__.__name__
 
1697
 
 
1698
    def __eq__(self, other):
 
1699
        # format objects are generally stateless
 
1700
        return isinstance(other, self.__class__)
 
1701
 
 
1702
    def __ne__(self, other):
 
1703
        return not self == other
 
1704
 
 
1705
    @classmethod
 
1706
    def find_format(klass, a_bzrdir):
 
1707
        """Return the format for the repository object in a_bzrdir.
 
1708
        
 
1709
        This is used by bzr native formats that have a "format" file in
 
1710
        the repository.  Other methods may be used by different types of 
 
1711
        control directory.
 
1712
        """
 
1713
        try:
 
1714
            transport = a_bzrdir.get_repository_transport(None)
 
1715
            format_string = transport.get("format").read()
 
1716
            return format_registry.get(format_string)
 
1717
        except errors.NoSuchFile:
 
1718
            raise errors.NoRepositoryPresent(a_bzrdir)
 
1719
        except KeyError:
 
1720
            raise errors.UnknownFormatError(format=format_string)
 
1721
 
 
1722
    @classmethod
 
1723
    def register_format(klass, format):
 
1724
        format_registry.register(format.get_format_string(), format)
 
1725
 
 
1726
    @classmethod
 
1727
    def unregister_format(klass, format):
 
1728
        format_registry.remove(format.get_format_string())
 
1729
    
 
1730
    @classmethod
 
1731
    def get_default_format(klass):
 
1732
        """Return the current default format."""
 
1733
        from bzrlib import bzrdir
 
1734
        return bzrdir.format_registry.make_bzrdir('default').repository_format
 
1735
 
 
1736
    def _get_control_store(self, repo_transport, control_files):
 
1737
        """Return the control store for this repository."""
 
1738
        raise NotImplementedError(self._get_control_store)
 
1739
 
 
1740
    def get_format_string(self):
 
1741
        """Return the ASCII format string that identifies this format.
 
1742
        
 
1743
        Note that in pre format ?? repositories the format string is 
 
1744
        not permitted nor written to disk.
 
1745
        """
 
1746
        raise NotImplementedError(self.get_format_string)
 
1747
 
 
1748
    def get_format_description(self):
 
1749
        """Return the short description for this format."""
 
1750
        raise NotImplementedError(self.get_format_description)
 
1751
 
 
1752
    def _get_revision_store(self, repo_transport, control_files):
 
1753
        """Return the revision store object for this a_bzrdir."""
 
1754
        raise NotImplementedError(self._get_revision_store)
 
1755
 
 
1756
    def _get_text_rev_store(self,
 
1757
                            transport,
 
1758
                            control_files,
 
1759
                            name,
 
1760
                            compressed=True,
 
1761
                            prefixed=False,
 
1762
                            serializer=None):
 
1763
        """Common logic for getting a revision store for a repository.
 
1764
        
 
1765
        see self._get_revision_store for the subclass-overridable method to 
 
1766
        get the store for a repository.
 
1767
        """
 
1768
        from bzrlib.store.revision.text import TextRevisionStore
 
1769
        dir_mode = control_files._dir_mode
 
1770
        file_mode = control_files._file_mode
 
1771
        text_store = TextStore(transport.clone(name),
 
1772
                              prefixed=prefixed,
 
1773
                              compressed=compressed,
 
1774
                              dir_mode=dir_mode,
 
1775
                              file_mode=file_mode)
 
1776
        _revision_store = TextRevisionStore(text_store, serializer)
 
1777
        return _revision_store
 
1778
 
 
1779
    # TODO: this shouldn't be in the base class, it's specific to things that
 
1780
    # use weaves or knits -- mbp 20070207
 
1781
    def _get_versioned_file_store(self,
 
1782
                                  name,
 
1783
                                  transport,
 
1784
                                  control_files,
 
1785
                                  prefixed=True,
 
1786
                                  versionedfile_class=None,
 
1787
                                  versionedfile_kwargs={},
 
1788
                                  escaped=False):
 
1789
        if versionedfile_class is None:
 
1790
            versionedfile_class = self._versionedfile_class
 
1791
        weave_transport = control_files._transport.clone(name)
 
1792
        dir_mode = control_files._dir_mode
 
1793
        file_mode = control_files._file_mode
 
1794
        return VersionedFileStore(weave_transport, prefixed=prefixed,
 
1795
                                  dir_mode=dir_mode,
 
1796
                                  file_mode=file_mode,
 
1797
                                  versionedfile_class=versionedfile_class,
 
1798
                                  versionedfile_kwargs=versionedfile_kwargs,
 
1799
                                  escaped=escaped)
 
1800
 
 
1801
    def initialize(self, a_bzrdir, shared=False):
 
1802
        """Initialize a repository of this format in a_bzrdir.
 
1803
 
 
1804
        :param a_bzrdir: The bzrdir to put the new repository in it.
 
1805
        :param shared: The repository should be initialized as a sharable one.
 
1806
        :returns: The new repository object.
 
1807
        
 
1808
        This may raise UninitializableFormat if shared repository are not
 
1809
        compatible the a_bzrdir.
 
1810
        """
 
1811
        raise NotImplementedError(self.initialize)
 
1812
 
 
1813
    def is_supported(self):
 
1814
        """Is this format supported?
 
1815
 
 
1816
        Supported formats must be initializable and openable.
 
1817
        Unsupported formats may not support initialization or committing or 
 
1818
        some other features depending on the reason for not being supported.
 
1819
        """
 
1820
        return True
 
1821
 
 
1822
    def check_conversion_target(self, target_format):
 
1823
        raise NotImplementedError(self.check_conversion_target)
 
1824
 
 
1825
    def open(self, a_bzrdir, _found=False):
 
1826
        """Return an instance of this format for the bzrdir a_bzrdir.
 
1827
        
 
1828
        _found is a private parameter, do not use it.
 
1829
        """
 
1830
        raise NotImplementedError(self.open)
 
1831
 
 
1832
 
 
1833
class MetaDirRepositoryFormat(RepositoryFormat):
 
1834
    """Common base class for the new repositories using the metadir layout."""
 
1835
 
 
1836
    rich_root_data = False
 
1837
    supports_tree_reference = False
 
1838
    _matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1839
 
 
1840
    def __init__(self):
 
1841
        super(MetaDirRepositoryFormat, self).__init__()
 
1842
 
 
1843
    def _create_control_files(self, a_bzrdir):
 
1844
        """Create the required files and the initial control_files object."""
 
1845
        # FIXME: RBC 20060125 don't peek under the covers
 
1846
        # NB: no need to escape relative paths that are url safe.
 
1847
        repository_transport = a_bzrdir.get_repository_transport(self)
 
1848
        control_files = lockable_files.LockableFiles(repository_transport,
 
1849
                                'lock', lockdir.LockDir)
 
1850
        control_files.create_lock()
 
1851
        return control_files
 
1852
 
 
1853
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
 
1854
        """Upload the initial blank content."""
 
1855
        control_files = self._create_control_files(a_bzrdir)
 
1856
        control_files.lock_write()
 
1857
        try:
 
1858
            control_files._transport.mkdir_multi(dirs,
 
1859
                    mode=control_files._dir_mode)
 
1860
            for file, content in files:
 
1861
                control_files.put(file, content)
 
1862
            for file, content in utf8_files:
 
1863
                control_files.put_utf8(file, content)
 
1864
            if shared == True:
 
1865
                control_files.put_utf8('shared-storage', '')
 
1866
        finally:
 
1867
            control_files.unlock()
 
1868
 
 
1869
 
 
1870
# formats which have no format string are not discoverable
 
1871
# and not independently creatable, so are not registered.  They're 
 
1872
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
 
1873
# needed, it's constructed directly by the BzrDir.  Non-native formats where
 
1874
# the repository is not separately opened are similar.
 
1875
 
 
1876
format_registry.register_lazy(
 
1877
    'Bazaar-NG Repository format 7',
 
1878
    'bzrlib.repofmt.weaverepo',
 
1879
    'RepositoryFormat7'
 
1880
    )
 
1881
 
 
1882
# KEEP in sync with bzrdir.format_registry default, which controls the overall
 
1883
# default control directory format
 
1884
format_registry.register_lazy(
 
1885
    'Bazaar-NG Knit Repository Format 1',
 
1886
    'bzrlib.repofmt.knitrepo',
 
1887
    'RepositoryFormatKnit1',
 
1888
    )
 
1889
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
 
1890
 
 
1891
format_registry.register_lazy(
 
1892
    'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
 
1893
    'bzrlib.repofmt.knitrepo',
 
1894
    'RepositoryFormatKnit3',
 
1895
    )
 
1896
 
 
1897
 
 
1898
class InterRepository(InterObject):
 
1899
    """This class represents operations taking place between two repositories.
 
1900
 
 
1901
    Its instances have methods like copy_content and fetch, and contain
 
1902
    references to the source and target repositories these operations can be 
 
1903
    carried out on.
 
1904
 
 
1905
    Often we will provide convenience methods on 'repository' which carry out
 
1906
    operations with another repository - they will always forward to
 
1907
    InterRepository.get(other).method_name(parameters).
 
1908
    """
 
1909
 
 
1910
    _optimisers = []
 
1911
    """The available optimised InterRepository types."""
 
1912
 
 
1913
    def copy_content(self, revision_id=None):
 
1914
        raise NotImplementedError(self.copy_content)
 
1915
 
 
1916
    def fetch(self, revision_id=None, pb=None):
 
1917
        """Fetch the content required to construct revision_id.
 
1918
 
 
1919
        The content is copied from self.source to self.target.
 
1920
 
 
1921
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
1922
                            content is copied.
 
1923
        :param pb: optional progress bar to use for progress reports. If not
 
1924
                   provided a default one will be created.
 
1925
 
 
1926
        Returns the copied revision count and the failed revisions in a tuple:
 
1927
        (copied, failures).
 
1928
        """
 
1929
        raise NotImplementedError(self.fetch)
 
1930
   
 
1931
    @needs_read_lock
 
1932
    def missing_revision_ids(self, revision_id=None):
 
1933
        """Return the revision ids that source has that target does not.
 
1934
        
 
1935
        These are returned in topological order.
 
1936
 
 
1937
        :param revision_id: only return revision ids included by this
 
1938
                            revision_id.
 
1939
        """
 
1940
        # generic, possibly worst case, slow code path.
 
1941
        target_ids = set(self.target.all_revision_ids())
 
1942
        if revision_id is not None:
 
1943
            source_ids = self.source.get_ancestry(revision_id)
 
1944
            assert source_ids[0] is None
 
1945
            source_ids.pop(0)
 
1946
        else:
 
1947
            source_ids = self.source.all_revision_ids()
 
1948
        result_set = set(source_ids).difference(target_ids)
 
1949
        # this may look like a no-op: its not. It preserves the ordering
 
1950
        # other_ids had while only returning the members from other_ids
 
1951
        # that we've decided we need.
 
1952
        return [rev_id for rev_id in source_ids if rev_id in result_set]
 
1953
 
 
1954
    @staticmethod
 
1955
    def _same_model(source, target):
 
1956
        """True if source and target have the same data representation."""
 
1957
        if source.supports_rich_root() != target.supports_rich_root():
 
1958
            return False
 
1959
        if source._serializer != target._serializer:
 
1960
            return False
 
1961
        return True
 
1962
 
 
1963
 
 
1964
class InterSameDataRepository(InterRepository):
 
1965
    """Code for converting between repositories that represent the same data.
 
1966
    
 
1967
    Data format and model must match for this to work.
 
1968
    """
 
1969
 
 
1970
    @classmethod
 
1971
    def _get_repo_format_to_test(self):
 
1972
        """Repository format for testing with.
 
1973
        
 
1974
        InterSameData can pull from subtree to subtree and from non-subtree to
 
1975
        non-subtree, so we test this with the richest repository format.
 
1976
        """
 
1977
        from bzrlib.repofmt import knitrepo
 
1978
        return knitrepo.RepositoryFormatKnit3()
 
1979
 
 
1980
    @staticmethod
 
1981
    def is_compatible(source, target):
 
1982
        return InterRepository._same_model(source, target)
 
1983
 
 
1984
    @needs_write_lock
 
1985
    def copy_content(self, revision_id=None):
 
1986
        """Make a complete copy of the content in self into destination.
 
1987
 
 
1988
        This copies both the repository's revision data, and configuration information
 
1989
        such as the make_working_trees setting.
 
1990
        
 
1991
        This is a destructive operation! Do not use it on existing 
 
1992
        repositories.
 
1993
 
 
1994
        :param revision_id: Only copy the content needed to construct
 
1995
                            revision_id and its parents.
 
1996
        """
 
1997
        try:
 
1998
            self.target.set_make_working_trees(self.source.make_working_trees())
 
1999
        except NotImplementedError:
 
2000
            pass
 
2001
        # but don't bother fetching if we have the needed data now.
 
2002
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
2003
            self.target.has_revision(revision_id)):
 
2004
            return
 
2005
        self.target.fetch(self.source, revision_id=revision_id)
 
2006
 
 
2007
    @needs_write_lock
 
2008
    def fetch(self, revision_id=None, pb=None):
 
2009
        """See InterRepository.fetch()."""
 
2010
        from bzrlib.fetch import GenericRepoFetcher
 
2011
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
2012
               self.source, self.source._format, self.target,
 
2013
               self.target._format)
 
2014
        f = GenericRepoFetcher(to_repository=self.target,
 
2015
                               from_repository=self.source,
 
2016
                               last_revision=revision_id,
 
2017
                               pb=pb)
 
2018
        return f.count_copied, f.failed_revisions
 
2019
 
 
2020
 
 
2021
class InterWeaveRepo(InterSameDataRepository):
 
2022
    """Optimised code paths between Weave based repositories.
 
2023
    
 
2024
    This should be in bzrlib/repofmt/weaverepo.py but we have not yet
 
2025
    implemented lazy inter-object optimisation.
 
2026
    """
 
2027
 
 
2028
    @classmethod
 
2029
    def _get_repo_format_to_test(self):
 
2030
        from bzrlib.repofmt import weaverepo
 
2031
        return weaverepo.RepositoryFormat7()
 
2032
 
 
2033
    @staticmethod
 
2034
    def is_compatible(source, target):
 
2035
        """Be compatible with known Weave formats.
 
2036
        
 
2037
        We don't test for the stores being of specific types because that
 
2038
        could lead to confusing results, and there is no need to be 
 
2039
        overly general.
 
2040
        """
 
2041
        from bzrlib.repofmt.weaverepo import (
 
2042
                RepositoryFormat5,
 
2043
                RepositoryFormat6,
 
2044
                RepositoryFormat7,
 
2045
                )
 
2046
        try:
 
2047
            return (isinstance(source._format, (RepositoryFormat5,
 
2048
                                                RepositoryFormat6,
 
2049
                                                RepositoryFormat7)) and
 
2050
                    isinstance(target._format, (RepositoryFormat5,
 
2051
                                                RepositoryFormat6,
 
2052
                                                RepositoryFormat7)))
 
2053
        except AttributeError:
 
2054
            return False
 
2055
    
 
2056
    @needs_write_lock
 
2057
    def copy_content(self, revision_id=None):
 
2058
        """See InterRepository.copy_content()."""
 
2059
        # weave specific optimised path:
 
2060
        try:
 
2061
            self.target.set_make_working_trees(self.source.make_working_trees())
 
2062
        except NotImplementedError:
 
2063
            pass
 
2064
        # FIXME do not peek!
 
2065
        if self.source.control_files._transport.listable():
 
2066
            pb = ui.ui_factory.nested_progress_bar()
 
2067
            try:
 
2068
                self.target.weave_store.copy_all_ids(
 
2069
                    self.source.weave_store,
 
2070
                    pb=pb,
 
2071
                    from_transaction=self.source.get_transaction(),
 
2072
                    to_transaction=self.target.get_transaction())
 
2073
                pb.update('copying inventory', 0, 1)
 
2074
                self.target.control_weaves.copy_multi(
 
2075
                    self.source.control_weaves, ['inventory'],
 
2076
                    from_transaction=self.source.get_transaction(),
 
2077
                    to_transaction=self.target.get_transaction())
 
2078
                self.target._revision_store.text_store.copy_all_ids(
 
2079
                    self.source._revision_store.text_store,
 
2080
                    pb=pb)
 
2081
            finally:
 
2082
                pb.finished()
 
2083
        else:
 
2084
            self.target.fetch(self.source, revision_id=revision_id)
 
2085
 
 
2086
    @needs_write_lock
 
2087
    def fetch(self, revision_id=None, pb=None):
 
2088
        """See InterRepository.fetch()."""
 
2089
        from bzrlib.fetch import GenericRepoFetcher
 
2090
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
2091
               self.source, self.source._format, self.target, self.target._format)
 
2092
        f = GenericRepoFetcher(to_repository=self.target,
 
2093
                               from_repository=self.source,
 
2094
                               last_revision=revision_id,
 
2095
                               pb=pb)
 
2096
        return f.count_copied, f.failed_revisions
 
2097
 
 
2098
    @needs_read_lock
 
2099
    def missing_revision_ids(self, revision_id=None):
 
2100
        """See InterRepository.missing_revision_ids()."""
 
2101
        # we want all revisions to satisfy revision_id in source.
 
2102
        # but we don't want to stat every file here and there.
 
2103
        # we want then, all revisions other needs to satisfy revision_id 
 
2104
        # checked, but not those that we have locally.
 
2105
        # so the first thing is to get a subset of the revisions to 
 
2106
        # satisfy revision_id in source, and then eliminate those that
 
2107
        # we do already have. 
 
2108
        # this is slow on high latency connection to self, but as as this
 
2109
        # disk format scales terribly for push anyway due to rewriting 
 
2110
        # inventory.weave, this is considered acceptable.
 
2111
        # - RBC 20060209
 
2112
        if revision_id is not None:
 
2113
            source_ids = self.source.get_ancestry(revision_id)
 
2114
            assert source_ids[0] is None
 
2115
            source_ids.pop(0)
 
2116
        else:
 
2117
            source_ids = self.source._all_possible_ids()
 
2118
        source_ids_set = set(source_ids)
 
2119
        # source_ids is the worst possible case we may need to pull.
 
2120
        # now we want to filter source_ids against what we actually
 
2121
        # have in target, but don't try to check for existence where we know
 
2122
        # we do not have a revision as that would be pointless.
 
2123
        target_ids = set(self.target._all_possible_ids())
 
2124
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
2125
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
2126
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
2127
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
2128
        if revision_id is not None:
 
2129
            # we used get_ancestry to determine source_ids then we are assured all
 
2130
            # revisions referenced are present as they are installed in topological order.
 
2131
            # and the tip revision was validated by get_ancestry.
 
2132
            return required_topo_revisions
 
2133
        else:
 
2134
            # if we just grabbed the possibly available ids, then 
 
2135
            # we only have an estimate of whats available and need to validate
 
2136
            # that against the revision records.
 
2137
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
2138
 
 
2139
 
 
2140
class InterKnitRepo(InterSameDataRepository):
 
2141
    """Optimised code paths between Knit based repositories."""
 
2142
 
 
2143
    @classmethod
 
2144
    def _get_repo_format_to_test(self):
 
2145
        from bzrlib.repofmt import knitrepo
 
2146
        return knitrepo.RepositoryFormatKnit1()
 
2147
 
 
2148
    @staticmethod
 
2149
    def is_compatible(source, target):
 
2150
        """Be compatible with known Knit formats.
 
2151
        
 
2152
        We don't test for the stores being of specific types because that
 
2153
        could lead to confusing results, and there is no need to be 
 
2154
        overly general.
 
2155
        """
 
2156
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit
 
2157
        try:
 
2158
            are_knits = (isinstance(source._format, RepositoryFormatKnit) and
 
2159
                isinstance(target._format, RepositoryFormatKnit))
 
2160
        except AttributeError:
 
2161
            return False
 
2162
        return are_knits and InterRepository._same_model(source, target)
 
2163
 
 
2164
    @needs_write_lock
 
2165
    def fetch(self, revision_id=None, pb=None):
 
2166
        """See InterRepository.fetch()."""
 
2167
        from bzrlib.fetch import KnitRepoFetcher
 
2168
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
2169
               self.source, self.source._format, self.target, self.target._format)
 
2170
        f = KnitRepoFetcher(to_repository=self.target,
 
2171
                            from_repository=self.source,
 
2172
                            last_revision=revision_id,
 
2173
                            pb=pb)
 
2174
        return f.count_copied, f.failed_revisions
 
2175
 
 
2176
    @needs_read_lock
 
2177
    def missing_revision_ids(self, revision_id=None):
 
2178
        """See InterRepository.missing_revision_ids()."""
 
2179
        if revision_id is not None:
 
2180
            source_ids = self.source.get_ancestry(revision_id)
 
2181
            assert source_ids[0] is None
 
2182
            source_ids.pop(0)
 
2183
        else:
 
2184
            source_ids = self.source.all_revision_ids()
 
2185
        source_ids_set = set(source_ids)
 
2186
        # source_ids is the worst possible case we may need to pull.
 
2187
        # now we want to filter source_ids against what we actually
 
2188
        # have in target, but don't try to check for existence where we know
 
2189
        # we do not have a revision as that would be pointless.
 
2190
        target_ids = set(self.target.all_revision_ids())
 
2191
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
2192
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
2193
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
2194
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
2195
        if revision_id is not None:
 
2196
            # we used get_ancestry to determine source_ids then we are assured all
 
2197
            # revisions referenced are present as they are installed in topological order.
 
2198
            # and the tip revision was validated by get_ancestry.
 
2199
            return required_topo_revisions
 
2200
        else:
 
2201
            # if we just grabbed the possibly available ids, then 
 
2202
            # we only have an estimate of whats available and need to validate
 
2203
            # that against the revision records.
 
2204
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
2205
 
 
2206
 
 
2207
class InterModel1and2(InterRepository):
 
2208
 
 
2209
    @classmethod
 
2210
    def _get_repo_format_to_test(self):
 
2211
        return None
 
2212
 
 
2213
    @staticmethod
 
2214
    def is_compatible(source, target):
 
2215
        if not source.supports_rich_root() and target.supports_rich_root():
 
2216
            return True
 
2217
        else:
 
2218
            return False
 
2219
 
 
2220
    @needs_write_lock
 
2221
    def fetch(self, revision_id=None, pb=None):
 
2222
        """See InterRepository.fetch()."""
 
2223
        from bzrlib.fetch import Model1toKnit2Fetcher
 
2224
        f = Model1toKnit2Fetcher(to_repository=self.target,
 
2225
                                 from_repository=self.source,
 
2226
                                 last_revision=revision_id,
 
2227
                                 pb=pb)
 
2228
        return f.count_copied, f.failed_revisions
 
2229
 
 
2230
    @needs_write_lock
 
2231
    def copy_content(self, revision_id=None):
 
2232
        """Make a complete copy of the content in self into destination.
 
2233
        
 
2234
        This is a destructive operation! Do not use it on existing 
 
2235
        repositories.
 
2236
 
 
2237
        :param revision_id: Only copy the content needed to construct
 
2238
                            revision_id and its parents.
 
2239
        """
 
2240
        try:
 
2241
            self.target.set_make_working_trees(self.source.make_working_trees())
 
2242
        except NotImplementedError:
 
2243
            pass
 
2244
        # but don't bother fetching if we have the needed data now.
 
2245
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
2246
            self.target.has_revision(revision_id)):
 
2247
            return
 
2248
        self.target.fetch(self.source, revision_id=revision_id)
 
2249
 
 
2250
 
 
2251
class InterKnit1and2(InterKnitRepo):
 
2252
 
 
2253
    @classmethod
 
2254
    def _get_repo_format_to_test(self):
 
2255
        return None
 
2256
 
 
2257
    @staticmethod
 
2258
    def is_compatible(source, target):
 
2259
        """Be compatible with Knit1 source and Knit3 target"""
 
2260
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
 
2261
        try:
 
2262
            from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
 
2263
                    RepositoryFormatKnit3
 
2264
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
2265
                    isinstance(target._format, (RepositoryFormatKnit3)))
 
2266
        except AttributeError:
 
2267
            return False
 
2268
 
 
2269
    @needs_write_lock
 
2270
    def fetch(self, revision_id=None, pb=None):
 
2271
        """See InterRepository.fetch()."""
 
2272
        from bzrlib.fetch import Knit1to2Fetcher
 
2273
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
2274
               self.source, self.source._format, self.target, 
 
2275
               self.target._format)
 
2276
        f = Knit1to2Fetcher(to_repository=self.target,
 
2277
                            from_repository=self.source,
 
2278
                            last_revision=revision_id,
 
2279
                            pb=pb)
 
2280
        return f.count_copied, f.failed_revisions
 
2281
 
 
2282
 
 
2283
class InterRemoteRepository(InterRepository):
 
2284
    """Code for converting between RemoteRepository objects.
 
2285
 
 
2286
    This just gets an non-remote repository from the RemoteRepository, and calls
 
2287
    InterRepository.get again.
 
2288
    """
 
2289
 
 
2290
    def __init__(self, source, target):
 
2291
        if isinstance(source, remote.RemoteRepository):
 
2292
            source._ensure_real()
 
2293
            real_source = source._real_repository
 
2294
        else:
 
2295
            real_source = source
 
2296
        if isinstance(target, remote.RemoteRepository):
 
2297
            target._ensure_real()
 
2298
            real_target = target._real_repository
 
2299
        else:
 
2300
            real_target = target
 
2301
        self.real_inter = InterRepository.get(real_source, real_target)
 
2302
 
 
2303
    @staticmethod
 
2304
    def is_compatible(source, target):
 
2305
        if isinstance(source, remote.RemoteRepository):
 
2306
            return True
 
2307
        if isinstance(target, remote.RemoteRepository):
 
2308
            return True
 
2309
        return False
 
2310
 
 
2311
    def copy_content(self, revision_id=None):
 
2312
        self.real_inter.copy_content(revision_id=revision_id)
 
2313
 
 
2314
    def fetch(self, revision_id=None, pb=None):
 
2315
        self.real_inter.fetch(revision_id=revision_id, pb=pb)
 
2316
 
 
2317
    @classmethod
 
2318
    def _get_repo_format_to_test(self):
 
2319
        return None
 
2320
 
 
2321
 
 
2322
InterRepository.register_optimiser(InterSameDataRepository)
 
2323
InterRepository.register_optimiser(InterWeaveRepo)
 
2324
InterRepository.register_optimiser(InterKnitRepo)
 
2325
InterRepository.register_optimiser(InterModel1and2)
 
2326
InterRepository.register_optimiser(InterKnit1and2)
 
2327
InterRepository.register_optimiser(InterRemoteRepository)
 
2328
 
 
2329
 
 
2330
class CopyConverter(object):
 
2331
    """A repository conversion tool which just performs a copy of the content.
 
2332
    
 
2333
    This is slow but quite reliable.
 
2334
    """
 
2335
 
 
2336
    def __init__(self, target_format):
 
2337
        """Create a CopyConverter.
 
2338
 
 
2339
        :param target_format: The format the resulting repository should be.
 
2340
        """
 
2341
        self.target_format = target_format
 
2342
        
 
2343
    def convert(self, repo, pb):
 
2344
        """Perform the conversion of to_convert, giving feedback via pb.
 
2345
 
 
2346
        :param to_convert: The disk object to convert.
 
2347
        :param pb: a progress bar to use for progress information.
 
2348
        """
 
2349
        self.pb = pb
 
2350
        self.count = 0
 
2351
        self.total = 4
 
2352
        # this is only useful with metadir layouts - separated repo content.
 
2353
        # trigger an assertion if not such
 
2354
        repo._format.get_format_string()
 
2355
        self.repo_dir = repo.bzrdir
 
2356
        self.step('Moving repository to repository.backup')
 
2357
        self.repo_dir.transport.move('repository', 'repository.backup')
 
2358
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
 
2359
        repo._format.check_conversion_target(self.target_format)
 
2360
        self.source_repo = repo._format.open(self.repo_dir,
 
2361
            _found=True,
 
2362
            _override_transport=backup_transport)
 
2363
        self.step('Creating new repository')
 
2364
        converted = self.target_format.initialize(self.repo_dir,
 
2365
                                                  self.source_repo.is_shared())
 
2366
        converted.lock_write()
 
2367
        try:
 
2368
            self.step('Copying content into repository.')
 
2369
            self.source_repo.copy_content_into(converted)
 
2370
        finally:
 
2371
            converted.unlock()
 
2372
        self.step('Deleting old repository content.')
 
2373
        self.repo_dir.transport.delete_tree('repository.backup')
 
2374
        self.pb.note('repository converted')
 
2375
 
 
2376
    def step(self, message):
 
2377
        """Update the pb by a step."""
 
2378
        self.count +=1
 
2379
        self.pb.update(message, self.count, self.total)
 
2380
 
 
2381
 
 
2382
_unescape_map = {
 
2383
    'apos':"'",
 
2384
    'quot':'"',
 
2385
    'amp':'&',
 
2386
    'lt':'<',
 
2387
    'gt':'>'
 
2388
}
 
2389
 
 
2390
 
 
2391
def _unescaper(match, _map=_unescape_map):
 
2392
    code = match.group(1)
 
2393
    try:
 
2394
        return _map[code]
 
2395
    except KeyError:
 
2396
        if not code.startswith('#'):
 
2397
            raise
 
2398
        return unichr(int(code[1:])).encode('utf8')
 
2399
 
 
2400
 
 
2401
_unescape_re = None
 
2402
 
 
2403
 
 
2404
def _unescape_xml(data):
 
2405
    """Unescape predefined XML entities in a string of data."""
 
2406
    global _unescape_re
 
2407
    if _unescape_re is None:
 
2408
        _unescape_re = re.compile('\&([^;]*);')
 
2409
    return _unescape_re.sub(_unescaper, data)