/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-15 04:50:34 UTC
  • mto: This revision was merged to the branch mainline in revision 2913.
  • Revision ID: mbp@sourcefrog.net-20071015045034-390357g4hrq386qp
Review cleanups, mostly documentation

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