/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: 2008-09-19 06:53:41 UTC
  • mto: (3696.5.1 commit-updates)
  • mto: This revision was merged to the branch mainline in revision 3741.
  • Revision ID: robertc@robertcollins.net-20080919065341-5t5w1p2gi926nfia
First cut - make it work - at updating the tree stat cache during commit.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008 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
    errors,
 
29
    generate_ids,
 
30
    gpg,
 
31
    graph,
 
32
    lazy_regex,
 
33
    lockable_files,
 
34
    lockdir,
 
35
    lru_cache,
 
36
    osutils,
 
37
    registry,
 
38
    remote,
 
39
    revision as _mod_revision,
 
40
    symbol_versioning,
 
41
    transactions,
 
42
    tsort,
 
43
    ui,
 
44
    )
 
45
from bzrlib.bundle import serializer
 
46
from bzrlib.revisiontree import RevisionTree
 
47
from bzrlib.store.versioned import VersionedFileStore
 
48
from bzrlib.store.text import TextStore
 
49
from bzrlib.testament import Testament
 
50
from bzrlib.util import bencode
 
51
""")
 
52
 
 
53
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
54
from bzrlib.inter import InterObject
 
55
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
 
56
from bzrlib.symbol_versioning import (
 
57
        deprecated_method,
 
58
        one_one,
 
59
        one_two,
 
60
        one_three,
 
61
        one_six,
 
62
        )
 
63
from bzrlib.trace import mutter, mutter_callsite, note, warning
 
64
 
 
65
 
 
66
# Old formats display a warning, but only once
 
67
_deprecation_warning_done = False
 
68
 
 
69
 
 
70
class CommitBuilder(object):
 
71
    """Provides an interface to build up a commit.
 
72
 
 
73
    This allows describing a tree to be committed without needing to 
 
74
    know the internals of the format of the repository.
 
75
    """
 
76
    
 
77
    # all clients should supply tree roots.
 
78
    record_root_entry = True
 
79
    # the default CommitBuilder does not manage trees whose root is versioned.
 
80
    _versioned_root = False
 
81
 
 
82
    def __init__(self, repository, parents, config, timestamp=None,
 
83
                 timezone=None, committer=None, revprops=None,
 
84
                 revision_id=None):
 
85
        """Initiate a CommitBuilder.
 
86
 
 
87
        :param repository: Repository to commit to.
 
88
        :param parents: Revision ids of the parents of the new revision.
 
89
        :param config: Configuration to use.
 
90
        :param timestamp: Optional timestamp recorded for commit.
 
91
        :param timezone: Optional timezone for timestamp.
 
92
        :param committer: Optional committer to set for commit.
 
93
        :param revprops: Optional dictionary of revision properties.
 
94
        :param revision_id: Optional revision id.
 
95
        """
 
96
        self._config = config
 
97
 
 
98
        if committer is None:
 
99
            self._committer = self._config.username()
 
100
        else:
 
101
            self._committer = committer
 
102
 
 
103
        self.new_inventory = Inventory(None)
 
104
        self._new_revision_id = revision_id
 
105
        self.parents = parents
 
106
        self.repository = repository
 
107
 
 
108
        self._revprops = {}
 
109
        if revprops is not None:
 
110
            self._revprops.update(revprops)
 
111
 
 
112
        if timestamp is None:
 
113
            timestamp = time.time()
 
114
        # Restrict resolution to 1ms
 
115
        self._timestamp = round(timestamp, 3)
 
116
 
 
117
        if timezone is None:
 
118
            self._timezone = osutils.local_time_offset()
 
119
        else:
 
120
            self._timezone = int(timezone)
 
121
 
 
122
        self._generate_revision_if_needed()
 
123
        self.__heads = graph.HeadsCache(repository.get_graph()).heads
 
124
 
 
125
    def commit(self, message):
 
126
        """Make the actual commit.
 
127
 
 
128
        :return: The revision id of the recorded revision.
 
129
        """
 
130
        rev = _mod_revision.Revision(
 
131
                       timestamp=self._timestamp,
 
132
                       timezone=self._timezone,
 
133
                       committer=self._committer,
 
134
                       message=message,
 
135
                       inventory_sha1=self.inv_sha1,
 
136
                       revision_id=self._new_revision_id,
 
137
                       properties=self._revprops)
 
138
        rev.parent_ids = self.parents
 
139
        self.repository.add_revision(self._new_revision_id, rev,
 
140
            self.new_inventory, self._config)
 
141
        self.repository.commit_write_group()
 
142
        return self._new_revision_id
 
143
 
 
144
    def abort(self):
 
145
        """Abort the commit that is being built.
 
146
        """
 
147
        self.repository.abort_write_group()
 
148
 
 
149
    def revision_tree(self):
 
150
        """Return the tree that was just committed.
 
151
 
 
152
        After calling commit() this can be called to get a RevisionTree
 
153
        representing the newly committed tree. This is preferred to
 
154
        calling Repository.revision_tree() because that may require
 
155
        deserializing the inventory, while we already have a copy in
 
156
        memory.
 
157
        """
 
158
        return RevisionTree(self.repository, self.new_inventory,
 
159
                            self._new_revision_id)
 
160
 
 
161
    def finish_inventory(self):
 
162
        """Tell the builder that the inventory is finished."""
 
163
        if self.new_inventory.root is None:
 
164
            raise AssertionError('Root entry should be supplied to'
 
165
                ' record_entry_contents, as of bzr 0.10.')
 
166
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
 
167
        self.new_inventory.revision_id = self._new_revision_id
 
168
        self.inv_sha1 = self.repository.add_inventory(
 
169
            self._new_revision_id,
 
170
            self.new_inventory,
 
171
            self.parents
 
172
            )
 
173
 
 
174
    def _gen_revision_id(self):
 
175
        """Return new revision-id."""
 
176
        return generate_ids.gen_revision_id(self._config.username(),
 
177
                                            self._timestamp)
 
178
 
 
179
    def _generate_revision_if_needed(self):
 
180
        """Create a revision id if None was supplied.
 
181
        
 
182
        If the repository can not support user-specified revision ids
 
183
        they should override this function and raise CannotSetRevisionId
 
184
        if _new_revision_id is not None.
 
185
 
 
186
        :raises: CannotSetRevisionId
 
187
        """
 
188
        if self._new_revision_id is None:
 
189
            self._new_revision_id = self._gen_revision_id()
 
190
            self.random_revid = True
 
191
        else:
 
192
            self.random_revid = False
 
193
 
 
194
    def _heads(self, file_id, revision_ids):
 
195
        """Calculate the graph heads for revision_ids in the graph of file_id.
 
196
 
 
197
        This can use either a per-file graph or a global revision graph as we
 
198
        have an identity relationship between the two graphs.
 
199
        """
 
200
        return self.__heads(revision_ids)
 
201
 
 
202
    def _check_root(self, ie, parent_invs, tree):
 
203
        """Helper for record_entry_contents.
 
204
 
 
205
        :param ie: An entry being added.
 
206
        :param parent_invs: The inventories of the parent revisions of the
 
207
            commit.
 
208
        :param tree: The tree that is being committed.
 
209
        """
 
210
        # In this revision format, root entries have no knit or weave When
 
211
        # serializing out to disk and back in root.revision is always
 
212
        # _new_revision_id
 
213
        ie.revision = self._new_revision_id
 
214
 
 
215
    def _get_delta(self, ie, basis_inv, path):
 
216
        """Get a delta against the basis inventory for ie."""
 
217
        if ie.file_id not in basis_inv:
 
218
            # add
 
219
            return (None, path, ie.file_id, ie)
 
220
        elif ie != basis_inv[ie.file_id]:
 
221
            # common but altered
 
222
            # TODO: avoid tis id2path call.
 
223
            return (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
 
224
        else:
 
225
            # common, unaltered
 
226
            return None
 
227
 
 
228
    def record_entry_contents(self, ie, parent_invs, path, tree,
 
229
        content_summary):
 
230
        """Record the content of ie from tree into the commit if needed.
 
231
 
 
232
        Side effect: sets ie.revision when unchanged
 
233
 
 
234
        :param ie: An inventory entry present in the commit.
 
235
        :param parent_invs: The inventories of the parent revisions of the
 
236
            commit.
 
237
        :param path: The path the entry is at in the tree.
 
238
        :param tree: The tree which contains this entry and should be used to 
 
239
            obtain content.
 
240
        :param content_summary: Summary data from the tree about the paths
 
241
            content - stat, length, exec, sha/link target. This is only
 
242
            accessed when the entry has a revision of None - that is when it is
 
243
            a candidate to commit.
 
244
        :return: A tuple (change_delta, version_recorded, fs_hash).
 
245
            change_delta is an inventory_delta change for this entry against
 
246
            the basis tree of the commit, or None if no change occured against
 
247
            the basis tree.
 
248
            version_recorded is True if a new version of the entry has been
 
249
            recorded. For instance, committing a merge where a file was only
 
250
            changed on the other side will return (delta, False).
 
251
            fs_hash is either None, or the hash of the path. (Currently we 
 
252
            use sha1 hashes of the entire file content, and only calculate
 
253
            these for regular files).
 
254
        """
 
255
        if self.new_inventory.root is None:
 
256
            if ie.parent_id is not None:
 
257
                raise errors.RootMissing()
 
258
            self._check_root(ie, parent_invs, tree)
 
259
        if ie.revision is None:
 
260
            kind = content_summary[0]
 
261
        else:
 
262
            # ie is carried over from a prior commit
 
263
            kind = ie.kind
 
264
        # XXX: repository specific check for nested tree support goes here - if
 
265
        # the repo doesn't want nested trees we skip it ?
 
266
        if (kind == 'tree-reference' and
 
267
            not self.repository._format.supports_tree_reference):
 
268
            # mismatch between commit builder logic and repository:
 
269
            # this needs the entry creation pushed down into the builder.
 
270
            raise NotImplementedError('Missing repository subtree support.')
 
271
        self.new_inventory.add(ie)
 
272
 
 
273
        # TODO: slow, take it out of the inner loop.
 
274
        try:
 
275
            basis_inv = parent_invs[0]
 
276
        except IndexError:
 
277
            basis_inv = Inventory(root_id=None)
 
278
 
 
279
        # ie.revision is always None if the InventoryEntry is considered
 
280
        # for committing. We may record the previous parents revision if the
 
281
        # content is actually unchanged against a sole head.
 
282
        if ie.revision is not None:
 
283
            if not self._versioned_root and path == '':
 
284
                # repositories that do not version the root set the root's
 
285
                # revision to the new commit even when no change occurs, and
 
286
                # this masks when a change may have occurred against the basis,
 
287
                # so calculate if one happened.
 
288
                if ie.file_id in basis_inv:
 
289
                    delta = (basis_inv.id2path(ie.file_id), path,
 
290
                        ie.file_id, ie)
 
291
                else:
 
292
                    # add
 
293
                    delta = (None, path, ie.file_id, ie)
 
294
                return delta, False, None
 
295
            else:
 
296
                # we don't need to commit this, because the caller already
 
297
                # determined that an existing revision of this file is
 
298
                # appropriate. If its not being considered for committing then
 
299
                # it and all its parents to the root must be unaltered so
 
300
                # no-change against the basis.
 
301
                if ie.revision == self._new_revision_id:
 
302
                    raise AssertionError("Impossible situation, a skipped "
 
303
                        "inventory entry (%r) claims to be modified in this "
 
304
                        "commit (%r).", (ie, self._new_revision_id))
 
305
                return None, False, None
 
306
        # XXX: Friction: parent_candidates should return a list not a dict
 
307
        #      so that we don't have to walk the inventories again.
 
308
        parent_candiate_entries = ie.parent_candidates(parent_invs)
 
309
        head_set = self._heads(ie.file_id, parent_candiate_entries.keys())
 
310
        heads = []
 
311
        for inv in parent_invs:
 
312
            if ie.file_id in inv:
 
313
                old_rev = inv[ie.file_id].revision
 
314
                if old_rev in head_set:
 
315
                    heads.append(inv[ie.file_id].revision)
 
316
                    head_set.remove(inv[ie.file_id].revision)
 
317
 
 
318
        store = False
 
319
        # now we check to see if we need to write a new record to the
 
320
        # file-graph.
 
321
        # We write a new entry unless there is one head to the ancestors, and
 
322
        # the kind-derived content is unchanged.
 
323
 
 
324
        # Cheapest check first: no ancestors, or more the one head in the
 
325
        # ancestors, we write a new node.
 
326
        if len(heads) != 1:
 
327
            store = True
 
328
        if not store:
 
329
            # There is a single head, look it up for comparison
 
330
            parent_entry = parent_candiate_entries[heads[0]]
 
331
            # if the non-content specific data has changed, we'll be writing a
 
332
            # node:
 
333
            if (parent_entry.parent_id != ie.parent_id or
 
334
                parent_entry.name != ie.name):
 
335
                store = True
 
336
        # now we need to do content specific checks:
 
337
        if not store:
 
338
            # if the kind changed the content obviously has
 
339
            if kind != parent_entry.kind:
 
340
                store = True
 
341
        if kind == 'file':
 
342
            if content_summary[2] is None:
 
343
                raise ValueError("Files must not have executable = None")
 
344
            if not store:
 
345
                if (# if the file length changed we have to store:
 
346
                    parent_entry.text_size != content_summary[1] or
 
347
                    # if the exec bit has changed we have to store:
 
348
                    parent_entry.executable != content_summary[2]):
 
349
                    store = True
 
350
                elif parent_entry.text_sha1 == content_summary[3]:
 
351
                    # all meta and content is unchanged (using a hash cache
 
352
                    # hit to check the sha)
 
353
                    ie.revision = parent_entry.revision
 
354
                    ie.text_size = parent_entry.text_size
 
355
                    ie.text_sha1 = parent_entry.text_sha1
 
356
                    ie.executable = parent_entry.executable
 
357
                    return self._get_delta(ie, basis_inv, path), False, None
 
358
                else:
 
359
                    # Either there is only a hash change(no hash cache entry,
 
360
                    # or same size content change), or there is no change on
 
361
                    # this file at all.
 
362
                    # Provide the parent's hash to the store layer, so that the
 
363
                    # content is unchanged we will not store a new node.
 
364
                    nostore_sha = parent_entry.text_sha1
 
365
            if store:
 
366
                # We want to record a new node regardless of the presence or
 
367
                # absence of a content change in the file.
 
368
                nostore_sha = None
 
369
            ie.executable = content_summary[2]
 
370
            lines = tree.get_file(ie.file_id, path).readlines()
 
371
            try:
 
372
                ie.text_sha1, ie.text_size = self._add_text_to_weave(
 
373
                    ie.file_id, lines, heads, nostore_sha)
 
374
            except errors.ExistingContent:
 
375
                # Turns out that the file content was unchanged, and we were
 
376
                # only going to store a new node if it was changed. Carry over
 
377
                # the entry.
 
378
                ie.revision = parent_entry.revision
 
379
                ie.text_size = parent_entry.text_size
 
380
                ie.text_sha1 = parent_entry.text_sha1
 
381
                ie.executable = parent_entry.executable
 
382
                return self._get_delta(ie, basis_inv, path), False, None
 
383
        elif kind == 'directory':
 
384
            if not store:
 
385
                # all data is meta here, nothing specific to directory, so
 
386
                # carry over:
 
387
                ie.revision = parent_entry.revision
 
388
                return self._get_delta(ie, basis_inv, path), False, None
 
389
            lines = []
 
390
            self._add_text_to_weave(ie.file_id, lines, heads, None)
 
391
        elif kind == 'symlink':
 
392
            current_link_target = content_summary[3]
 
393
            if not store:
 
394
                # symlink target is not generic metadata, check if it has
 
395
                # changed.
 
396
                if current_link_target != parent_entry.symlink_target:
 
397
                    store = True
 
398
            if not store:
 
399
                # unchanged, carry over.
 
400
                ie.revision = parent_entry.revision
 
401
                ie.symlink_target = parent_entry.symlink_target
 
402
                return self._get_delta(ie, basis_inv, path), False, None
 
403
            ie.symlink_target = current_link_target
 
404
            lines = []
 
405
            self._add_text_to_weave(ie.file_id, lines, heads, None)
 
406
        elif kind == 'tree-reference':
 
407
            if not store:
 
408
                if content_summary[3] != parent_entry.reference_revision:
 
409
                    store = True
 
410
            if not store:
 
411
                # unchanged, carry over.
 
412
                ie.reference_revision = parent_entry.reference_revision
 
413
                ie.revision = parent_entry.revision
 
414
                return self._get_delta(ie, basis_inv, path), False, None
 
415
            ie.reference_revision = content_summary[3]
 
416
            lines = []
 
417
            self._add_text_to_weave(ie.file_id, lines, heads, None)
 
418
        else:
 
419
            raise NotImplementedError('unknown kind')
 
420
        ie.revision = self._new_revision_id
 
421
        return self._get_delta(ie, basis_inv, path), True, ie.text_sha1
 
422
 
 
423
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
 
424
        # Note: as we read the content directly from the tree, we know its not
 
425
        # been turned into unicode or badly split - but a broken tree
 
426
        # implementation could give us bad output from readlines() so this is
 
427
        # not a guarantee of safety. What would be better is always checking
 
428
        # the content during test suite execution. RBC 20070912
 
429
        parent_keys = tuple((file_id, parent) for parent in parents)
 
430
        return self.repository.texts.add_lines(
 
431
            (file_id, self._new_revision_id), parent_keys, new_lines,
 
432
            nostore_sha=nostore_sha, random_id=self.random_revid,
 
433
            check_content=False)[0:2]
 
434
 
 
435
 
 
436
class RootCommitBuilder(CommitBuilder):
 
437
    """This commitbuilder actually records the root id"""
 
438
    
 
439
    # the root entry gets versioned properly by this builder.
 
440
    _versioned_root = True
 
441
 
 
442
    def _check_root(self, ie, parent_invs, tree):
 
443
        """Helper for record_entry_contents.
 
