/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: Robert Collins
  • Date: 2007-10-04 01:24:06 UTC
  • mto: This revision was merged to the branch mainline in revision 2889.
  • Revision ID: robertc@robertcollins.net-20071004012406-20bfylx7ngky01r5
Move responsibility for detecting same-repo fetching from the
per-repository fetch logic to the wrapper function that is the official
API. (Robert Collins)

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