/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: Martin Pool
  • Date: 2007-10-12 08:00:07 UTC
  • mto: This revision was merged to the branch mainline in revision 2913.
  • Revision ID: mbp@sourcefrog.net-20071012080007-vf80woayyom8s8e1
Rename update_to_one_parent_via_delta to more wieldy update_basis_by_delta

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