444
 
 
445
        :param ie: An entry being added.
 
446
        :param parent_invs: The inventories of the parent revisions of the
 
447
            commit.
 
448
        :param tree: The tree that is being committed.
 
449
        """
 
450
 
 
451
 
 
452
######################################################################
 
453
# Repositories
 
454
 
 
455
class Repository(object):
 
456
    """Repository holding history for one or more branches.
 
457
 
 
458
    The repository holds and retrieves historical information including
 
459
    revisions and file history.  It's normally accessed only by the Branch,
 
460
    which views a particular line of development through that history.
 
461
 
 
462
    The Repository builds on top of some byte storage facilies (the revisions,
 
463
    signatures, inventories and texts attributes) and a Transport, which
 
464
    respectively provide byte storage and a means to access the (possibly
 
465
    remote) disk.
 
466
 
 
467
    The byte storage facilities are addressed via tuples, which we refer to
 
468
    as 'keys' throughout the code base. Revision_keys, inventory_keys and
 
469
    signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
 
470
    (file_id, revision_id). We use this interface because it allows low
 
471
    friction with the underlying code that implements disk indices, network
 
472
    encoding and other parts of bzrlib.
 
473
 
 
474
    :ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
 
475
        the serialised revisions for the repository. This can be used to obtain
 
476
        revision graph information or to access raw serialised revisions.
 
477
        The result of trying to insert data into the repository via this store
 
478
        is undefined: it should be considered read-only except for implementors
 
479
        of repositories.
 
480
    :ivar signatures: A bzrlib.versionedfile.VersionedFiles instance containing
 
481
        the serialised signatures for the repository. This can be used to
 
482
        obtain access to raw serialised signatures.  The result of trying to
 
483
        insert data into the repository via this store is undefined: it should
 
484
        be considered read-only except for implementors of repositories.
 
485
    :ivar inventories: A bzrlib.versionedfile.VersionedFiles instance containing
 
486
        the serialised inventories for the repository. This can be used to
 
487
        obtain unserialised inventories.  The result of trying to insert data
 
488
        into the repository via this store is undefined: it should be
 
489
        considered read-only except for implementors of repositories.
 
490
    :ivar texts: A bzrlib.versionedfile.VersionedFiles instance containing the
 
491
        texts of files and directories for the repository. This can be used to
 
492
        obtain file texts or file graphs. Note that Repository.iter_file_bytes
 
493
        is usually a better interface for accessing file texts.
 
494
        The result of trying to insert data into the repository via this store
 
495
        is undefined: it should be considered read-only except for implementors
 
496
        of repositories.
 
497
    :ivar _transport: Transport for file access to repository, typically
 
498
        pointing to .bzr/repository.
 
499
    """
 
500
 
 
501
    # What class to use for a CommitBuilder. Often its simpler to change this
 
502
    # in a Repository class subclass rather than to override
 
503
    # get_commit_builder.
 
504
    _commit_builder_class = CommitBuilder
 
505
    # The search regex used by xml based repositories to determine what things
 
506
    # where changed in a single commit.
 
507
    _file_ids_altered_regex = lazy_regex.lazy_compile(
 
508
        r'file_id="(?P<file_id>[^"]+)"'
 
509
        r'.* revision="(?P<revision_id>[^"]+)"'
 
510
        )
 
511
 
 
512
    def abort_write_group(self):
 
513
        """Commit the contents accrued within the current write group.
 
514
 
 
515
        :seealso: start_write_group.
 
516
        """
 
517
        if self._write_group is not self.get_transaction():
 
518
            # has an unlock or relock occured ?
 
519
            raise errors.BzrError('mismatched lock context and write group.')
 
520
        self._abort_write_group()
 
521
        self._write_group = None
 
522
 
 
523
    def _abort_write_group(self):
 
524
        """Template method for per-repository write group cleanup.
 
525
        
 
526
        This is called during abort before the write group is considered to be 
 
527
        finished and should cleanup any internal state accrued during the write
 
528
        group. There is no requirement that data handed to the repository be
 
529
        *not* made available - this is not a rollback - but neither should any
 
530
        attempt be made to ensure that data added is fully commited. Abort is
 
531
        invoked when an error has occured so futher disk or network operations
 
532
        may not be possible or may error and if possible should not be
 
533
        attempted.
 
534
        """
 
535
 
 
536
    def add_fallback_repository(self, repository):
 
537
        """Add a repository to use for looking up data not held locally.
 
538
        
 
539
        :param repository: A repository.
 
540
        """
 
541
        if not self._format.supports_external_lookups:
 
542
            raise errors.UnstackableRepositoryFormat(self._format, self.base)
 
543
        self._check_fallback_repository(repository)
 
544
        self._fallback_repositories.append(repository)
 
545
        self.texts.add_fallback_versioned_files(repository.texts)
 
546
        self.inventories.add_fallback_versioned_files(repository.inventories)
 
547
        self.revisions.add_fallback_versioned_files(repository.revisions)
 
548
        self.signatures.add_fallback_versioned_files(repository.signatures)
 
549
 
 
550
    def _check_fallback_repository(self, repository):
 
551
        """Check that this repository can fallback to repository safely.
 
552
 
 
553
        Raise an error if not.
 
554
        
 
555
        :param repository: A repository to fallback to.
 
556
        """
 
557
        return InterRepository._assert_same_model(self, repository)
 
558
 
 
559
    def add_inventory(self, revision_id, inv, parents):
 
560
        """Add the inventory inv to the repository as revision_id.
 
561
        
 
562
        :param parents: The revision ids of the parents that revision_id
 
563
                        is known to have and are in the repository already.
 
564
 
 
565
        :returns: The validator(which is a sha1 digest, though what is sha'd is
 
566
            repository format specific) of the serialized inventory.
 
567
        """
 
568
        if not self.is_in_write_group():
 
569
            raise AssertionError("%r not in write group" % (self,))
 
570
        _mod_revision.check_not_reserved_id(revision_id)
 
571
        if not (inv.revision_id is None or inv.revision_id == revision_id):
 
572
            raise AssertionError(
 
573
                "Mismatch between inventory revision"
 
574
                " id and insertion revid (%r, %r)"
 
575
                % (inv.revision_id, revision_id))
 
576
        if inv.root is None:
 
577
            raise AssertionError()
 
578
        inv_lines = self._serialise_inventory_to_lines(inv)
 
579
        return self._inventory_add_lines(revision_id, parents,
 
580
            inv_lines, check_content=False)
 
581
 
 
582
    def _inventory_add_lines(self, revision_id, parents, lines,
 
583
        check_content=True):
 
584
        """Store lines in inv_vf and return the sha1 of the inventory."""
 
585
        parents = [(parent,) for parent in parents]
 
586
        return self.inventories.add_lines((revision_id,), parents, lines,
 
587
            check_content=check_content)[0]
 
588
 
 
589
    def add_revision(self, revision_id, rev, inv=None, config=None):
 
590
        """Add rev to the revision store as revision_id.
 
591
 
 
592
        :param revision_id: the revision id to use.
 
593
        :param rev: The revision object.
 
594
        :param inv: The inventory for the revision. if None, it will be looked
 
595
                    up in the inventory storer
 
596
        :param config: If None no digital signature will be created.
 
597
                       If supplied its signature_needed method will be used
 
598
                       to determine if a signature should be made.
 
599
        """
 
600
        # TODO: jam 20070210 Shouldn't we check rev.revision_id and
 
601
        #       rev.parent_ids?
 
602
        _mod_revision.check_not_reserved_id(revision_id)
 
603
        if config is not None and config.signature_needed():
 
604
            if inv is None:
 
605
                inv = self.get_inventory(revision_id)
 
606
            plaintext = Testament(rev, inv).as_short_text()
 
607
            self.store_revision_signature(
 
608
                gpg.GPGStrategy(config), plaintext, revision_id)
 
609
        # check inventory present
 
610
        if not self.inventories.get_parent_map([(revision_id,)]):
 
611
            if inv is None:
 
612
                raise errors.WeaveRevisionNotPresent(revision_id,
 
613
                                                     self.inventories)
 
614
            else:
 
615
                # yes, this is not suitable for adding with ghosts.
 
616
                rev.inventory_sha1 = self.add_inventory(revision_id, inv,
 
617
                                                        rev.parent_ids)
 
618
        else:
 
619
            key = (revision_id,)
 
620
            rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
 
621
        self._add_revision(rev)
 
622
 
 
623
    def _add_revision(self, revision):
 
624
        text = self._serializer.write_revision_to_string(revision)
 
625
        key = (revision.revision_id,)
 
626
        parents = tuple((parent,) for parent in revision.parent_ids)
 
627
        self.revisions.add_lines(key, parents, osutils.split_lines(text))
 
628
 
 
629
    def all_revision_ids(self):
 
630
        """Returns a list of all the revision ids in the repository. 
 
631
 
 
632
        This is conceptually deprecated because code should generally work on
 
633
        the graph reachable from a particular revision, and ignore any other
 
634
        revisions that might be present.  There is no direct replacement
 
635
        method.
 
636
        """
 
637
        if 'evil' in debug.debug_flags:
 
638
            mutter_callsite(2, "all_revision_ids is linear with history.")
 
639
        return self._all_revision_ids()
 
640
 
 
641
    def _all_revision_ids(self):
 
642
        """Returns a list of all the revision ids in the repository. 
 
643
 
 
644
        These are in as much topological order as the underlying store can 
 
645
        present.
 
646
        """
 
647
        raise NotImplementedError(self._all_revision_ids)
 
648
 
 
649
    def break_lock(self):
 
650
        """Break a lock if one is present from another instance.
 
651
 
 
652
        Uses the ui factory to ask for confirmation if the lock may be from
 
653
        an active process.
 
654
        """
 
655
        self.control_files.break_lock()
 
656
 
 
657
    @needs_read_lock
 
658
    def _eliminate_revisions_not_present(self, revision_ids):
 
659
        """Check every revision id in revision_ids to see if we have it.
 
660
 
 
661
        Returns a set of the present revisions.
 
662
        """
 
663
        result = []
 
664
        graph = self.get_graph()
 
665
        parent_map = graph.get_parent_map(revision_ids)
 
666
        # The old API returned a list, should this actually be a set?
 
667
        return parent_map.keys()
 
668
 
 
669
    @staticmethod
 
670
    def create(a_bzrdir):
 
671
        """Construct the current default format repository in a_bzrdir."""
 
672
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
 
673
 
 
674
    def __init__(self, _format, a_bzrdir, control_files):
 
675
        """instantiate a Repository.
 
676
 
 
677
        :param _format: The format of the repository on disk.
 
678
        :param a_bzrdir: The BzrDir of the repository.
 
679
 
 
680
        In the future we will have a single api for all stores for
 
681
        getting file texts, inventories and revisions, then
 
682
        this construct will accept instances of those things.
 
683
        """
 
684
        super(Repository, self).__init__()
 
685
        self._format = _format
 
686
        # the following are part of the public API for Repository:
 
687
        self.bzrdir = a_bzrdir
 
688
        self.control_files = control_files
 
689
        self._transport = control_files._transport
 
690
        self.base = self._transport.base
 
691
        # for tests
 
692
        self._reconcile_does_inventory_gc = True
 
693
        self._reconcile_fixes_text_parents = False
 
694
        self._reconcile_backsup_inventory = True
 
695
        # not right yet - should be more semantically clear ? 
 
696
        # 
 
697
        # TODO: make sure to construct the right store classes, etc, depending
 
698
        # on whether escaping is required.
 
699
        self._warn_if_deprecated()
 
700
        self._write_group = None
 
701
        # Additional places to query for data.
 
702
        self._fallback_repositories = []
 
703
        # What order should fetch operations request streams in?
 
704
        # The default is unordered as that is the cheapest for an origin to
 
705
        # provide.
 
706
        self._fetch_order = 'unordered'
 
707
        # Does this repository use deltas that can be fetched as-deltas ?
 
708
        # (E.g. knits, where the knit deltas can be transplanted intact.
 
709
        # We default to False, which will ensure that enough data to get
 
710
        # a full text out of any fetch stream will be grabbed.
 
711
        self._fetch_uses_deltas = False
 
712
        # Should fetch trigger a reconcile after the fetch? Only needed for
 
713
        # some repository formats that can suffer internal inconsistencies.
 
714
        self._fetch_reconcile = False
 
715
 
 
716
    def __repr__(self):
 
717
        return '%s(%r)' % (self.__class__.__name__,
 
718
                           self.base)
 
719
 
 
720
    def has_same_location(self, other):
 
721
        """Returns a boolean indicating if this repository is at the same
 
722
        location as another repository.
 
723
 
 
724
        This might return False even when two repository objects are accessing
 
725
        the same physical repository via different URLs.
 
726
        """
 
727
        if self.__class__ is not other.__class__:
 
728
            return False
 
729
        return (self._transport.base == other._transport.base)
 
730
 
 
731
    def is_in_write_group(self):
 
732
        """Return True if there is an open write group.
 
733
 
 
734
        :seealso: start_write_group.
 
735
        """
 
736
        return self._write_group is not None
 
737
 
 
738
    def is_locked(self):
 
739
        return self.control_files.is_locked()
 
740
 
 
741
    def is_write_locked(self):
 
742
        """Return True if this object is write locked."""
 
743
        return self.is_locked() and self.control_files._lock_mode == 'w'
 
744
 
 
745
    def lock_write(self, token=None):
 
746
        """Lock this repository for writing.
 
747
 
 
748
        This causes caching within the repository obejct to start accumlating
 
749
        data during reads, and allows a 'write_group' to be obtained. Write
 
750
        groups must be used for actual data insertion.
 
751
        
 
752
        :param token: if this is already locked, then lock_write will fail
 
753
            unless the token matches the existing lock.
 
754
        :returns: a token if this instance supports tokens, otherwise None.
 
755
        :raises TokenLockingNotSupported: when a token is given but this
 
756
            instance doesn't support using token locks.
 
757
        :raises MismatchedToken: if the specified token doesn't match the token
 
758
            of the existing lock.
 
759
        :seealso: start_write_group.
 
760
 
 
761
        A token should be passed in if you know that you have locked the object
 
762
        some other way, and need to synchronise this object's state with that
 
763
        fact.
 
764
 
 
765
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
 
766
        """
 
767
        result = self.control_files.lock_write(token=token)
 
768
        for repo in self._fallback_repositories:
 
769
            # Writes don't affect fallback repos
 
770
            repo.lock_read()
 
771
        self._refresh_data()
 
772
        return result
 
773
 
 
774
    def lock_read(self):
 
775
        self.control_files.lock_read()
 
776
        for repo in self._fallback_repositories:
 
777
            repo.lock_read()
 
778
        self._refresh_data()
 
779
 
 
780
    def get_physical_lock_status(self):
 
781
        return self.control_files.get_physical_lock_status()
 
782
 
 
783
    def leave_lock_in_place(self):
 
784
        """Tell this repository not to release the physical lock when this
 
785
        object is unlocked.
 
786
        
 
787
        If lock_write doesn't return a token, then this method is not supported.
 
788
        """
 
789
        self.control_files.leave_in_place()
 
790
 
 
791
    def dont_leave_lock_in_place(self):
 
792
        """Tell this repository to release the physical lock when this
 
793
        object is unlocked, even if it didn't originally acquire it.
 
794
 
 
795
        If lock_write doesn't return a token, then this method is not supported.
 
796
        """
 
797
        self.control_files.dont_leave_in_place()
 
798
 
 
799
    @needs_read_lock
 
800
    def gather_stats(self, revid=None, committers=None):
 
801
        """Gather statistics from a revision id.
 
802
 
 
803
        :param revid: The revision id to gather statistics from, if None, then
 
804
            no revision specific statistics are gathered.
 
805
        :param committers: Optional parameter controlling whether to grab
 
806
            a count of committers from the revision specific statistics.
 
807
        :return: A dictionary of statistics. Currently this contains:
 
808
            committers: The number of committers if requested.
 
809
            firstrev: A tuple with timestamp, timezone for the penultimate left
 
810
                most ancestor of revid, if revid is not the NULL_REVISION.
 
811
            latestrev: A tuple with timestamp, timezone for revid, if revid is
 
812
                not the NULL_REVISION.
 
813
            revisions: The total revision count in the repository.
 
814
            size: An estimate disk size of the repository in bytes.
 
815
        """
 
816
        result = {}
 
817
        if revid and committers:
 
818
            result['committers'] = 0
 
819
        if revid and revid != _mod_revision.NULL_REVISION:
 
820
            if committers:
 
821
                all_committers = set()
 
822
            revisions = self.get_ancestry(revid)
 
823
            # pop the leading None
 
824
            revisions.pop(0)
 
825
            first_revision = None
 
826
            if not committers:
 
827
                # ignore the revisions in the middle - just grab first and last
 
828
                revisions = revisions[0], revisions[-1]
 
829
            for revision in self.get_revisions(revisions):
 
830
                if not first_revision:
 
831
                    first_revision = revision
 
832
                if committers:
 
833
                    all_committers.add(revision.committer)
 
834
            last_revision = revision
 
835
            if committers:
 
836
                result['committers'] = len(all_committers)
 
837
            result['firstrev'] = (first_revision.timestamp,
 
838
                first_revision.timezone)
 
839
            result['latestrev'] = (last_revision.timestamp,
 
840
                last_revision.timezone)
 
841
 
 
842
        # now gather global repository information
 
843
        # XXX: This is available for many repos regardless of listability.
 
844
        if self.bzrdir.root_transport.listable():
 
845
            # XXX: do we want to __define len__() ?
 
846
            # Maybe the versionedfiles object should provide a different
 
847
            # method to get the number of keys.
 
848
            result['revisions'] = len(self.revisions.keys())
 
849
            # result['size'] = t
 
850
        return result
 
851
 
 
852
    def find_branches(self, using=False):
 
853
        """Find branches underneath this repository.
 
854
 
 
855
        This will include branches inside other branches.
 
856
 
 
857
        :param using: If True, list only branches using this repository.
 
858
        """
 
859
        if using and not self.is_shared():
 
860
            try:
 
861
                return [self.bzrdir.open_branch()]
 
862
            except errors.NotBranchError:
 
863
                return []
 
864
        class Evaluator(object):
 
865
 
 
866
            def __init__(self):
 
867
                self.first_call = True
 
868
 
 
869
            def __call__(self, bzrdir):
 
870
                # On the first call, the parameter is always the bzrdir
 
871
                # containing the current repo.
 
872
                if not self.first_call:
 
873
                    try:
 
874
                        repository = bzrdir.open_repository()
 
875
                    except errors.NoRepositoryPresent:
 
876
                        pass
 
877
                    else:
 
878
                        return False, (None, repository)
 
879
                self.first_call = False
 
880
                try:
 
881
                    value = (bzrdir.open_branch(), None)
 
882
                except errors.NotBranchError:
 
883
                    value = (None, None)
 
884
                return True, value
 
885
 
 
886
        branches = []
 
887
        for branch, repository in bzrdir.BzrDir.find_bzrdirs(
 
888
                self.bzrdir.root_transport, evaluate=Evaluator()):
 
889
            if branch is not None:
 
890
                branches.append(branch)
 
891
            if not using and repository is not None:
 
892
                branches.extend(repository.find_branches())
 
893
        return branches
 
894
 
 
895
    @needs_read_lock
 
896
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
 
897
        """Return the revision ids that other has that this does not.
 
898
        
 
899
        These are returned in topological order.
 
900
 
 
901
        revision_id: only return revision ids included by revision_id.
 
902
        """
 
903
        return InterRepository.get(other, self).search_missing_revision_ids(
 
904
            revision_id, find_ghosts)
 
905
 
 
906
    @deprecated_method(one_two)
 
907
    @needs_read_lock
 
908
    def missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
 
909
        """Return the revision ids that other has that this does not.
 
910
        
 
911
        These are returned in topological order.
 
912
 
 
913
        revision_id: only return revision ids included by revision_id.
 
914
        """
 
915
        keys =  self.search_missing_revision_ids(
 
916
            other, revision_id, find_ghosts).get_keys()
 
917
        other.lock_read()
 
918
        try:
 
919
            parents = other.get_graph().get_parent_map(keys)
 
920
        finally:
 
921
            other.unlock()
 
922
        return tsort.topo_sort(parents)
 
923
 
 
924
    @staticmethod
 
925
    def open(base):
 
926
        """Open the repository rooted at base.
 
927
 
 
928
        For instance, if the repository is at URL/.bzr/repository,
 
929
        Repository.open(URL) -> a Repository instance.
 
930
        """
 
931
        control = bzrdir.BzrDir.open(base)
 
932
        return control.open_repository()
 
933
 
 
934
    def copy_content_into(self, destination, revision_id=None):
 
935
        """Make a complete copy of the content in self into destination.
 
936
        
 
937
        This is a destructive operation! Do not use it on existing 
 
938
        repositories.
 
939
        """
 
940
        return InterRepository.get(self, destination).copy_content(revision_id)
 
941
 
 
942
    def commit_write_group(self):
 
943
        """Commit the contents accrued within the current write group.
 
944
 
 
945
        :seealso: start_write_group.
 
946
        """
 
947
        if self._write_group is not self.get_transaction():
 
948
            # has an unlock or relock occured ?
 
949
            raise errors.BzrError('mismatched lock context %r and '
 
950
                'write group %r.' %
 
951
                (self.get_transaction(), self._write_group))
 
952
        self._commit_write_group()
 
953
        self._write_group = None
 
954
 
 
955
    def _commit_write_group(self):
 
956
        """Template method for per-repository write group cleanup.
 
957
        
 
958
        This is called before the write group is considered to be 
 
959
        finished and should ensure that all data handed to the repository
 
960
        for writing during the write group is safely committed (to the 
 
961
        extent possible considering file system caching etc).
 
962
        """
 
963
 
 
964
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
 
965
        """Fetch the content required to construct revision_id from source.
 
966
 
 
967
        If revision_id is None all content is copied.
 
968
        :param find_ghosts: Find and copy revisions in the source that are
 
969
            ghosts in the target (and not reachable directly by walking out to
 
970
            the first-present revision in target from revision_id).
 
971
        """
 
972
        # fast path same-url fetch operations
 
973
        if self.has_same_location(source):
 
974
            # check that last_revision is in 'from' and then return a
 
975
            # no-operation.
 
976
            if (revision_id is not None and
 
977
                not _mod_revision.is_null(revision_id)):
 
978
                self.get_revision(revision_id)
 
979
            return 0, []
 
980
        # if there is no specific appropriate InterRepository, this will get
 
981
        # the InterRepository base class, which raises an
 
982
        # IncompatibleRepositories when asked to fetch.
 
983
        inter = InterRepository.get(source, self)
 
984
        return inter.fetch(revision_id=revision_id, pb=pb,
 
985
            find_ghosts=find_ghosts)
 
986
 
 
987
    def create_bundle(self, target, base, fileobj, format=None):
 
988
        return serializer.write_bundle(self, target, base, fileobj, format)
 
989
 
 
990
    def get_commit_builder(self, branch, parents, config, timestamp=None,
 
991
                           timezone=None, committer=None, revprops=None,
 
992
                           revision_id=None):
 
993
        """Obtain a CommitBuilder for this repository.
 
994
        
 
995
        :param branch: Branch to commit to.
 
996
        :param parents: Revision ids of the parents of the new revision.
 
997
        :param config: Configuration to use.
 
998
        :param timestamp: Optional timestamp recorded for commit.
 
999
        :param timezone: Optional timezone for timestamp.
 
1000
        :param committer: Optional committer to set for commit.
 
1001
        :param revprops: Optional dictionary of revision properties.
 
1002
        :param revision_id: Optional revision id.
 
1003
        """
 
1004
        result = self._commit_builder_class(self, parents, config,
 
1005
            timestamp, timezone, committer, revprops, revision_id)
 
1006
        self.start_write_group()
 
1007
        return result
 
1008
 
 
1009
    def unlock(self):
 
1010
        if (self.control_files._lock_count == 1 and
 
1011
            self.control_files._lock_mode == 'w'):
 
1012
            if self._write_group is not None:
 
1013
                self.abort_write_group()
 
1014
                self.control_files.unlock()
 
1015
                raise errors.BzrError(
 
1016
                    'Must end write groups before releasing write locks.')
 
1017
        self.control_files.unlock()
 
1018
        for repo in self._fallback_repositories:
 
1019
            repo.unlock()
 
1020
 
 
1021
    @needs_read_lock
 
1022
    def clone(self, a_bzrdir, revision_id=None):
 
1023
        """Clone this repository into a_bzrdir using the current format.
 
1024
 
 
1025
        Currently no check is made that the format of this repository and
 
1026
        the bzrdir format are compatible. FIXME RBC 20060201.
 
1027
 
 
1028
        :return: The newly created destination repository.
 
1029
        """
 
1030
        # TODO: deprecate after 0.16; cloning this with all its settings is
 
1031
        # probably not very useful -- mbp 20070423
 
1032
        dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
 
1033
        self.copy_content_into(dest_repo, revision_id)
 
1034
        return dest_repo
 
1035
 
 
1036
    def start_write_group(self):
 
1037
        """Start a write group in the repository.
 
1038
 
 
1039
        Write groups are used by repositories which do not have a 1:1 mapping
 
1040
        between file ids and backend store to manage the insertion of data from
 
1041
        both fetch and commit operations.
 
1042
 
 
1043
        A write lock is required around the start_write_group/commit_write_group
 
1044
        for the support of lock-requiring repository formats.
 
1045
 
 
1046
        One can only insert data into a repository inside a write group.
 
1047
 
 
1048
        :return: None.
 
1049
        """
 
1050
        if not self.is_write_locked():
 
1051
            raise errors.NotWriteLocked(self)
 
1052
        if self._write_group:
 
1053
            raise errors.BzrError('already in a write group')
 
1054
        self._start_write_group()
 
1055
        # so we can detect unlock/relock - the write group is now entered.
 
1056
        self._write_group = self.get_transaction()
 
1057
 
 
1058
    def _start_write_group(self):
 
1059
        """Template method for per-repository write group startup.
 
1060
        
 
1061
        This is called before the write group is considered to be 
 
1062
        entered.
 
1063
        """
 
1064
 
 
1065
    @needs_read_lock
 
1066
    def sprout(self, to_bzrdir, revision_id=None):
 
1067
        """Create a descendent repository for new development.
 
1068
 
 
1069
        Unlike clone, this does not copy the settings of the repository.
 
1070
        """
 
1071
        dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
 
1072
        dest_repo.fetch(self, revision_id=revision_id)
 
1073
        return dest_repo
 
1074
 
 
1075
    def _create_sprouting_repo(self, a_bzrdir, shared):
 
1076
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
 
1077
            # use target default format.
 
1078
            dest_repo = a_bzrdir.create_repository()
 
1079
        else:
 
1080
            # Most control formats need the repository to be specifically
 
1081
            # created, but on some old all-in-one formats it's not needed
 
1082
            try:
 
1083
                dest_repo = self._format.initialize(a_bzrdir, shared=shared)
 
1084
            except errors.UninitializableFormat:
 
1085
                dest_repo = a_bzrdir.open_repository()
 
1086
        return dest_repo
 
1087
 
 
1088
    @needs_read_lock
 
1089
    def has_revision(self, revision_id):
 
1090
        """True if this repository has a copy of the revision."""
 
1091
        return revision_id in self.has_revisions((revision_id,))
 
1092
 
 
1093
    @needs_read_lock
 
1094
    def has_revisions(self, revision_ids):
 
1095
        """Probe to find out the presence of multiple revisions.
 
1096
 
 
1097
        :param revision_ids: An iterable of revision_ids.
 
1098
        :return: A set of the revision_ids that were present.
 
1099
        """
 
1100
        parent_map = self.revisions.get_parent_map(
 
1101
            [(rev_id,) for rev_id in revision_ids])
 
1102
        result = set()
 
1103
        if _mod_revision.NULL_REVISION in revision_ids:
 
1104
            result.add(_mod_revision.NULL_REVISION)
 
1105
        result.update([key[0] for key in parent_map])
 
1106
        return result
 
1107
 
 
1108
    @needs_read_lock
 
1109
    def get_revision(self, revision_id):
 
1110
        """Return the Revision object for a named revision."""
 
1111
        return self.get_revisions([revision_id])[0]
 
1112
 
 
1113
    @needs_read_lock
 
1114
    def get_revision_reconcile(self, revision_id):
 
1115
        """'reconcile' helper routine that allows access to a revision always.
 
1116
        
 
1117
        This variant of get_revision does not cross check the weave graph
 
1118
        against the revision one as get_revision does: but it should only
 
1119
        be used by reconcile, or reconcile-alike commands that are correcting
 
1120
        or testing the revision graph.
 
1121
        """
 
1122
        return self._get_revisions([revision_id])[0]
 
1123
 
 
1124
    @needs_read_lock
 
1125
    def get_revisions(self, revision_ids):
 
1126
        """Get many revisions at once."""
 
1127
        return self._get_revisions(revision_ids)
 
1128
 
 
1129
    @needs_read_lock
 
1130
    def _get_revisions(self, revision_ids):
 
1131
        """Core work logic to get many revisions without sanity checks."""
 
1132
        for rev_id in revision_ids:
 
1133
            if not rev_id or not isinstance(rev_id, basestring):
 
1134
                raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
 
1135
        keys = [(key,) for key in revision_ids]
 
1136
        stream = self.revisions.get_record_stream(keys, 'unordered', True)
 
1137
        revs = {}
 
1138
        for record in stream:
 
1139
            if record.storage_kind == 'absent':
 
1140
                raise errors.NoSuchRevision(self, record.key[0])
 
1141
            text = record.get_bytes_as('fulltext')
 
1142
            rev = self._serializer.read_revision_from_string(text)
 
1143
            revs[record.key[0]] = rev
 
1144
        return [revs[revid] for revid in revision_ids]
 
1145
 
 
1146
    @needs_read_lock
 
1147
    def get_revision_xml(self, revision_id):
 
1148
        # TODO: jam 20070210 This shouldn't be necessary since get_revision
 
1149
        #       would have already do it.
 
1150
        # TODO: jam 20070210 Just use _serializer.write_revision_to_string()
 
1151
        rev = self.get_revision(revision_id)
 
1152
        rev_tmp = StringIO()
 
1153
        # the current serializer..
 
1154
        self._serializer.write_revision(rev, rev_tmp)
 
1155
        rev_tmp.seek(0)
 
1156
        return rev_tmp.getvalue()
 
1157
 
 
1158
    def get_deltas_for_revisions(self, revisions):
 
1159
        """Produce a generator of revision deltas.
 
1160
        
 
1161
        Note that the input is a sequence of REVISIONS, not revision_ids.
 
1162
        Trees will be held in memory until the generator exits.
 
1163
        Each delta is relative to the revision's lefthand predecessor.
 
1164
        """
 
1165
        required_trees = set()
 
1166
        for revision in revisions:
 
1167
            required_trees.add(revision.revision_id)
 
1168
            required_trees.update(revision.parent_ids[:1])
 
1169
        trees = dict((t.get_revision_id(), t) for 
 
1170
                     t in self.revision_trees(required_trees))
 
1171
        for revision in revisions:
 
1172
            if not revision.parent_ids:
 
1173
                old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
 
1174
            else:
 
1175
                old_tree = trees[revision.parent_ids[0]]
 
1176
            yield trees[revision.revision_id].changes_from(old_tree)
 
1177
 
 
1178
    @needs_read_lock
 
1179
    def get_revision_delta(self, revision_id):
 
1180
        """Return the delta for one revision.
 
1181
 
 
1182
        The delta is relative to the left-hand predecessor of the
 
1183
        revision.
 
1184
        """
 
1185
        r = self.get_revision(revision_id)
 
1186
        return list(self.get_deltas_for_revisions([r]))[0]
 
1187
 
 
1188
    @needs_write_lock
 
1189
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
1190
        signature = gpg_strategy.sign(plaintext)
 
1191
        self.add_signature_text(revision_id, signature)
 
1192
 
 
1193
    @needs_write_lock
 
1194
    def add_signature_text(self, revision_id, signature):
 
1195
        self.signatures.add_lines((revision_id,), (),
 
1196
            osutils.split_lines(signature))
 
1197
 
 
1198
    def find_text_key_references(self):
 
1199
        """Find the text key references within the repository.
 
1200
 
 
1201
        :return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
 
1202
        revision_ids. Each altered file-ids has the exact revision_ids that
 
1203
        altered it listed explicitly.
 
1204
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
 
1205
            to whether they were referred to by the inventory of the
 
1206
            revision_id that they contain. The inventory texts from all present
 
1207
            revision ids are assessed to generate this report.
 
1208
        """
 
1209
        revision_keys = self.revisions.keys()
 
1210
        w = self.inventories
 
1211
        pb = ui.ui_factory.nested_progress_bar()
 
1212
        try:
 
1213
            return self._find_text_key_references_from_xml_inventory_lines(
 
1214
                w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
 
1215
        finally:
 
1216
            pb.finished()
 
1217
 
 
1218
    def _find_text_key_references_from_xml_inventory_lines(self,
 
1219
        line_iterator):
 
1220
        """Core routine for extracting references to texts from inventories.
 
1221
 
 
1222
        This performs the translation of xml lines to revision ids.
 
1223
 
 
1224
        :param line_iterator: An iterator of lines, origin_version_id
 
1225
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
 
1226
            to whether they were referred to by the inventory of the
 
1227
            revision_id that they contain. Note that if that revision_id was
 
1228
            not part of the line_iterator's output then False will be given -
 
1229
            even though it may actually refer to that key.
 
1230
        """
 
1231
        if not self._serializer.support_altered_by_hack:
 
1232
            raise AssertionError(
 
1233
                "_find_text_key_references_from_xml_inventory_lines only "
 
1234
                "supported for branches which store inventory as unnested xml"
 
1235
                ", not on %r" % self)
 
1236
        result = {}
 
1237
 
 
1238
        # this code needs to read every new line in every inventory for the
 
1239
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
 
1240
        # not present in one of those inventories is unnecessary but not 
 
1241
        # harmful because we are filtering by the revision id marker in the
 
1242
        # inventory lines : we only select file ids altered in one of those  
 
1243
        # revisions. We don't need to see all lines in the inventory because
 
1244
        # only those added in an inventory in rev X can contain a revision=X
 
1245
        # line.
 
1246
        unescape_revid_cache = {}
 
1247
        unescape_fileid_cache = {}
 
1248
 
 
1249
        # jam 20061218 In a big fetch, this handles hundreds of thousands
 
1250
        # of lines, so it has had a lot of inlining and optimizing done.
 
1251
        # Sorry that it is a little bit messy.
 
1252
        # Move several functions to be local variables, since this is a long
 
1253
        # running loop.
 
1254
        search = self._file_ids_altered_regex.search
 
1255
        unescape = _unescape_xml
 
1256
        setdefault = result.setdefault
 
1257
        for line, line_key in line_iterator:
 
1258
            match = search(line)
 
1259
            if match is None:
 
1260
                continue
 
1261
            # One call to match.group() returning multiple items is quite a
 
1262
            # bit faster than 2 calls to match.group() each returning 1
 
1263
            file_id, revision_id = match.group('file_id', 'revision_id')
 
1264
 
 
1265
            # Inlining the cache lookups helps a lot when you make 170,000
 
1266
            # lines and 350k ids, versus 8.4 unique ids.
 
1267
            # Using a cache helps in 2 ways:
 
1268
            #   1) Avoids unnecessary decoding calls
 
1269
            #   2) Re-uses cached strings, which helps in future set and
 
1270
            #      equality checks.
 
1271
            # (2) is enough that removing encoding entirely along with
 
1272
            # the cache (so we are using plain strings) results in no
 
1273
            # performance improvement.
 
1274
            try:
 
1275
                revision_id = unescape_revid_cache[revision_id]
 
1276
            except KeyError:
 
1277
                unescaped = unescape(revision_id)
 
1278
                unescape_revid_cache[revision_id] = unescaped
 
1279
                revision_id = unescaped
 
1280
 
 
1281
            # Note that unconditionally unescaping means that we deserialise
 
1282
            # every fileid, which for general 'pull' is not great, but we don't
 
1283
            # really want to have some many fulltexts that this matters anyway.
 
1284
            # RBC 20071114.
 
1285
            try:
 
1286
                file_id = unescape_fileid_cache[file_id]
 
1287
            except KeyError:
 
1288
                unescaped = unescape(file_id)
 
1289
                unescape_fileid_cache[file_id] = unescaped
 
1290
                file_id = unescaped
 
1291
 
 
1292
            key = (file_id, revision_id)
 
1293
            setdefault(key, False)
 
1294
            if revision_id == line_key[-1]:
 
1295
                result[key] = True
 
1296
        return result
 
1297
 
 
1298
    def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
 
1299
        revision_ids):
 
1300
        """Helper routine for fileids_altered_by_revision_ids.
 
1301
 
 
1302
        This performs the translation of xml lines to revision ids.
 
1303
 
 
1304
        :param line_iterator: An iterator of lines, origin_version_id
 
1305
        :param revision_ids: The revision ids to filter for. This should be a
 
1306
            set or other type which supports efficient __contains__ lookups, as
 
1307
            the revision id from each parsed line will be looked up in the
 
1308
            revision_ids filter.
 
1309
        :return: a dictionary mapping altered file-ids to an iterable of
 
1310
        revision_ids. Each altered file-ids has the exact revision_ids that
 
1311
        altered it listed explicitly.
 
1312
        """
 
1313
        result = {}
 
1314
        setdefault = result.setdefault
 
1315
        for key in \
 
1316
            self._find_text_key_references_from_xml_inventory_lines(
 
1317
                line_iterator).iterkeys():
 
1318
            # once data is all ensured-consistent; then this is
 
1319
            # if revision_id == version_id
 
1320
            if key[-1:] in revision_ids:
 
1321
                setdefault(key[0], set()).add(key[-1])
 
1322
        return result
 
1323
 
 
1324
    def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
 
1325
        """Find the file ids and versions affected by revisions.
 
1326
 
 
1327
        :param revisions: an iterable containing revision ids.
 
1328
        :param _inv_weave: The inventory weave from this repository or None.
 
1329
            If None, the inventory weave will be opened automatically.
 
1330
        :return: a dictionary mapping altered file-ids to an iterable of
 
1331
        revision_ids. Each altered file-ids has the exact revision_ids that
 
1332
        altered it listed explicitly.
 
1333
        """
 
1334
        selected_keys = set((revid,) for revid in revision_ids)
 
1335
        w = _inv_weave or self.inventories
 
1336
        pb = ui.ui_factory.nested_progress_bar()
 
1337
        try:
 
1338
            return self._find_file_ids_from_xml_inventory_lines(
 
1339
                w.iter_lines_added_or_present_in_keys(
 
1340
                    selected_keys, pb=pb),
 
1341
                selected_keys)
 
1342
        finally:
 
1343
            pb.finished()
 
1344
 
 
1345
    def iter_files_bytes(self, desired_files):
 
1346
        """Iterate through file versions.
 
1347
 
 
1348
        Files will not necessarily be returned in the order they occur in
 
1349
        desired_files.  No specific order is guaranteed.
 
1350
 
 
1351
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
 
1352
        value supplied by the caller as part of desired_files.  It should
 
1353
        uniquely identify the file version in the caller's context.  (Examples:
 
1354
        an index number or a TreeTransform trans_id.)
 
1355
 
 
1356
        bytes_iterator is an iterable of bytestrings for the file.  The
 
1357
        kind of iterable and length of the bytestrings are unspecified, but for
 
1358
        this implementation, it is a list of bytes produced by
 
1359
        VersionedFile.get_record_stream().
 
1360
 
 
1361
        :param desired_files: a list of (file_id, revision_id, identifier)
 
1362
            triples
 
1363
        """
 
1364
        transaction = self.get_transaction()
 
1365
        text_keys = {}
 
1366
        for file_id, revision_id, callable_data in desired_files:
 
1367
            text_keys[(file_id, revision_id)] = callable_data
 
1368
        for record in self.texts.get_record_stream(text_keys, 'unordered', True):
 
1369
            if record.storage_kind == 'absent':
 
1370
                raise errors.RevisionNotPresent(record.key, self)
 
1371
            yield text_keys[record.key], record.get_bytes_as('fulltext')
 
1372
 
 
1373
    def _generate_text_key_index(self, text_key_references=None,
 
1374
        ancestors=None):
 
1375
        """Generate a new text key index for the repository.
 
1376
 
 
1377
        This is an expensive function that will take considerable time to run.
 
1378
 
 
1379
        :return: A dict mapping text keys ((file_id, revision_id) tuples) to a
 
1380
            list of parents, also text keys. When a given key has no parents,
 
1381
            the parents list will be [NULL_REVISION].
 
1382
        """
 
1383
        # All revisions, to find inventory parents.
 
1384
        if ancestors is None:
 
1385
            graph = self.get_graph()
 
1386
            ancestors = graph.get_parent_map(self.all_revision_ids())
 
1387
        if text_key_references is None:
 
1388
            text_key_references = self.find_text_key_references()
 
1389
        pb = ui.ui_factory.nested_progress_bar()
 
1390
        try:
 
1391
            return self._do_generate_text_key_index(ancestors,
 
1392
                text_key_references, pb)
 
1393
        finally:
 
1394
            pb.finished()
 
1395
 
 
1396
    def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
 
1397
        """Helper for _generate_text_key_index to avoid deep nesting."""
 
1398
        revision_order = tsort.topo_sort(ancestors)
 
1399
        invalid_keys = set()
 
1400
        revision_keys = {}
 
1401
        for revision_id in revision_order:
 
1402
            revision_keys[revision_id] = set()
 
1403
        text_count = len(text_key_references)
 
1404
        # a cache of the text keys to allow reuse; costs a dict of all the
 
1405
        # keys, but saves a 2-tuple for every child of a given key.
 
1406
        text_key_cache = {}
 
1407
        for text_key, valid in text_key_references.iteritems():
 
1408
            if not valid:
 
1409
                invalid_keys.add(text_key)
 
1410
            else:
 
1411
                revision_keys[text_key[1]].add(text_key)
 
1412
            text_key_cache[text_key] = text_key
 
1413
        del text_key_references
 
1414
        text_index = {}
 
1415
        text_graph = graph.Graph(graph.DictParentsProvider(text_index))
 
1416
        NULL_REVISION = _mod_revision.NULL_REVISION
 
1417
        # Set a cache with a size of 10 - this suffices for bzr.dev but may be
 
1418
        # too small for large or very branchy trees. However, for 55K path
 
1419
        # trees, it would be easy to use too much memory trivially. Ideally we
 
1420
        # could gauge this by looking at available real memory etc, but this is
 
1421
        # always a tricky proposition.
 
1422
        inventory_cache = lru_cache.LRUCache(10)
 
1423
        batch_size = 10 # should be ~150MB on a 55K path tree
 
1424
        batch_count = len(revision_order) / batch_size + 1
 
1425
        processed_texts = 0
 
1426
        pb.update("Calculating text parents.", processed_texts, text_count)
 
1427
        for offset in xrange(batch_count):
 
1428
            to_query = revision_order[offset * batch_size:(offset + 1) *
 
1429
                batch_size]
 
1430
            if not to_query:
 
1431
                break
 
1432
            for rev_tree in self.revision_trees(to_query):
 
1433
                revision_id = rev_tree.get_revision_id()
 
1434
                parent_ids = ancestors[revision_id]
 
1435
                for text_key in revision_keys[revision_id]:
 
1436
                    pb.update("Calculating text parents.", processed_texts)
 
1437
                    processed_texts += 1
 
1438
                    candidate_parents = []
 
1439
                    for parent_id in parent_ids:
 
1440
                        parent_text_key = (text_key[0], parent_id)
 
1441
                        try:
 
1442
                            check_parent = parent_text_key not in \
 
1443
                                revision_keys[parent_id]
 
1444
                        except KeyError:
 
1445
                            # the parent parent_id is a ghost:
 
1446
                            check_parent = False
 
1447
                            # truncate the derived graph against this ghost.
 
1448
                            parent_text_key = None
 
1449
                        if check_parent:
 
1450
                            # look at the parent commit details inventories to
 
1451
                            # determine possible candidates in the per file graph.
 
1452
                            # TODO: cache here.
 
1453
                            try:
 
1454
                                inv = inventory_cache[parent_id]
 
1455
                            except KeyError:
 
1456
                                inv = self.revision_tree(parent_id).inventory
 
1457
                                inventory_cache[parent_id] = inv
 
1458
                            parent_entry = inv._byid.get(text_key[0], None)
 
1459
                            if parent_entry is not None:
 
1460
                                parent_text_key = (
 
1461
                                    text_key[0], parent_entry.revision)
 
1462
                            else:
 
1463
                                parent_text_key = None
 
1464
                        if parent_text_key is not None:
 
1465
                            candidate_parents.append(
 
1466
                                text_key_cache[parent_text_key])
 
1467
                    parent_heads = text_graph.heads(candidate_parents)
 
1468
                    new_parents = list(parent_heads)
 
1469
                    new_parents.sort(key=lambda x:candidate_parents.index(x))
 
1470
                    if new_parents == []:
 
1471
                        new_parents = [NULL_REVISION]
 
1472
                    text_index[text_key] = new_parents
 
1473
 
 
1474
        for text_key in invalid_keys:
 
1475
            text_index[text_key] = [NULL_REVISION]
 
1476
        return text_index
 
1477
 
 
1478
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
 
1479
        """Get an iterable listing the keys of all the data introduced by a set
 
1480
        of revision IDs.
 
1481
 
 
1482
        The keys will be ordered so that the corresponding items can be safely
 
1483
        fetched and inserted in that order.
 
1484
 
 
1485
        :returns: An iterable producing tuples of (knit-kind, file-id,
 
1486
            versions).  knit-kind is one of 'file', 'inventory', 'signatures',
 
1487
            'revisions'.  file-id is None unless knit-kind is 'file'.
 
1488
        """
 
1489
        # XXX: it's a bit weird to control the inventory weave caching in this
 
1490
        # generator.  Ideally the caching would be done in fetch.py I think.  Or
 
1491
        # maybe this generator should explicitly have the contract that it
 
1492
        # should not be iterated until the previously yielded item has been
 
1493
        # processed?
 
1494
        inv_w = self.inventories
 
1495
 
 
1496
        # file ids that changed
 
1497
        file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
 
1498
        count = 0
 
1499
        num_file_ids = len(file_ids)
 
1500
        for file_id, altered_versions in file_ids.iteritems():
 
1501
            if _files_pb is not None:
 
1502
                _files_pb.update("fetch texts", count, num_file_ids)
 
1503
            count += 1
 
1504
            yield ("file", file_id, altered_versions)
 
1505
        # We're done with the files_pb.  Note that it finished by the caller,
 
1506
        # just as it was created by the caller.
 
1507
        del _files_pb
 
1508
 
 
1509
        # inventory
 
1510
        yield ("inventory", None, revision_ids)
 
1511
 
 
1512
        # signatures
 
1513
        revisions_with_signatures = set()
 
1514
        for rev_id in revision_ids:
 
1515
            try:
 
1516
                self.get_signature_text(rev_id)
 
1517
            except errors.NoSuchRevision:
 
1518
                # not signed.
 
1519
                pass
 
1520
            else:
 
1521
                revisions_with_signatures.add(rev_id)
 
1522
        yield ("signatures", None, revisions_with_signatures)
 
1523
 
 
1524
        # revisions
 
1525
        yield ("revisions", None, revision_ids)
 
1526
 
 
1527
    @needs_read_lock
 
1528
    def get_inventory(self, revision_id):
 
1529
        """Get Inventory object by revision id."""
 
1530
        return self.iter_inventories([revision_id]).next()
 
1531
 
 
1532
    def iter_inventories(self, revision_ids):
 
1533
        """Get many inventories by revision_ids.
 
1534
 
 
1535
        This will buffer some or all of the texts used in constructing the
 
1536
        inventories in memory, but will only parse a single inventory at a
 
1537
        time.
 
1538
 
 
1539
        :return: An iterator of inventories.
 
1540
        """
 
1541
        if ((None in revision_ids)
 
1542
            or (_mod_revision.NULL_REVISION in revision_ids)):
 
1543
            raise ValueError('cannot get null revision inventory')
 
1544
        return self._iter_inventories(revision_ids)
 
1545
 
 
1546
    def _iter_inventories(self, revision_ids):
 
1547
        """single-document based inventory iteration."""
 
1548
        for text, revision_id in self._iter_inventory_xmls(revision_ids):
 
1549
            yield self.deserialise_inventory(revision_id, text)
 
1550
 
 
1551
    def _iter_inventory_xmls(self, revision_ids):
 
1552
        keys = [(revision_id,) for revision_id in revision_ids]
 
1553
        stream = self.inventories.get_record_stream(keys, 'unordered', True)
 
1554
        texts = {}
 
1555
        for record in stream:
 
1556
            if record.storage_kind != 'absent':
 
1557
                texts[record.key] = record.get_bytes_as('fulltext')
 
1558
            else:
 
1559
                raise errors.NoSuchRevision(self, record.key)
 
1560
        for key in keys:
 
1561
            yield texts[key], key[-1]
 
1562
 
 
1563
    def deserialise_inventory(self, revision_id, xml):
 
1564
        """Transform the xml into an inventory object. 
 
1565
 
 
1566
        :param revision_id: The expected revision id of the inventory.
 
1567
        :param xml: A serialised inventory.
 
1568
        """
 
1569
        result = self._serializer.read_inventory_from_string(xml, revision_id)
 
1570
        if result.revision_id != revision_id:
 
1571
            raise AssertionError('revision id mismatch %s != %s' % (
 
1572
                result.revision_id, revision_id))
 
1573
        return result
 
1574
 
 
1575
    def serialise_inventory(self, inv):
 
1576
        return self._serializer.write_inventory_to_string(inv)
 
1577
 
 
1578
    def _serialise_inventory_to_lines(self, inv):
 
1579
        return self._serializer.write_inventory_to_lines(inv)
 
1580
 
 
1581
    def get_serializer_format(self):
 
1582
        return self._serializer.format_num
 
1583
 
 
1584
    @needs_read_lock
 
1585
    def get_inventory_xml(self, revision_id):
 
1586
        """Get inventory XML as a file object."""
 
1587
        texts = self._iter_inventory_xmls([revision_id])
 
1588
        try:
 
1589
            text, revision_id = texts.next()
 
1590
        except StopIteration:
 
1591
            raise errors.HistoryMissing(self, 'inventory', revision_id)
 
1592
        return text
 
1593
 
 
1594
    @needs_read_lock
 
1595
    def get_inventory_sha1(self, revision_id):
 
1596
        """Return the sha1 hash of the inventory entry
 
1597
        """
 
1598
        return self.get_revision(revision_id).inventory_sha1
 
1599
 
 
1600
    def iter_reverse_revision_history(self, revision_id):
 
1601
        """Iterate backwards through revision ids in the lefthand history
 
1602
 
 
1603
        :param revision_id: The revision id to start with.  All its lefthand
 
1604
            ancestors will be traversed.
 
1605
        """
 
1606
        graph = self.get_graph()
 
1607
        next_id = revision_id
 
1608
        while True:
 
1609
            if next_id in (None, _mod_revision.NULL_REVISION):
 
1610
                return
 
1611
            yield next_id
 
1612
            # Note: The following line may raise KeyError in the event of
 
1613
            # truncated history. We decided not to have a try:except:raise
 
1614
            # RevisionNotPresent here until we see a use for it, because of the
 
1615
            # cost in an inner loop that is by its very nature O(history).
 
1616
            # Robert Collins 20080326
 
1617
            parents = graph.get_parent_map([next_id])[next_id]
 
1618
            if len(parents) == 0:
 
1619
                return
 
1620
            else:
 
1621
                next_id = parents[0]
 
1622
 
 
1623
    @needs_read_lock
 
1624
    def get_revision_inventory(self, revision_id):
 
1625
        """Return inventory of a past revision."""
 
1626
        # TODO: Unify this with get_inventory()
 
1627
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
 
1628
        # must be the same as its revision, so this is trivial.
 
1629
        if revision_id is None:
 
1630
            # This does not make sense: if there is no revision,
 
1631
            # then it is the current tree inventory surely ?!
 
1632
            # and thus get_root_id() is something that looks at the last
 
1633
            # commit on the branch, and the get_root_id is an inventory check.
 
1634
            raise NotImplementedError
 
1635
            # return Inventory(self.get_root_id())
 
1636
        else:
 
1637
            return self.get_inventory(revision_id)
 
1638
 
 
1639
    def is_shared(self):
 
1640
        """Return True if this repository is flagged as a shared repository."""
 
1641
        raise NotImplementedError(self.is_shared)
 
1642
 
 
1643
    @needs_write_lock
 
1644
    def reconcile(self, other=None, thorough=False):
 
1645
        """Reconcile this repository."""
 
1646
        from bzrlib.reconcile import RepoReconciler
 
1647
        reconciler = RepoReconciler(self, thorough=thorough)
 
1648
        reconciler.reconcile()
 
1649
        return reconciler
 
1650
 
 
1651
    def _refresh_data(self):
 
1652
        """Helper called from lock_* to ensure coherency with disk.
 
1653
 
 
1654
        The default implementation does nothing; it is however possible
 
1655
        for repositories to maintain loaded indices across multiple locks
 
1656
        by checking inside their implementation of this method to see
 
1657
        whether their indices are still valid. This depends of course on
 
1658
        the disk format being validatable in this manner.
 
1659
        """
 
1660
 
 
1661
    @needs_read_lock
 
1662
    def revision_tree(self, revision_id):
 
1663
        """Return Tree for a revision on this branch.
 
1664
 
 
1665
        `revision_id` may be NULL_REVISION for the empty tree revision.
 
1666
        """
 
1667
        revision_id = _mod_revision.ensure_null(revision_id)
 
1668
        # TODO: refactor this to use an existing revision object
 
1669
        # so we don't need to read it in twice.
 
1670
        if revision_id == _mod_revision.NULL_REVISION:
 
1671
            return RevisionTree(self, Inventory(root_id=None), 
 
1672
                                _mod_revision.NULL_REVISION)
 
1673
        else:
 
1674
            inv = self.get_revision_inventory(revision_id)
 
1675
            return RevisionTree(self, inv, revision_id)
 
1676
 
 
1677
    def revision_trees(self, revision_ids):
 
1678
        """Return Tree for a revision on this branch.
 
1679
 
 
1680
        `revision_id` may not be None or 'null:'"""
 
1681
        inventories = self.iter_inventories(revision_ids)
 
1682
        for inv in inventories:
 
1683
            yield RevisionTree(self, inv, inv.revision_id)
 
1684
 
 
1685
    @needs_read_lock
 
1686
    def get_ancestry(self, revision_id, topo_sorted=True):
 
1687
        """Return a list of revision-ids integrated by a revision.
 
1688
 
 
1689
        The first element of the list is always None, indicating the origin 
 
1690
        revision.  This might change when we have history horizons, or 
 
1691
        perhaps we should have a new API.
 
1692
        
 
1693
        This is topologically sorted.
 
1694
        """
 
1695
        if _mod_revision.is_null(revision_id):
 
1696
            return [None]
 
1697
        if not self.has_revision(revision_id):
 
1698
            raise errors.NoSuchRevision(self, revision_id)
 
1699
        graph = self.get_graph()
 
1700
        keys = set()
 
1701
        search = graph._make_breadth_first_searcher([revision_id])
 
1702
        while True:
 
1703
            try:
 
1704
                found, ghosts = search.next_with_ghosts()
 
1705
            except StopIteration:
 
1706
                break
 
1707
            keys.update(found)
 
1708
        if _mod_revision.NULL_REVISION in keys:
 
1709
            keys.remove(_mod_revision.NULL_REVISION)
 
1710
        if topo_sorted:
 
1711
            parent_map = graph.get_parent_map(keys)
 
1712
            keys = tsort.topo_sort(parent_map)
 
1713
        return [None] + list(keys)
 
1714
 
 
1715
    def pack(self):
 
1716
        """Compress the data within the repository.
 
1717
 
 
1718
        This operation only makes sense for some repository types. For other
 
1719
        types it should be a no-op that just returns.
 
1720
 
 
1721
        This stub method does not require a lock, but subclasses should use
 
1722
        @needs_write_lock as this is a long running call its reasonable to 
 
1723
        implicitly lock for the user.
 
1724
        """
 
1725
 
 
1726
    @needs_read_lock
 
1727
    @deprecated_method(one_six)
 
1728
    def print_file(self, file, revision_id):
 
1729
        """Print `file` to stdout.
 
1730
        
 
1731
        FIXME RBC 20060125 as John Meinel points out this is a bad api
 
1732
        - it writes to stdout, it assumes that that is valid etc. Fix
 
1733
        by creating a new more flexible convenience function.
 
1734
        """
 
1735
        tree = self.revision_tree(revision_id)
 
1736
        # use inventory as it was in that revision
 
1737
        file_id = tree.inventory.path2id(file)
 
1738
        if not file_id:
 
1739
            # TODO: jam 20060427 Write a test for this code path
 
1740
            #       it had a bug in it, and was raising the wrong
 
1741
            #       exception.
 
1742
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
 
1743
        tree.print_file(file_id)
 
1744
 
 
1745
    def get_transaction(self):
 
1746
        return self.control_files.get_transaction()
 
1747
 
 
1748
    @deprecated_method(one_one)
 
1749
    def get_parents(self, revision_ids):
 
1750
        """See StackedParentsProvider.get_parents"""
 
1751
        parent_map = self.get_parent_map(revision_ids)
 
1752
        return [parent_map.get(r, None) for r in revision_ids]
 
1753
 
 
1754
    def get_parent_map(self, revision_ids):
 
1755
        """See graph._StackedParentsProvider.get_parent_map"""
 
1756
        # revisions index works in keys; this just works in revisions
 
1757
        # therefore wrap and unwrap
 
1758
        query_keys = []
 
1759
        result = {}
 
1760
        for revision_id in revision_ids:
 
1761
            if revision_id == _mod_revision.NULL_REVISION:
 
1762
                result[revision_id] = ()
 
1763
            elif revision_id is None:
 
1764
                raise ValueError('get_parent_map(None) is not valid')
 
1765
            else:
 
1766
                query_keys.append((revision_id ,))
 
1767
        for ((revision_id,), parent_keys) in \
 
1768
                self.revisions.get_parent_map(query_keys).iteritems():
 
1769
            if parent_keys:
 
1770
                result[revision_id] = tuple(parent_revid
 
1771
                    for (parent_revid,) in parent_keys)
 
1772
            else:
 
1773
                result[revision_id] = (_mod_revision.NULL_REVISION,)
 
1774
        return result
 
1775
 
 
1776
    def _make_parents_provider(self):
 
1777
        return self
 
1778
 
 
1779
    def get_graph(self, other_repository=None):
 
1780
        """Return the graph walker for this repository format"""
 
1781
        parents_provider = self._make_parents_provider()
 
1782
        if (other_repository is not None and
 
1783
            not self.has_same_location(other_repository)):
 
1784
            parents_provider = graph._StackedParentsProvider(
 
1785
                [parents_provider, other_repository._make_parents_provider()])
 
1786
        return graph.Graph(parents_provider)
 
1787
 
 
1788
    def _get_versioned_file_checker(self):
 
1789
        """Return an object suitable for checking versioned files."""
 
1790
        return _VersionedFileChecker(self)
 
1791
 
 
1792
    def revision_ids_to_search_result(self, result_set):
 
1793
        """Convert a set of revision ids to a graph SearchResult."""
 
1794
        result_parents = set()
 
1795
        for parents in self.get_graph().get_parent_map(
 
1796
            result_set).itervalues():
 
1797
            result_parents.update(parents)
 
1798
        included_keys = result_set.intersection(result_parents)
 
1799
        start_keys = result_set.difference(included_keys)
 
1800
        exclude_keys = result_parents.difference(result_set)
 
1801
        result = graph.SearchResult(start_keys, exclude_keys,
 
1802
            len(result_set), result_set)
 
1803
        return result
 
1804
 
 
1805
    @needs_write_lock
 
1806
    def set_make_working_trees(self, new_value):
 
1807
        """Set the policy flag for making working trees when creating branches.
 
1808
 
 
1809
        This only applies to branches that use this repository.
 
1810
 
 
1811
        The default is 'True'.
 
1812
        :param new_value: True to restore the default, False to disable making
 
1813
                          working trees.
 
1814
        """
 
1815
        raise NotImplementedError(self.set_make_working_trees)
 
1816
    
 
1817
    def make_working_trees(self):
 
1818
        """Returns the policy for making working trees on new branches."""
 
1819
        raise NotImplementedError(self.make_working_trees)
 
1820
 
 
1821
    @needs_write_lock
 
1822
    def sign_revision(self, revision_id, gpg_strategy):
 
1823
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
 
1824
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
 
1825
 
 
1826
    @needs_read_lock
 
1827
    def has_signature_for_revision_id(self, revision_id):
 
1828
        """Query for a revision signature for revision_id in the repository."""
 
1829
        if not self.has_revision(revision_id):
 
1830
            raise errors.NoSuchRevision(self, revision_id)
 
1831
        sig_present = (1 == len(
 
1832
            self.signatures.get_parent_map([(revision_id,)])))
 
1833
        return sig_present
 
1834
 
 
1835
    @needs_read_lock
 
1836
    def get_signature_text(self, revision_id):
 
1837
        """Return the text for a signature."""
 
1838
        stream = self.signatures.get_record_stream([(revision_id,)],
 
1839
            'unordered', True)
 
1840
        record = stream.next()
 
1841
        if record.storage_kind == 'absent':
 
1842
            raise errors.NoSuchRevision(self, revision_id)
 
1843
        return record.get_bytes_as('fulltext')
 
1844
 
 
1845
    @needs_read_lock
 
1846
    def check(self, revision_ids=None):
 
1847
        """Check consistency of all history of given revision_ids.
 
1848
 
 
1849
        Different repository implementations should override _check().
 
1850
 
 
1851
        :param revision_ids: A non-empty list of revision_ids whose ancestry
 
1852
             will be checked.  Typically the last revision_id of a branch.
 
1853
        """
 
1854
        return self._check(revision_ids)
 
1855
 
 
1856
    def _check(self, revision_ids):
 
1857
        result = check.Check(self)
 
1858
        result.check()
 
1859
        return result
 
1860
 
 
1861
    def _warn_if_deprecated(self):
 
1862
        global _deprecation_warning_done
 
1863
        if _deprecation_warning_done:
 
1864
            return
 
1865
        _deprecation_warning_done = True
 
1866
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
 
1867
                % (self._format, self.bzrdir.transport.base))
 
1868
 
 
1869
    def supports_rich_root(self):
 
1870
        return self._format.rich_root_data
 
1871
 
 
1872
    def _check_ascii_revisionid(self, revision_id, method):
 
1873
        """Private helper for ascii-only repositories."""
 
1874
        # weave repositories refuse to store revisionids that are non-ascii.
 
1875
        if revision_id is not None:
 
1876
            # weaves require ascii revision ids.
 
1877
            if isinstance(revision_id, unicode):
 
1878
                try:
 
1879
                    revision_id.encode('ascii')
 
1880
                except UnicodeEncodeError:
 
1881
                    raise errors.NonAsciiRevisionId(method, self)
 
1882
            else:
 
1883
                try:
 
1884
                    revision_id.decode('ascii')
 
1885
                except UnicodeDecodeError:
 
1886
                    raise errors.NonAsciiRevisionId(method, self)
 
1887
    
 
1888
    def revision_graph_can_have_wrong_parents(self):
 
1889
        """Is it possible for this repository to have a revision graph with
 
1890
        incorrect parents?
 
1891
 
 
1892
        If True, then this repository must also implement
 
1893
        _find_inconsistent_revision_parents so that check and reconcile can
 
1894
        check for inconsistencies before proceeding with other checks that may
 
1895
        depend on the revision index being consistent.
 
1896
        """
 
1897
        raise NotImplementedError(self.revision_graph_can_have_wrong_parents)
 
1898
 
 
1899
 
 
1900
# remove these delegates a while after bzr 0.15
 
1901
def __make_delegated(name, from_module):
 
1902
    def _deprecated_repository_forwarder():
 
1903
        symbol_versioning.warn('%s moved to %s in bzr 0.15'
 
1904
            % (name, from_module),
 
1905
            DeprecationWarning,
 
1906
            stacklevel=2)
 
1907
        m = __import__(from_module, globals(), locals(), [name])
 
1908
        try:
 
1909
            return getattr(m, name)
 
1910
        except AttributeError:
 
1911
            raise AttributeError('module %s has no name %s'
 
1912
                    % (m, name))
 
1913
    globals()[name] = _deprecated_repository_forwarder
 
1914
 
 
1915
for _name in [
 
1916
        'AllInOneRepository',
 
1917
        'WeaveMetaDirRepository',
 
1918
        'PreSplitOutRepositoryFormat',
 
1919
        'RepositoryFormat4',
 
1920
        'RepositoryFormat5',
 
1921
        'RepositoryFormat6',
 
1922
        'RepositoryFormat7',
 
1923
        ]:
 
1924
    __make_delegated(_name, 'bzrlib.repofmt.weaverepo')
 
1925
 
 
1926
for _name in [
 
1927
        'KnitRepository',
 
1928
        'RepositoryFormatKnit',
 
1929
        'RepositoryFormatKnit1',
 
1930
        ]:
 
1931
    __make_delegated(_name, 'bzrlib.repofmt.knitrepo')
 
1932
 
 
1933
 
 
1934
def install_revision(repository, rev, revision_tree):
 
1935
    """Install all revision data into a repository."""
 
1936
    install_revisions(repository, [(rev, revision_tree, None)])
 
1937
 
 
1938
 
 
1939
def install_revisions(repository, iterable, num_revisions=None, pb=None):
 
1940
    """Install all revision data into a repository.
 
1941
 
 
1942
    Accepts an iterable of revision, tree, signature tuples.  The signature
 
1943
    may be None.
 
1944
    """
 
1945
    repository.start_write_group()
 
1946
    try:
 
1947
        for n, (revision, revision_tree, signature) in enumerate(iterable):
 
1948
            _install_revision(repository, revision, revision_tree, signature)
 
1949
            if pb is not None:
 
1950
                pb.update('Transferring revisions', n + 1, num_revisions)
 
1951
    except:
 
1952
        repository.abort_write_group()
 
1953
        raise
 
1954
    else:
 
1955
        repository.commit_write_group()
 
1956
 
 
1957
 
 
1958
def _install_revision(repository, rev, revision_tree, signature):
 
1959
    """Install all revision data into a repository."""
 
1960
    present_parents = []
 
1961
    parent_trees = {}
 
1962
    for p_id in rev.parent_ids:
 
1963
        if repository.has_revision(p_id):
 
1964
            present_parents.append(p_id)
 
1965
            parent_trees[p_id] = repository.revision_tree(p_id)
 
1966
        else:
 
1967
            parent_trees[p_id] = repository.revision_tree(
 
1968
                                     _mod_revision.NULL_REVISION)
 
1969
 
 
1970
    inv = revision_tree.inventory
 
1971
    entries = inv.iter_entries()
 
1972
    # backwards compatibility hack: skip the root id.
 
1973
    if not repository.supports_rich_root():
 
1974
        path, root = entries.next()
 
1975
        if root.revision != rev.revision_id:
 
1976
            raise errors.IncompatibleRevision(repr(repository))
 
1977
    text_keys = {}
 
1978
    for path, ie in entries:
 
1979
        text_keys[(ie.file_id, ie.revision)] = ie
 
1980
    text_parent_map = repository.texts.get_parent_map(text_keys)
 
1981
    missing_texts = set(text_keys) - set(text_parent_map)
 
1982
    # Add the texts that are not already present
 
1983
    for text_key in missing_texts:
 
1984
        ie = text_keys[text_key]
 
1985
        text_parents = []
 
1986
        # FIXME: TODO: The following loop overlaps/duplicates that done by
 
1987
        # commit to determine parents. There is a latent/real bug here where
 
1988
        # the parents inserted are not those commit would do - in particular
 
1989
        # they are not filtered by heads(). RBC, AB
 
1990
        for revision, tree in parent_trees.iteritems():
 
1991
            if ie.file_id not in tree:
 
1992
                continue
 
1993
            parent_id = tree.inventory[ie.file_id].revision
 
1994
            if parent_id in text_parents:
 
1995
                continue
 
1996
            text_parents.append((ie.file_id, parent_id))
 
1997
        lines = revision_tree.get_file(ie.file_id).readlines()
 
1998
        repository.texts.add_lines(text_key, text_parents, lines)
 
1999
    try:
 
2000
        # install the inventory
 
2001
        repository.add_inventory(rev.revision_id, inv, present_parents)
 
2002
    except errors.RevisionAlreadyPresent:
 
2003
        pass
 
2004
    if signature is not None:
 
2005
        repository.add_signature_text(rev.revision_id, signature)
 
2006
    repository.add_revision(rev.revision_id, rev, inv)
 
2007
 
 
2008
 
 
2009
class MetaDirRepository(Repository):
 
2010
    """Repositories in the new meta-dir layout.
 
2011
    
 
2012
    :ivar _transport: Transport for access to repository control files,
 
2013
        typically pointing to .bzr/repository.
 
2014
    """
 
2015
 
 
2016
    def __init__(self, _format, a_bzrdir, control_files):
 
2017
        super(MetaDirRepository, self).__init__(_format, a_bzrdir, control_files)
 
2018
        self._transport = control_files._transport
 
2019
 
 
2020
    def is_shared(self):
 
2021
        """Return True if this repository is flagged as a shared repository."""
 
2022
        return self._transport.has('shared-storage')
 
2023
 
 
2024
    @needs_write_lock
 
2025
    def set_make_working_trees(self, new_value):
 
2026
        """Set the policy flag for making working trees when creating branches.
 
2027
 
 
2028
        This only applies to branches that use this repository.
 
2029
 
 
2030
        The default is 'True'.
 
2031
        :param new_value: True to restore the default, False to disable making
 
2032
                          working trees.
 
2033
        """
 
2034
        if new_value:
 
2035
            try:
 
2036
                self._transport.delete('no-working-trees')
 
2037
            except errors.NoSuchFile:
 
2038
                pass
 
2039
        else:
 
2040
            self._transport.put_bytes('no-working-trees', '',
 
2041
                mode=self.bzrdir._get_file_mode())
 
2042
    
 
2043
    def make_working_trees(self):
 
2044
        """Returns the policy for making working trees on new branches."""
 
2045
        return not self._transport.has('no-working-trees')
 
2046
 
 
2047
 
 
2048
class MetaDirVersionedFileRepository(MetaDirRepository):
 
2049
    """Repositories in a meta-dir, that work via versioned file objects."""
 
2050
 
 
2051
    def __init__(self, _format, a_bzrdir, control_files):
 
2052
        super(MetaDirVersionedFileRepository, self).__init__(_format, a_bzrdir,
 
2053
            control_files)
 
2054
 
 
2055
 
 
2056
class RepositoryFormatRegistry(registry.Registry):
 
2057
    """Registry of RepositoryFormats."""
 
2058
 
 
2059
    def get(self, format_string):
 
2060
        r = registry.Registry.get(self, format_string)
 
2061
        if callable(r):
 
2062
            r = r()
 
2063
        return r
 
2064
    
 
2065
 
 
2066
format_registry = RepositoryFormatRegistry()
 
2067
"""Registry of formats, indexed by their identifying format string.
 
2068
 
 
2069
This can contain either format instances themselves, or classes/factories that
 
2070
can be called to obtain one.
 
2071
"""
 
2072
 
 
2073
 
 
2074
#####################################################################
 
2075
# Repository Formats
 
2076
 
 
2077
class RepositoryFormat(object):
 
2078
    """A repository format.
 
2079
 
 
2080
    Formats provide three things:
 
2081
     * An initialization routine to construct repository data on disk.
 
2082
     * a format string which is used when the BzrDir supports versioned
 
2083
       children.
 
2084
     * an open routine which returns a Repository instance.
 
2085
 
 
2086
    There is one and only one Format subclass for each on-disk format. But
 
2087
    there can be one Repository subclass that is used for several different
 
2088
    formats. The _format attribute on a Repository instance can be used to
 
2089
    determine the disk format.
 
2090
 
 
2091
    Formats are placed in an dict by their format string for reference 
 
2092
    during opening. These should be subclasses of RepositoryFormat
 
2093
    for consistency.
 
2094
 
 
2095
    Once a format is deprecated, just deprecate the initialize and open
 
2096
    methods on the format class. Do not deprecate the object, as the 
 
2097
    object will be created every system load.
 
2098
 
 
2099
    Common instance attributes:
 
2100
    _matchingbzrdir - the bzrdir format that the repository format was
 
2101
    originally written to work with. This can be used if manually
 
2102
    constructing a bzrdir and repository, or more commonly for test suite
 
2103
    parameterization.
 
2104
    """
 
2105
 
 
2106
    # Set to True or False in derived classes. True indicates that the format
 
2107
    # supports ghosts gracefully.
 
2108
    supports_ghosts = None
 
2109
    # Can this repository be given external locations to lookup additional
 
2110
    # data. Set to True or False in derived classes.
 
2111
    supports_external_lookups = None
 
2112
 
 
2113
    def __str__(self):
 
2114
        return "<%s>" % self.__class__.__name__
 
2115
 
 
2116
    def __eq__(self, other):
 
2117
        # format objects are generally stateless
 
2118
        return isinstance(other, self.__class__)
 
2119
 
 
2120
    def __ne__(self, other):
 
2121
        return not self == other
 
2122
 
 
2123
    @classmethod
 
2124
    def find_format(klass, a_bzrdir):
 
2125
        """Return the format for the repository object in a_bzrdir.
 
2126
        
 
2127
        This is used by bzr native formats that have a "format" file in
 
2128
        the repository.  Other methods may be used by different types of 
 
2129
        control directory.
 
2130
        """
 
2131
        try:
 
2132
            transport = a_bzrdir.get_repository_transport(None)
 
2133
            format_string = transport.get("format").read()
 
2134
            return format_registry.get(format_string)
 
2135
        except errors.NoSuchFile:
 
2136
            raise errors.NoRepositoryPresent(a_bzrdir)
 
2137
        except KeyError:
 
2138
            raise errors.UnknownFormatError(format=format_string,
 
2139
                                            kind='repository')
 
2140
 
 
2141
    @classmethod
 
2142
    def register_format(klass, format):
 
2143
        format_registry.register(format.get_format_string(), format)
 
2144
 
 
2145
    @classmethod
 
2146
    def unregister_format(klass, format):
 
2147
        format_registry.remove(format.get_format_string())
 
2148
    
 
2149
    @classmethod
 
2150
    def get_default_format(klass):
 
2151
        """Return the current default format."""
 
2152
        from bzrlib import bzrdir
 
2153
        return bzrdir.format_registry.make_bzrdir('default').repository_format
 
2154
 
 
2155
    def get_format_string(self):
 
2156
        """Return the ASCII format string that identifies this format.
 
2157
        
 
2158
        Note that in pre format ?? repositories the format string is 
 
2159
        not permitted nor written to disk.
 
2160
        """
 
2161
        raise NotImplementedError(self.get_format_string)
 
2162
 
 
2163
    def get_format_description(self):
 
2164
        """Return the short description for this format."""
 
2165
        raise NotImplementedError(self.get_format_description)
 
2166
 
 
2167
    # TODO: this shouldn't be in the base class, it's specific to things that
 
2168
    # use weaves or knits -- mbp 20070207
 
2169
    def _get_versioned_file_store(self,
 
2170
                                  name,
 
2171
                                  transport,
 
2172
                                  control_files,
 
2173
                                  prefixed=True,
 
2174
                                  versionedfile_class=None,
 
2175
                                  versionedfile_kwargs={},
 
2176
                                  escaped=False):
 
2177
        if versionedfile_class is None:
 
2178
            versionedfile_class = self._versionedfile_class
 
2179
        weave_transport = control_files._transport.clone(name)
 
2180
        dir_mode = control_files._dir_mode
 
2181
        file_mode = control_files._file_mode
 
2182
        return VersionedFileStore(weave_transport, prefixed=prefixed,
 
2183
                                  dir_mode=dir_mode,
 
2184
                                  file_mode=file_mode,
 
2185
                                  versionedfile_class=versionedfile_class,
 
2186
                                  versionedfile_kwargs=versionedfile_kwargs,
 
2187
                                  escaped=escaped)
 
2188
 
 
2189
    def initialize(self, a_bzrdir, shared=False):
 
2190
        """Initialize a repository of this format in a_bzrdir.
 
2191
 
 
2192
        :param a_bzrdir: The bzrdir to put the new repository in it.
 
2193
        :param shared: The repository should be initialized as a sharable one.
 
2194
        :returns: The new repository object.
 
2195
        
 
2196
        This may raise UninitializableFormat if shared repository are not
 
2197
        compatible the a_bzrdir.
 
2198
        """
 
2199
        raise NotImplementedError(self.initialize)
 
2200
 
 
2201
    def is_supported(self):
 
2202
        """Is this format supported?
 
2203
 
 
2204
        Supported formats must be initializable and openable.
 
2205
        Unsupported formats may not support initialization or committing or 
 
2206
        some other features depending on the reason for not being supported.
 
2207
        """
 
2208
        return True
 
2209
 
 
2210
    def check_conversion_target(self, target_format):
 
2211
        raise NotImplementedError(self.check_conversion_target)
 
2212
 
 
2213
    def open(self, a_bzrdir, _found=False):
 
2214
        """Return an instance of this format for the bzrdir a_bzrdir.
 
2215
        
 
2216
        _found is a private parameter, do not use it.
 
2217
        """
 
2218
        raise NotImplementedError(self.open)
 
2219
 
 
2220
 
 
2221
class MetaDirRepositoryFormat(RepositoryFormat):
 
2222
    """Common base class for the new repositories using the metadir layout."""
 
2223
 
 
2224
    rich_root_data = False
 
2225
    supports_tree_reference = False
 
2226
    supports_external_lookups = False
 
2227
    _matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
2228
 
 
2229
    def __init__(self):
 
2230
        super(MetaDirRepositoryFormat, self).__init__()
 
2231
 
 
2232
    def _create_control_files(self, a_bzrdir):
 
2233
        """Create the required files and the initial control_files object."""
 
2234
        # FIXME: RBC 20060125 don't peek under the covers
 
2235
        # NB: no need to escape relative paths that are url safe.
 
2236
        repository_transport = a_bzrdir.get_repository_transport(self)
 
2237
        control_files = lockable_files.LockableFiles(repository_transport,
 
2238
                                'lock', lockdir.LockDir)
 
2239
        control_files.create_lock()
 
2240
        return control_files
 
2241
 
 
2242
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
 
2243
        """Upload the initial blank content."""
 
2244
        control_files = self._create_control_files(a_bzrdir)
 
2245
        control_files.lock_write()
 
2246
        transport = control_files._transport
 
2247
        if shared == True:
 
2248
            utf8_files += [('shared-storage', '')]
 
2249
        try:
 
2250
            transport.mkdir_multi(dirs, mode=a_bzrdir._get_dir_mode())
 
2251
            for (filename, content_stream) in files:
 
2252
                transport.put_file(filename, content_stream,
 
2253
                    mode=a_bzrdir._get_file_mode())
 
2254
            for (filename, content_bytes) in utf8_files:
 
2255
                transport.put_bytes_non_atomic(filename, content_bytes,
 
2256
                    mode=a_bzrdir._get_file_mode())
 
2257
        finally:
 
2258
            control_files.unlock()
 
2259
 
 
2260
 
 
2261
# formats which have no format string are not discoverable
 
2262
# and not independently creatable, so are not registered.  They're 
 
2263
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
 
2264
# needed, it's constructed directly by the BzrDir.  Non-native formats where
 
2265
# the repository is not separately opened are similar.
 
2266
 
 
2267
format_registry.register_lazy(
 
2268
    'Bazaar-NG Repository format 7',
 
2269
    'bzrlib.repofmt.weaverepo',
 
2270
    'RepositoryFormat7'
 
2271
    )
 
2272
 
 
2273
format_registry.register_lazy(
 
2274
    'Bazaar-NG Knit Repository Format 1',
 
2275
    'bzrlib.repofmt.knitrepo',
 
2276
    'RepositoryFormatKnit1',
 
2277
    )
 
2278
 
 
2279
format_registry.register_lazy(
 
2280
    'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
 
2281
    'bzrlib.repofmt.knitrepo',
 
2282
    'RepositoryFormatKnit3',
 
2283
    )
 
2284
 
 
2285
format_registry.register_lazy(
 
2286
    'Bazaar Knit Repository Format 4 (bzr 1.0)\n',
 
2287
    'bzrlib.repofmt.knitrepo',
 
2288
    'RepositoryFormatKnit4',
 
2289
    )
 
2290
 
 
2291
# Pack-based formats. There is one format for pre-subtrees, and one for
 
2292
# post-subtrees to allow ease of testing.
 
2293
# NOTE: These are experimental in 0.92. Stable in 1.0 and above
 
2294
format_registry.register_lazy(
 
2295
    'Bazaar pack repository format 1 (needs bzr 0.92)\n',
 
2296
    'bzrlib.repofmt.pack_repo',
 
2297
    'RepositoryFormatKnitPack1',
 
2298
    )
 
2299
format_registry.register_lazy(
 
2300
    'Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n',
 
2301
    'bzrlib.repofmt.pack_repo',
 
2302
    'RepositoryFormatKnitPack3',
 
2303
    )
 
2304
format_registry.register_lazy(
 
2305
    'Bazaar pack repository format 1 with rich root (needs bzr 1.0)\n',
 
2306
    'bzrlib.repofmt.pack_repo',
 
2307
    'RepositoryFormatKnitPack4',
 
2308
    )
 
2309
format_registry.register_lazy(
 
2310
    'Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n',
 
2311
    'bzrlib.repofmt.pack_repo',
 
2312
    'RepositoryFormatKnitPack5',
 
2313
    )
 
2314
format_registry.register_lazy(
 
2315
    'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n',
 
2316
    'bzrlib.repofmt.pack_repo',
 
2317
    'RepositoryFormatKnitPack5RichRoot',
 
2318
    )
 
2319
format_registry.register_lazy(
 
2320
    'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n',
 
2321
    'bzrlib.repofmt.pack_repo',
 
2322
    'RepositoryFormatKnitPack5RichRootBroken',
 
2323
    )
 
2324
 
 
2325
# Development formats. 
 
2326
# 1.5->1.6
 
2327
format_registry.register_lazy(
 
2328
    "Bazaar development format 1 (needs bzr.dev from before 1.6)\n",
 
2329
    'bzrlib.repofmt.pack_repo',
 
2330
    'RepositoryFormatPackDevelopment1',
 
2331
    )
 
2332
format_registry.register_lazy(
 
2333
    ("Bazaar development format 1 with subtree support "
 
2334
        "(needs bzr.dev from before 1.6)\n"),
 
2335
    'bzrlib.repofmt.pack_repo',
 
2336
    'RepositoryFormatPackDevelopment1Subtree',
 
2337
    )
 
2338
# 1.6->1.7 go below here
 
2339
 
 
2340
 
 
2341
class InterRepository(InterObject):
 
2342
    """This class represents operations taking place between two repositories.
 
2343
 
 
2344
    Its instances have methods like copy_content and fetch, and contain
 
2345
    references to the source and target repositories these operations can be 
 
2346
    carried out on.
 
2347
 
 
2348
    Often we will provide convenience methods on 'repository' which carry out
 
2349
    operations with another repository - they will always forward to
 
2350
    InterRepository.get(other).method_name(parameters).
 
2351
    """
 
2352
 
 
2353
    _optimisers = []
 
2354
    """The available optimised InterRepository types."""
 
2355
 
 
2356
    def copy_content(self, revision_id=None):
 
2357
        raise NotImplementedError(self.copy_content)
 
2358
 
 
2359
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
2360
        """Fetch the content required to construct revision_id.
 
2361
 
 
2362
        The content is copied from self.source to self.target.
 
2363
 
 
2364
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
2365
                            content is copied.
 
2366
        :param pb: optional progress bar to use for progress reports. If not
 
2367
                   provided a default one will be created.
 
2368
 
 
2369
        :returns: (copied_revision_count, failures).
 
2370
        """
 
2371
        # Normally we should find a specific InterRepository subclass to do
 
2372
        # the fetch; if nothing else then at least InterSameDataRepository.
 
2373
        # If none of them is suitable it looks like fetching is not possible;
 
2374
        # we try to give a good message why.  _assert_same_model will probably
 
2375
        # give a helpful message; otherwise a generic one.
 
2376
        self._assert_same_model(self.source, self.target)
 
2377
        raise errors.IncompatibleRepositories(self.source, self.target,
 
2378
            "no suitableInterRepository found")
 
2379
 
 
2380
    def _walk_to_common_revisions(self, revision_ids):
 
2381
        """Walk out from revision_ids in source to revisions target has.
 
2382
 
 
2383
        :param revision_ids: The start point for the search.
 
2384
        :return: A set of revision ids.
 
2385
        """
 
2386
        target_graph = self.target.get_graph()
 
2387
        revision_ids = frozenset(revision_ids)
 
2388
        if set(target_graph.get_parent_map(revision_ids)) == revision_ids:
 
2389
            return graph.SearchResult(revision_ids, set(), 0, set())
 
2390
        missing_revs = set()
 
2391
        source_graph = self.source.get_graph()
 
2392
        # ensure we don't pay silly lookup costs.
 
2393
        searcher = source_graph._make_breadth_first_searcher(revision_ids)
 
2394
        null_set = frozenset([_mod_revision.NULL_REVISION])
 
2395
        while True:
 
2396
            try:
 
2397
                next_revs, ghosts = searcher.next_with_ghosts()
 
2398
            except StopIteration:
 
2399
                break
 
2400
            if revision_ids.intersection(ghosts):
 
2401
                absent_ids = set(revision_ids.intersection(ghosts))
 
2402
                # If all absent_ids are present in target, no error is needed.
 
2403
                absent_ids.difference_update(
 
2404
                    set(target_graph.get_parent_map(absent_ids)))
 
2405
                if absent_ids:
 
2406
                    raise errors.NoSuchRevision(self.source, absent_ids.pop())
 
2407
            # we don't care about other ghosts as we can't fetch them and
 
2408
            # haven't been asked to.
 
2409
            next_revs = set(next_revs)
 
2410
            # we always have NULL_REVISION present.
 
2411
            have_revs = set(target_graph.get_parent_map(next_revs)).union(null_set)
 
2412
            missing_revs.update(next_revs - have_revs)
 
2413
            searcher.stop_searching_any(have_revs)
 
2414
        return searcher.get_result()
 
2415
   
 
2416
    @deprecated_method(one_two)
 
2417
    @needs_read_lock
 
2418
    def missing_revision_ids(self, revision_id=None, find_ghosts=True):
 
2419
        """Return the revision ids that source has that target does not.
 
2420
        
 
2421
        These are returned in topological order.
 
2422
 
 
2423
        :param revision_id: only return revision ids included by this
 
2424
                            revision_id.
 
2425
        :param find_ghosts: If True find missing revisions in deep history
 
2426
            rather than just finding the surface difference.
 
2427
        """
 
2428
        return list(self.search_missing_revision_ids(
 
2429
            revision_id, find_ghosts).get_keys())
 
2430
 
 
2431
    @needs_read_lock
 
2432
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
 
2433
        """Return the revision ids that source has that target does not.
 
2434
        
 
2435
        :param revision_id: only return revision ids included by this
 
2436
                            revision_id.
 
2437
        :param find_ghosts: If True find missing revisions in deep history
 
2438
            rather than just finding the surface difference.
 
2439
        :return: A bzrlib.graph.SearchResult.
 
2440
        """
 
2441
        # stop searching at found target revisions.
 
2442
        if not find_ghosts and revision_id is not None:
 
2443
            return self._walk_to_common_revisions([revision_id])
 
2444
        # generic, possibly worst case, slow code path.
 
2445
        target_ids = set(self.target.all_revision_ids())
 
2446
        if revision_id is not None:
 
2447
            source_ids = self.source.get_ancestry(revision_id)
 
2448
            if source_ids[0] is not None:
 
2449
                raise AssertionError()
 
2450
            source_ids.pop(0)
 
2451
        else:
 
2452
            source_ids = self.source.all_revision_ids()
 
2453
        result_set = set(source_ids).difference(target_ids)
 
2454
        return self.source.revision_ids_to_search_result(result_set)
 
2455
 
 
2456
    @staticmethod
 
2457
    def _same_model(source, target):
 
2458
        """True if source and target have the same data representation.
 
2459
        
 
2460
        Note: this is always called on the base class; overriding it in a
 
2461
        subclass will have no effect.
 
2462
        """
 
2463
        try:
 
2464
            InterRepository._assert_same_model(source, target)
 
2465
            return True
 
2466
        except errors.IncompatibleRepositories, e:
 
2467
            return False
 
2468
 
 
2469
    @staticmethod
 
2470
    def _assert_same_model(source, target):
 
2471
        """Raise an exception if two repositories do not use the same model.
 
2472
        """
 
2473
        if source.supports_rich_root() != target.supports_rich_root():
 
2474
            raise errors.IncompatibleRepositories(source, target,
 
2475
                "different rich-root support")
 
2476
        if source._serializer != target._serializer:
 
2477
            raise errors.IncompatibleRepositories(source, target,
 
2478
                "different serializers")
 
2479
 
 
2480
 
 
2481
class InterSameDataRepository(InterRepository):
 
2482
    """Code for converting between repositories that represent the same data.
 
2483
    
 
2484
    Data format and model must match for this to work.
 
2485
    """
 
2486
 
 
2487
    @classmethod
 
2488
    def _get_repo_format_to_test(self):
 
2489
        """Repository format for testing with.
 
2490
        
 
2491
        InterSameData can pull from subtree to subtree and from non-subtree to
 
2492
        non-subtree, so we test this with the richest repository format.
 
2493
        """
 
2494
        from bzrlib.repofmt import knitrepo
 
2495
        return knitrepo.RepositoryFormatKnit3()
 
2496
 
 
2497
    @staticmethod
 
2498
    def is_compatible(source, target):
 
2499
        return InterRepository._same_model(source, target)
 
2500
 
 
2501
    @needs_write_lock
 
2502
    def copy_content(self, revision_id=None):
 
2503
        """Make a complete copy of the content in self into destination.
 
2504
 
 
2505
        This copies both the repository's revision data, and configuration information
 
2506
        such as the make_working_trees setting.
 
2507
        
 
2508
        This is a destructive operation! Do not use it on existing 
 
2509
        repositories.
 
2510
 
 
2511
        :param revision_id: Only copy the content needed to construct
 
2512
                            revision_id and its parents.
 
2513
        """
 
2514
        try:
 
2515
            self.target.set_make_working_trees(self.source.make_working_trees())
 
2516
        except NotImplementedError:
 
2517
            pass
 
2518
        # but don't bother fetching if we have the needed data now.
 
2519
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
2520
            self.target.has_revision(revision_id)):
 
2521
            return
 
2522
        self.target.fetch(self.source, revision_id=revision_id)
 
2523
 
 
2524
    @needs_write_lock
 
2525
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
2526
        """See InterRepository.fetch()."""
 
2527
        from bzrlib.fetch import RepoFetcher
 
2528
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
2529
               self.source, self.source._format, self.target,
 
2530
               self.target._format)
 
2531
        f = RepoFetcher(to_repository=self.target,
 
2532
                               from_repository=self.source,
 
2533
                               last_revision=revision_id,
 
2534
                               pb=pb, find_ghosts=find_ghosts)
 
2535
        return f.count_copied, f.failed_revisions
 
2536
 
 
2537
 
 
2538
class InterWeaveRepo(InterSameDataRepository):
 
2539
    """Optimised code paths between Weave based repositories.
 
2540
    
 
2541
    This should be in bzrlib/repofmt/weaverepo.py but we have not yet
 
2542
    implemented lazy inter-object optimisation.
 
2543
    """
 
2544
 
 
2545
    @classmethod
 
2546
    def _get_repo_format_to_test(self):
 
2547
        from bzrlib.repofmt import weaverepo
 
2548
        return weaverepo.RepositoryFormat7()
 
2549
 
 
2550
    @staticmethod
 
2551
    def is_compatible(source, target):
 
2552
        """Be compatible with known Weave formats.
 
2553
        
 
2554
        We don't test for the stores being of specific types because that
 
2555
        could lead to confusing results, and there is no need to be 
 
2556
        overly general.
 
2557
        """
 
2558
        from bzrlib.repofmt.weaverepo import (
 
2559
                RepositoryFormat5,
 
2560
                RepositoryFormat6,
 
2561
                RepositoryFormat7,
 
2562
                )
 
2563
        try:
 
2564
            return (isinstance(source._format, (RepositoryFormat5,
 
2565
                                                RepositoryFormat6,
 
2566
                                                RepositoryFormat7)) and
 
2567
                    isinstance(target._format, (RepositoryFormat5,
 
2568
                                                RepositoryFormat6,
 
2569
                                                RepositoryFormat7)))
 
2570
        except AttributeError:
 
2571
            return False
 
2572
    
 
2573
    @needs_write_lock
 
2574
    def copy_content(self, revision_id=None):
 
2575
        """See InterRepository.copy_content()."""
 
2576
        # weave specific optimised path:
 
2577
        try:
 
2578
            self.target.set_make_working_trees(self.source.make_working_trees())
 
2579
        except (errors.RepositoryUpgradeRequired, NotImplemented):
 
2580
            pass
 
2581
        # FIXME do not peek!
 
2582
        if self.source._transport.listable():
 
2583
            pb = ui.ui_factory.nested_progress_bar()
 
2584
            try:
 
2585
                self.target.texts.insert_record_stream(
 
2586
                    self.source.texts.get_record_stream(
 
2587
                        self.source.texts.keys(), 'topological', False))
 
2588
                pb.update('copying inventory', 0, 1)
 
2589
                self.target.inventories.insert_record_stream(
 
2590
                    self.source.inventories.get_record_stream(
 
2591
                        self.source.inventories.keys(), 'topological', False))
 
2592
                self.target.signatures.insert_record_stream(
 
2593
                    self.source.signatures.get_record_stream(
 
2594
                        self.source.signatures.keys(),
 
2595
                        'unordered', True))
 
2596
                self.target.revisions.insert_record_stream(
 
2597
                    self.source.revisions.get_record_stream(
 
2598
                        self.source.revisions.keys(),
 
2599
                        'topological', True))
 
2600
            finally:
 
2601
                pb.finished()
 
2602
        else:
 
2603
            self.target.fetch(self.source, revision_id=revision_id)
 
2604
 
 
2605
    @needs_write_lock
 
2606
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
2607
        """See InterRepository.fetch()."""
 
2608
        from bzrlib.fetch import RepoFetcher
 
2609
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
2610
               self.source, self.source._format, self.target, self.target._format)
 
2611
        f = RepoFetcher(to_repository=self.target,
 
2612
                               from_repository=self.source,
 
2613
                               last_revision=revision_id,
 
2614
                               pb=pb, find_ghosts=find_ghosts)
 
2615
        return f.count_copied, f.failed_revisions
 
2616
 
 
2617
    @needs_read_lock
 
2618
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
 
2619
        """See InterRepository.missing_revision_ids()."""
 
2620
        # we want all revisions to satisfy revision_id in source.
 
2621
        # but we don't want to stat every file here and there.
 
2622
        # we want then, all revisions other needs to satisfy revision_id 
 
2623
        # checked, but not those that we have locally.
 
2624
        # so the first thing is to get a subset of the revisions to 
 
2625
        # satisfy revision_id in source, and then eliminate those that
 
2626
        # we do already have. 
 
2627
        # this is slow on high latency connection to self, but as as this
 
2628
        # disk format scales terribly for push anyway due to rewriting 
 
2629
        # inventory.weave, this is considered acceptable.
 
2630
        # - RBC 20060209
 
2631
        if revision_id is not None:
 
2632
            source_ids = self.source.get_ancestry(revision_id)
 
2633
            if source_ids[0] is not None:
 
2634
                raise AssertionError()
 
2635
            source_ids.pop(0)
 
2636
        else:
 
2637
            source_ids = self.source._all_possible_ids()
 
2638
        source_ids_set = set(source_ids)
 
2639
        # source_ids is the worst possible case we may need to pull.
 
2640
        # now we want to filter source_ids against what we actually
 
2641
        # have in target, but don't try to check for existence where we know
 
2642
        # we do not have a revision as that would be pointless.
 
2643
        target_ids = set(self.target._all_possible_ids())
 
2644
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
2645
        actually_present_revisions = set(
 
2646
            self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
2647
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
2648
        if revision_id is not None:
 
2649
            # we used get_ancestry to determine source_ids then we are assured all
 
2650
            # revisions referenced are present as they are installed in topological order.
 
2651
            # and the tip revision was validated by get_ancestry.
 
2652
            result_set = required_revisions
 
2653
        else:
 
2654
            # if we just grabbed the possibly available ids, then 
 
2655
            # we only have an estimate of whats available and need to validate
 
2656
            # that against the revision records.
 
2657
            result_set = set(
 
2658
                self.source._eliminate_revisions_not_present(required_revisions))
 
2659
        return self.source.revision_ids_to_search_result(result_set)
 
2660
 
 
2661
 
 
2662
class InterKnitRepo(InterSameDataRepository):
 
2663
    """Optimised code paths between Knit based repositories."""
 
2664
 
 
2665
    @classmethod
 
2666
    def _get_repo_format_to_test(self):
 
2667
        from bzrlib.repofmt import knitrepo
 
2668
        return knitrepo.RepositoryFormatKnit1()
 
2669
 
 
2670
    @staticmethod
 
2671
    def is_compatible(source, target):
 
2672
        """Be compatible with known Knit formats.
 
2673
        
 
2674
        We don't test for the stores being of specific types because that
 
2675
        could lead to confusing results, and there is no need to be 
 
2676
        overly general.
 
2677
        """
 
2678
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit
 
2679
        try:
 
2680
            are_knits = (isinstance(source._format, RepositoryFormatKnit) and
 
2681
                isinstance(target._format, RepositoryFormatKnit))
 
2682
        except AttributeError:
 
2683
            return False
 
2684
        return are_knits and InterRepository._same_model(source, target)
 
2685
 
 
2686
    @needs_write_lock
 
2687
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
2688
        """See InterRepository.fetch()."""
 
2689
        from bzrlib.fetch import RepoFetcher
 
2690
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
2691
               self.source, self.source._format, self.target, self.target._format)
 
2692
        f = RepoFetcher(to_repository=self.target,
 
2693
                            from_repository=self.source,
 
2694
                            last_revision=revision_id,
 
2695
                            pb=pb, find_ghosts=find_ghosts)
 
2696
        return f.count_copied, f.failed_revisions
 
2697
 
 
2698
    @needs_read_lock
 
2699
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
 
2700
        """See InterRepository.missing_revision_ids()."""
 
2701
        if revision_id is not None:
 
2702
            source_ids = self.source.get_ancestry(revision_id)
 
2703
            if source_ids[0] is not None:
 
2704
                raise AssertionError()
 
2705
            source_ids.pop(0)
 
2706
        else:
 
2707
            source_ids = self.source.all_revision_ids()
 
2708
        source_ids_set = set(source_ids)
 
2709
        # source_ids is the worst possible case we may need to pull.
 
2710
        # now we want to filter source_ids against what we actually
 
2711
        # have in target, but don't try to check for existence where we know
 
2712
        # we do not have a revision as that would be pointless.
 
2713
        target_ids = set(self.target.all_revision_ids())
 
2714
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
2715
        actually_present_revisions = set(
 
2716
            self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
2717
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
2718
        if revision_id is not None:
 
2719
            # we used get_ancestry to determine source_ids then we are assured all
 
2720
            # revisions referenced are present as they are installed in topological order.
 
2721
            # and the tip revision was validated by get_ancestry.
 
2722
            result_set = required_revisions
 
2723
        else:
 
2724
            # if we just grabbed the possibly available ids, then 
 
2725
            # we only have an estimate of whats available and need to validate
 
2726
            # that against the revision records.
 
2727
            result_set = set(
 
2728
                self.source._eliminate_revisions_not_present(required_revisions))
 
2729
        return self.source.revision_ids_to_search_result(result_set)
 
2730
 
 
2731
 
 
2732
class InterPackRepo(InterSameDataRepository):
 
2733
    """Optimised code paths between Pack based repositories."""
 
2734
 
 
2735
    @classmethod
 
2736
    def _get_repo_format_to_test(self):
 
2737
        from bzrlib.repofmt import pack_repo
 
2738
        return pack_repo.RepositoryFormatKnitPack1()
 
2739
 
 
2740
    @staticmethod
 
2741
    def is_compatible(source, target):
 
2742
        """Be compatible with known Pack formats.
 
2743
        
 
2744
        We don't test for the stores being of specific types because that
 
2745
        could lead to confusing results, and there is no need to be 
 
2746
        overly general.
 
2747
        """
 
2748
        from bzrlib.repofmt.pack_repo import RepositoryFormatPack
 
2749
        try:
 
2750
            are_packs = (isinstance(source._format, RepositoryFormatPack) and
 
2751
                isinstance(target._format, RepositoryFormatPack))
 
2752
        except AttributeError:
 
2753
            return False
 
2754
        return are_packs and InterRepository._same_model(source, target)
 
2755
 
 
2756
    @needs_write_lock
 
2757
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
2758
        """See InterRepository.fetch()."""
 
2759
        if (len(self.source._fallback_repositories) > 0 or
 
2760
            len(self.target._fallback_repositories) > 0):
 
2761
            # The pack layer is not aware of fallback repositories, so when
 
2762
            # fetching from a stacked repository or into a stacked repository
 
2763
            # we use the generic fetch logic which uses the VersionedFiles
 
2764
            # attributes on repository.
 
2765
            from bzrlib.fetch import RepoFetcher
 
2766
            fetcher = RepoFetcher(self.target, self.source, revision_id,
 
2767
                                  pb, find_ghosts)
 
2768
            return fetcher.count_copied, fetcher.failed_revisions
 
2769
        from bzrlib.repofmt.pack_repo import Packer
 
2770
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
2771
               self.source, self.source._format, self.target, self.target._format)
 
2772
        self.count_copied = 0
 
2773
        if revision_id is None:
 
2774
            # TODO:
 
2775
            # everything to do - use pack logic
 
2776
            # to fetch from all packs to one without
 
2777
            # inventory parsing etc, IFF nothing to be copied is in the target.
 
2778
            # till then:
 
2779
            source_revision_ids = frozenset(self.source.all_revision_ids())
 
2780
            revision_ids = source_revision_ids - \
 
2781
                frozenset(self.target.get_parent_map(source_revision_ids))
 
2782
            revision_keys = [(revid,) for revid in revision_ids]
 
2783
            index = self.target._pack_collection.revision_index.combined_index
 
2784
            present_revision_ids = set(item[1][0] for item in
 
2785
                index.iter_entries(revision_keys))
 
2786
            revision_ids = set(revision_ids) - present_revision_ids
 
2787
            # implementing the TODO will involve:
 
2788
            # - detecting when all of a pack is selected
 
2789
            # - avoiding as much as possible pre-selection, so the
 
2790
            # more-core routines such as create_pack_from_packs can filter in
 
2791
            # a just-in-time fashion. (though having a HEADS list on a
 
2792
            # repository might make this a lot easier, because we could
 
2793
            # sensibly detect 'new revisions' without doing a full index scan.
 
2794
        elif _mod_revision.is_null(revision_id):
 
2795
            # nothing to do:
 
2796
            return (0, [])
 
2797
        else:
 
2798
            try:
 
2799
                revision_ids = self.search_missing_revision_ids(revision_id,
 
2800
                    find_ghosts=find_ghosts).get_keys()
 
2801
            except errors.NoSuchRevision:
 
2802
                raise errors.InstallFailed([revision_id])
 
2803
            if len(revision_ids) == 0:
 
2804
                return (0, [])
 
2805
        packs = self.source._pack_collection.all_packs()
 
2806
        pack = Packer(self.target._pack_collection, packs, '.fetch',
 
2807
            revision_ids).pack()
 
2808
        if pack is not None:
 
2809
            self.target._pack_collection._save_pack_names()
 
2810
            # Trigger an autopack. This may duplicate effort as we've just done
 
2811
            # a pack creation, but for now it is simpler to think about as
 
2812
            # 'upload data, then repack if needed'.
 
2813
            self.target._pack_collection.autopack()
 
2814
            return (pack.get_revision_count(), [])
 
2815
        else:
 
2816
            return (0, [])
 
2817
 
 
2818
    @needs_read_lock
 
2819
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
 
2820
        """See InterRepository.missing_revision_ids().
 
2821
        
 
2822
        :param find_ghosts: Find ghosts throughout the ancestry of
 
2823
            revision_id.
 
2824
        """
 
2825
        if not find_ghosts and revision_id is not None:
 
2826
            return self._walk_to_common_revisions([revision_id])
 
2827
        elif revision_id is not None:
 
2828
            # Find ghosts: search for revisions pointing from one repository to
 
2829
            # the other, and vice versa, anywhere in the history of revision_id.
 
2830
            graph = self.target.get_graph(other_repository=self.source)
 
2831
            searcher = graph._make_breadth_first_searcher([revision_id])
 
2832
            found_ids = set()
 
2833
            while True:
 
2834
                try:
 
2835
                    next_revs, ghosts = searcher.next_with_ghosts()
 
2836
                except StopIteration:
 
2837
                    break
 
2838
                if revision_id in ghosts:
 
2839
                    raise errors.NoSuchRevision(self.source, revision_id)
 
2840
                found_ids.update(next_revs)
 
2841
                found_ids.update(ghosts)
 
2842
            found_ids = frozenset(found_ids)
 
2843
            # Double query here: should be able to avoid this by changing the
 
2844
            # graph api further.
 
2845
            result_set = found_ids - frozenset(
 
2846
                self.target.get_parent_map(found_ids))
 
2847
        else:
 
2848
            source_ids = self.source.all_revision_ids()
 
2849
            # source_ids is the worst possible case we may need to pull.
 
2850
            # now we want to filter source_ids against what we actually
 
2851
            # have in target, but don't try to check for existence where we know
 
2852
            # we do not have a revision as that would be pointless.
 
2853
            target_ids = set(self.target.all_revision_ids())
 
2854
            result_set = set(source_ids).difference(target_ids)
 
2855
        return self.source.revision_ids_to_search_result(result_set)
 
2856
 
 
2857
 
 
2858
class InterModel1and2(InterRepository):
 
2859
 
 
2860
    @classmethod
 
2861
    def _get_repo_format_to_test(self):
 
2862
        return None
 
2863
 
 
2864
    @staticmethod
 
2865
    def is_compatible(source, target):
 
2866
        if not source.supports_rich_root() and target.supports_rich_root():
 
2867
            return True
 
2868
        else:
 
2869
            return False
 
2870
 
 
2871
    @needs_write_lock
 
2872
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
2873
        """See InterRepository.fetch()."""
 
2874
        from bzrlib.fetch import Model1toKnit2Fetcher
 
2875
        f = Model1toKnit2Fetcher(to_repository=self.target,
 
2876
                                 from_repository=self.source,
 
2877
                                 last_revision=revision_id,
 
2878
                                 pb=pb, find_ghosts=find_ghosts)
 
2879
        return f.count_copied, f.failed_revisions
 
2880
 
 
2881
    @needs_write_lock
 
2882
    def copy_content(self, revision_id=None):
 
2883
        """Make a complete copy of the content in self into destination.
 
2884
        
 
2885
        This is a destructive operation! Do not use it on existing 
 
2886
        repositories.
 
2887
 
 
2888
        :param revision_id: Only copy the content needed to construct
 
2889
                            revision_id and its parents.
 
2890
        """
 
2891
        try:
 
2892
            self.target.set_make_working_trees(self.source.make_working_trees())
 
2893
        except NotImplementedError:
 
2894
            pass
 
2895
        # but don't bother fetching if we have the needed data now.
 
2896
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
2897
            self.target.has_revision(revision_id)):
 
2898
            return
 
2899
        self.target.fetch(self.source, revision_id=revision_id)
 
2900
 
 
2901
 
 
2902
class InterKnit1and2(InterKnitRepo):
 
2903
 
 
2904
    @classmethod
 
2905
    def _get_repo_format_to_test(self):
 
2906
        return None
 
2907
 
 
2908
    @staticmethod
 
2909
    def is_compatible(source, target):
 
2910
        """Be compatible with Knit1 source and Knit3 target"""
 
2911
        try:
 
2912
            from bzrlib.repofmt.knitrepo import (
 
2913
                RepositoryFormatKnit1,
 
2914
                RepositoryFormatKnit3,
 
2915
                )
 
2916
            from bzrlib.repofmt.pack_repo import (
 
2917
                RepositoryFormatKnitPack1,
 
2918
                RepositoryFormatKnitPack3,
 
2919
                RepositoryFormatKnitPack4,
 
2920
                RepositoryFormatKnitPack5,
 
2921
                RepositoryFormatKnitPack5RichRoot,
 
2922
                RepositoryFormatPackDevelopment1,
 
2923
                RepositoryFormatPackDevelopment1Subtree,
 
2924
                )
 
2925
            norichroot = (
 
2926
                RepositoryFormatKnit1,            # no rr, no subtree
 
2927
                RepositoryFormatKnitPack1,        # no rr, no subtree
 
2928
                RepositoryFormatPackDevelopment1, # no rr, no subtree
 
2929
                RepositoryFormatKnitPack5,        # no rr, no subtree
 
2930
                )
 
2931
            richroot = (
 
2932
                RepositoryFormatKnit3,            # rr, subtree
 
2933
                RepositoryFormatKnitPack3,        # rr, subtree
 
2934
                RepositoryFormatKnitPack4,        # rr, no subtree
 
2935
                RepositoryFormatKnitPack5RichRoot,# rr, no subtree
 
2936
                RepositoryFormatPackDevelopment1Subtree, # rr, subtree
 
2937
                )
 
2938
            for format in norichroot:
 
2939
                if format.rich_root_data:
 
2940
                    raise AssertionError('Format %s is a rich-root format'
 
2941
                        ' but is included in the non-rich-root list'
 
2942
                        % (format,))
 
2943
            for format in richroot:
 
2944
                if not format.rich_root_data:
 
2945
                    raise AssertionError('Format %s is not a rich-root format'
 
2946
                        ' but is included in the rich-root list'
 
2947
                        % (format,))
 
2948
            # TODO: One alternative is to just check format.rich_root_data,
 
2949
            #       instead of keeping membership lists. However, the formats
 
2950
            #       *also* have to use the same 'Knit' style of storage
 
2951
            #       (line-deltas, fulltexts, etc.)
 
2952
            return (isinstance(source._format, norichroot) and
 
2953
                    isinstance(target._format, richroot))
 
2954
        except AttributeError:
 
2955
            return False
 
2956
 
 
2957
    @needs_write_lock
 
2958
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
2959
        """See InterRepository.fetch()."""
 
2960
        from bzrlib.fetch import Knit1to2Fetcher
 
2961
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
2962
               self.source, self.source._format, self.target, 
 
2963
               self.target._format)
 
2964
        f = Knit1to2Fetcher(to_repository=self.target,
 
2965
                            from_repository=self.source,
 
2966
                            last_revision=revision_id,
 
2967
                            pb=pb, find_ghosts=find_ghosts)
 
2968
        return f.count_copied, f.failed_revisions
 
2969
 
 
2970
 
 
2971
class InterDifferingSerializer(InterKnitRepo):
 
2972
 
 
2973
    @classmethod
 
2974
    def _get_repo_format_to_test(self):
 
2975
        return None
 
2976
 
 
2977
    @staticmethod
 
2978
    def is_compatible(source, target):
 
2979
        """Be compatible with Knit2 source and Knit3 target"""
 
2980
        if source.supports_rich_root() != target.supports_rich_root():
 
2981
            return False
 
2982
        # Ideally, we'd support fetching if the source had no tree references
 
2983
        # even if it supported them...
 
2984
        if (getattr(source, '_format.supports_tree_reference', False) and
 
2985
            not getattr(target, '_format.supports_tree_reference', False)):
 
2986
            return False
 
2987
        return True
 
2988
 
 
2989
    @needs_write_lock
 
2990
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
2991
        """See InterRepository.fetch()."""
 
2992
        revision_ids = self.target.search_missing_revision_ids(self.source,
 
2993
            revision_id, find_ghosts=find_ghosts).get_keys()
 
2994
        revision_ids = tsort.topo_sort(
 
2995
            self.source.get_graph().get_parent_map(revision_ids))
 
2996
        def revisions_iterator():
 
2997
            for current_revision_id in revision_ids:
 
2998
                revision = self.source.get_revision(current_revision_id)
 
2999
                tree = self.source.revision_tree(current_revision_id)
 
3000
                try:
 
3001
                    signature = self.source.get_signature_text(
 
3002
                        current_revision_id)
 
3003
                except errors.NoSuchRevision:
 
3004
                    signature = None
 
3005
                yield revision, tree, signature
 
3006
        if pb is None:
 
3007
            my_pb = ui.ui_factory.nested_progress_bar()
 
3008
            pb = my_pb
 
3009
        else:
 
3010
            my_pb = None
 
3011
        try:
 
3012
            install_revisions(self.target, revisions_iterator(),
 
3013
                              len(revision_ids), pb)
 
3014
        finally:
 
3015
            if my_pb is not None:
 
3016
                my_pb.finished()
 
3017
        return len(revision_ids), 0
 
3018
 
 
3019
 
 
3020
class InterOtherToRemote(InterRepository):
 
3021
 
 
3022
    def __init__(self, source, target):
 
3023
        InterRepository.__init__(self, source, target)
 
3024
        self._real_inter = None
 
3025
 
 
3026
    @staticmethod
 
3027
    def is_compatible(source, target):
 
3028
        if isinstance(target, remote.RemoteRepository):
 
3029
            return True
 
3030
        return False
 
3031
 
 
3032
    def _ensure_real_inter(self):
 
3033
        if self._real_inter is None:
 
3034
            self.target._ensure_real()
 
3035
            real_target = self.target._real_repository
 
3036
            self._real_inter = InterRepository.get(self.source, real_target)
 
3037
    
 
3038
    def copy_content(self, revision_id=None):
 
3039
        self._ensure_real_inter()
 
3040
        self._real_inter.copy_content(revision_id=revision_id)
 
3041
 
 
3042
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
3043
        self._ensure_real_inter()
 
3044
        return self._real_inter.fetch(revision_id=revision_id, pb=pb,
 
3045
            find_ghosts=find_ghosts)
 
3046
 
 
3047
    @classmethod
 
3048
    def _get_repo_format_to_test(self):
 
3049
        return None
 
3050
 
 
3051
 
 
3052
class InterRemoteToOther(InterRepository):
 
3053
 
 
3054
    def __init__(self, source, target):
 
3055
        InterRepository.__init__(self, source, target)
 
3056
        self._real_inter = None
 
3057
 
 
3058
    @staticmethod
 
3059
    def is_compatible(source, target):
 
3060
        if not isinstance(source, remote.RemoteRepository):
 
3061
            return False
 
3062
        # Is source's model compatible with target's model?
 
3063
        source._ensure_real()
 
3064
        real_source = source._real_repository
 
3065
        if isinstance(real_source, remote.RemoteRepository):
 
3066
            raise NotImplementedError(
 
3067
                "We don't support remote repos backed by remote repos yet.")
 
3068
        return InterRepository._same_model(real_source, target)
 
3069
 
 
3070
    def _ensure_real_inter(self):
 
3071
        if self._real_inter is None:
 
3072
            self.source._ensure_real()
 
3073
            real_source = self.source._real_repository
 
3074
            self._real_inter = InterRepository.get(real_source, self.target)
 
3075
    
 
3076
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
3077
        self._ensure_real_inter()
 
3078
        return self._real_inter.fetch(revision_id=revision_id, pb=pb,
 
3079
            find_ghosts=find_ghosts)
 
3080
 
 
3081
    def copy_content(self, revision_id=None):
 
3082
        self._ensure_real_inter()
 
3083
        self._real_inter.copy_content(revision_id=revision_id)
 
3084
 
 
3085
    @classmethod
 
3086
    def _get_repo_format_to_test(self):
 
3087
        return None
 
3088
 
 
3089
 
 
3090
 
 
3091
InterRepository.register_optimiser(InterDifferingSerializer)
 
3092
InterRepository.register_optimiser(InterSameDataRepository)
 
3093
InterRepository.register_optimiser(InterWeaveRepo)
 
3094
InterRepository.register_optimiser(InterKnitRepo)
 
3095
InterRepository.register_optimiser(InterModel1and2)
 
3096
InterRepository.register_optimiser(InterKnit1and2)
 
3097
InterRepository.register_optimiser(InterPackRepo)
 
3098
InterRepository.register_optimiser(InterOtherToRemote)
 
3099
InterRepository.register_optimiser(InterRemoteToOther)
 
3100
 
 
3101
 
 
3102
class CopyConverter(object):
 
3103
    """A repository conversion tool which just performs a copy of the content.
 
3104
    
 
3105
    This is slow but quite reliable.
 
3106
    """
 
3107
 
 
3108
    def __init__(self, target_format):
 
3109
        """Create a CopyConverter.
 
3110
 
 
3111
        :param target_format: The format the resulting repository should be.
 
3112
        """
 
3113
        self.target_format = target_format
 
3114
        
 
3115
    def convert(self, repo, pb):
 
3116
        """Perform the conversion of to_convert, giving feedback via pb.
 
3117
 
 
3118
        :param to_convert: The disk object to convert.
 
3119
        :param pb: a progress bar to use for progress information.
 
3120
        """
 
3121
        self.pb = pb
 
3122
        self.count = 0
 
3123
        self.total = 4
 
3124
        # this is only useful with metadir layouts - separated repo content.
 
3125
        # trigger an assertion if not such
 
3126
        repo._format.get_format_string()
 
3127
        self.repo_dir = repo.bzrdir
 
3128
        self.step('Moving repository to repository.backup')
 
3129
        self.repo_dir.transport.move('repository', 'repository.backup')
 
3130
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
 
3131
        repo._format.check_conversion_target(self.target_format)
 
3132
        self.source_repo = repo._format.open(self.repo_dir,
 
3133
            _found=True,
 
3134
            _override_transport=backup_transport)
 
3135
        self.step('Creating new repository')
 
3136
        converted = self.target_format.initialize(self.repo_dir,
 
3137
                                                  self.source_repo.is_shared())
 
3138
        converted.lock_write()
 
3139
        try:
 
3140
            self.step('Copying content into repository.')
 
3141
            self.source_repo.copy_content_into(converted)
 
3142
        finally:
 
3143
            converted.unlock()
 
3144
        self.step('Deleting old repository content.')
 
3145
        self.repo_dir.transport.delete_tree('repository.backup')
 
3146
        self.pb.note('repository converted')
 
3147
 
 
3148
    def step(self, message):
 
3149
        """Update the pb by a step."""
 
3150
        self.count +=1
 
3151
        self.pb.update(message, self.count, self.total)
 
3152
 
 
3153
 
 
3154
_unescape_map = {
 
3155
    'apos':"'",
 
3156
    'quot':'"',
 
3157
    'amp':'&',
 
3158
    'lt':'<',
 
3159
    'gt':'>'
 
3160
}
 
3161
 
 
3162
 
 
3163
def _unescaper(match, _map=_unescape_map):
 
3164
    code = match.group(1)
 
3165
    try:
 
3166
        return _map[code]
 
3167
    except KeyError:
 
3168
        if not code.startswith('#'):
 
3169
            raise
 
3170
        return unichr(int(code[1:])).encode('utf8')
 
3171
 
 
3172
 
 
3173
_unescape_re = None
 
3174
 
 
3175
 
 
3176
def _unescape_xml(data):
 
3177
    """Unescape predefined XML entities in a string of data."""
 
3178
    global _unescape_re
 
3179
    if _unescape_re is None:
 
3180
        _unescape_re = re.compile('\&([^;]*);')
 
3181
    return _unescape_re.sub(_unescaper, data)
 
3182
 
 
3183
 
 
3184
class _VersionedFileChecker(object):
 
3185
 
 
3186
    def __init__(self, repository):
 
3187
        self.repository = repository
 
3188
        self.text_index = self.repository._generate_text_key_index()
 
3189
    
 
3190
    def calculate_file_version_parents(self, text_key):
 
3191
        """Calculate the correct parents for a file version according to
 
3192
        the inventories.
 
3193
        """
 
3194
        parent_keys = self.text_index[text_key]
 
3195
        if parent_keys == [_mod_revision.NULL_REVISION]:
 
3196
            return ()
 
3197
        return tuple(parent_keys)
 
3198
 
 
3199
    def check_file_version_parents(self, texts, progress_bar=None):
 
3200
        """Check the parents stored in a versioned file are correct.
 
3201
 
 
3202
        It also detects file versions that are not referenced by their
 
3203
        corresponding revision's inventory.
 
3204
 
 
3205
        :returns: A tuple of (wrong_parents, dangling_file_versions).
 
3206
            wrong_parents is a dict mapping {revision_id: (stored_parents,
 
3207
            correct_parents)} for each revision_id where the stored parents
 
3208
            are not correct.  dangling_file_versions is a set of (file_id,
 
3209
            revision_id) tuples for versions that are present in this versioned
 
3210
            file, but not used by the corresponding inventory.
 
3211
        """
 
3212
        wrong_parents = {}
 
3213
        self.file_ids = set([file_id for file_id, _ in
 
3214
            self.text_index.iterkeys()])
 
3215
        # text keys is now grouped by file_id
 
3216
        n_weaves = len(self.file_ids)
 
3217
        files_in_revisions = {}
 
3218
        revisions_of_files = {}
 
3219
        n_versions = len(self.text_index)
 
3220
        progress_bar.update('loading text store', 0, n_versions)
 
3221
        parent_map = self.repository.texts.get_parent_map(self.text_index)
 
3222
        # On unlistable transports this could well be empty/error...
 
3223
        text_keys = self.repository.texts.keys()
 
3224
        unused_keys = frozenset(text_keys) - set(self.text_index)
 
3225
        for num, key in enumerate(self.text_index.iterkeys()):
 
3226
            if progress_bar is not None:
 
3227
                progress_bar.update('checking text graph', num, n_versions)
 
3228
            correct_parents = self.calculate_file_version_parents(key)
 
3229
            try:
 
3230
                knit_parents = parent_map[key]
 
3231
            except errors.RevisionNotPresent:
 
3232
                # Missing text!
 
3233
                knit_parents = None
 
3234
            if correct_parents != knit_parents:
 
3235
                wrong_parents[key] = (knit_parents, correct_parents)
 
3236
        return wrong_parents, unused_keys
 
3237
 
 
3238
 
 
3239
def _old_get_graph(repository, revision_id):
 
3240
    """DO NOT USE. That is all. I'm serious."""
 
3241
    graph = repository.get_graph()
 
3242
    revision_graph = dict(((key, value) for key, value in
 
3243
        graph.iter_ancestry([revision_id]) if value is not None))
 
3244
    return _strip_NULL_ghosts(revision_graph)
 
3245
 
 
3246
 
 
3247
def _strip_NULL_ghosts(revision_graph):
 
3248
    """Also don't use this. more compatibility code for unmigrated clients."""
 
3249
    # Filter ghosts, and null:
 
3250
    if _mod_revision.NULL_REVISION in revision_graph:
 
3251
        del revision_graph[_mod_revision.NULL_REVISION]
 
3252
    for key, parents in revision_graph.items():
 
3253
        revision_graph[key] = tuple(parent for parent in parents if parent
 
3254
            in revision_graph)
 
3255
    return revision_graph