/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: John Arbash Meinel
  • Date: 2009-08-17 22:11:06 UTC
  • mto: This revision was merged to the branch mainline in revision 4629.
  • Revision ID: john@arbash-meinel.com-20090817221106-snef4s9g2f7zue60
Finish implementation tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
from bzrlib.lazy_import import lazy_import
 
18
lazy_import(globals(), """
 
19
import cStringIO
 
20
import re
 
21
import time
 
22
 
 
23
from bzrlib import (
 
24
    bzrdir,
 
25
    check,
 
26
    chk_map,
 
27
    debug,
 
28
    errors,
 
29
    fifo_cache,
 
30
    generate_ids,
 
31
    gpg,
 
32
    graph,
 
33
    inventory,
 
34
    inventory_delta,
 
35
    lazy_regex,
 
36
    lockable_files,
 
37
    lockdir,
 
38
    lru_cache,
 
39
    osutils,
 
40
    revision as _mod_revision,
 
41
    symbol_versioning,
 
42
    tsort,
 
43
    ui,
 
44
    versionedfile,
 
45
    )
 
46
from bzrlib.bundle import serializer
 
47
from bzrlib.revisiontree import RevisionTree
 
48
from bzrlib.store.versioned import VersionedFileStore
 
49
from bzrlib.testament import Testament
 
50
""")
 
51
 
 
52
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
53
from bzrlib.inter import InterObject
 
54
from bzrlib.inventory import (
 
55
    Inventory,
 
56
    InventoryDirectory,
 
57
    ROOT_ID,
 
58
    entry_factory,
 
59
    )
 
60
from bzrlib import registry
 
61
from bzrlib.trace import (
 
62
    log_exception_quietly, note, mutter, mutter_callsite, warning)
 
63
 
 
64
 
 
65
# Old formats display a warning, but only once
 
66
_deprecation_warning_done = False
 
67
 
 
68
 
 
69
class CommitBuilder(object):
 
70
    """Provides an interface to build up a commit.
 
71
 
 
72
    This allows describing a tree to be committed without needing to
 
73
    know the internals of the format of the repository.
 
74
    """
 
75
 
 
76
    # all clients should supply tree roots.
 
77
    record_root_entry = True
 
78
    # the default CommitBuilder does not manage trees whose root is versioned.
 
79
    _versioned_root = False
 
80
 
 
81
    def __init__(self, repository, parents, config, timestamp=None,
 
82
                 timezone=None, committer=None, revprops=None,
 
83
                 revision_id=None):
 
84
        """Initiate a CommitBuilder.
 
85
 
 
86
        :param repository: Repository to commit to.
 
87
        :param parents: Revision ids of the parents of the new revision.
 
88
        :param config: Configuration to use.
 
89
        :param timestamp: Optional timestamp recorded for commit.
 
90
        :param timezone: Optional timezone for timestamp.
 
91
        :param committer: Optional committer to set for commit.
 
92
        :param revprops: Optional dictionary of revision properties.
 
93
        :param revision_id: Optional revision id.
 
94
        """
 
95
        self._config = config
 
96
 
 
97
        if committer is None:
 
98
            self._committer = self._config.username()
 
99
        else:
 
100
            self._committer = committer
 
101
 
 
102
        self.new_inventory = Inventory(None)
 
103
        self._new_revision_id = revision_id
 
104
        self.parents = parents
 
105
        self.repository = repository
 
106
 
 
107
        self._revprops = {}
 
108
        if revprops is not None:
 
109
            self._validate_revprops(revprops)
 
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
        self._basis_delta = []
 
125
        # API compatibility, older code that used CommitBuilder did not call
 
126
        # .record_delete(), which means the delta that is computed would not be
 
127
        # valid. Callers that will call record_delete() should call
 
128
        # .will_record_deletes() to indicate that.
 
129
        self._recording_deletes = False
 
130
        # memo'd check for no-op commits.
 
131
        self._any_changes = False
 
132
 
 
133
    def any_changes(self):
 
134
        """Return True if any entries were changed.
 
135
        
 
136
        This includes merge-only changes. It is the core for the --unchanged
 
137
        detection in commit.
 
138
 
 
139
        :return: True if any changes have occured.
 
140
        """
 
141
        return self._any_changes
 
142
 
 
143
    def _validate_unicode_text(self, text, context):
 
144
        """Verify things like commit messages don't have bogus characters."""
 
145
        if '\r' in text:
 
146
            raise ValueError('Invalid value for %s: %r' % (context, text))
 
147
 
 
148
    def _validate_revprops(self, revprops):
 
149
        for key, value in revprops.iteritems():
 
150
            # We know that the XML serializers do not round trip '\r'
 
151
            # correctly, so refuse to accept them
 
152
            if not isinstance(value, basestring):
 
153
                raise ValueError('revision property (%s) is not a valid'
 
154
                                 ' (unicode) string: %r' % (key, value))
 
155
            self._validate_unicode_text(value,
 
156
                                        'revision property (%s)' % (key,))
 
157
 
 
158
    def commit(self, message):
 
159
        """Make the actual commit.
 
160
 
 
161
        :return: The revision id of the recorded revision.
 
162
        """
 
163
        self._validate_unicode_text(message, 'commit message')
 
164
        rev = _mod_revision.Revision(
 
165
                       timestamp=self._timestamp,
 
166
                       timezone=self._timezone,
 
167
                       committer=self._committer,
 
168
                       message=message,
 
169
                       inventory_sha1=self.inv_sha1,
 
170
                       revision_id=self._new_revision_id,
 
171
                       properties=self._revprops)
 
172
        rev.parent_ids = self.parents
 
173
        self.repository.add_revision(self._new_revision_id, rev,
 
174
            self.new_inventory, self._config)
 
175
        self.repository.commit_write_group()
 
176
        return self._new_revision_id
 
177
 
 
178
    def abort(self):
 
179
        """Abort the commit that is being built.
 
180
        """
 
181
        self.repository.abort_write_group()
 
182
 
 
183
    def revision_tree(self):
 
184
        """Return the tree that was just committed.
 
185
 
 
186
        After calling commit() this can be called to get a RevisionTree
 
187
        representing the newly committed tree. This is preferred to
 
188
        calling Repository.revision_tree() because that may require
 
189
        deserializing the inventory, while we already have a copy in
 
190
        memory.
 
191
        """
 
192
        if self.new_inventory is None:
 
193
            self.new_inventory = self.repository.get_inventory(
 
194
                self._new_revision_id)
 
195
        return RevisionTree(self.repository, self.new_inventory,
 
196
            self._new_revision_id)
 
197
 
 
198
    def finish_inventory(self):
 
199
        """Tell the builder that the inventory is finished.
 
200
 
 
201
        :return: The inventory id in the repository, which can be used with
 
202
            repository.get_inventory.
 
203
        """
 
204
        if self.new_inventory is None:
 
205
            # an inventory delta was accumulated without creating a new
 
206
            # inventory.
 
207
            basis_id = self.basis_delta_revision
 
208
            self.inv_sha1 = self.repository.add_inventory_by_delta(
 
209
                basis_id, self._basis_delta, self._new_revision_id,
 
210
                self.parents)
 
211
        else:
 
212
            if self.new_inventory.root is None:
 
213
                raise AssertionError('Root entry should be supplied to'
 
214
                    ' record_entry_contents, as of bzr 0.10.')
 
215
                self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
 
216
            self.new_inventory.revision_id = self._new_revision_id
 
217
            self.inv_sha1 = self.repository.add_inventory(
 
218
                self._new_revision_id,
 
219
                self.new_inventory,
 
220
                self.parents
 
221
                )
 
222
        return self._new_revision_id
 
223
 
 
224
    def _gen_revision_id(self):
 
225
        """Return new revision-id."""
 
226
        return generate_ids.gen_revision_id(self._config.username(),
 
227
                                            self._timestamp)
 
228
 
 
229
    def _generate_revision_if_needed(self):
 
230
        """Create a revision id if None was supplied.
 
231
 
 
232
        If the repository can not support user-specified revision ids
 
233
        they should override this function and raise CannotSetRevisionId
 
234
        if _new_revision_id is not None.
 
235
 
 
236
        :raises: CannotSetRevisionId
 
237
        """
 
238
        if self._new_revision_id is None:
 
239
            self._new_revision_id = self._gen_revision_id()
 
240
            self.random_revid = True
 
241
        else:
 
242
            self.random_revid = False
 
243
 
 
244
    def _heads(self, file_id, revision_ids):
 
245
        """Calculate the graph heads for revision_ids in the graph of file_id.
 
246
 
 
247
        This can use either a per-file graph or a global revision graph as we
 
248
        have an identity relationship between the two graphs.
 
249
        """
 
250
        return self.__heads(revision_ids)
 
251
 
 
252
    def _check_root(self, ie, parent_invs, tree):
 
253
        """Helper for record_entry_contents.
 
254
 
 
255
        :param ie: An entry being added.
 
256
        :param parent_invs: The inventories of the parent revisions of the
 
257
            commit.
 
258
        :param tree: The tree that is being committed.
 
259
        """
 
260
        # In this revision format, root entries have no knit or weave When
 
261
        # serializing out to disk and back in root.revision is always
 
262
        # _new_revision_id
 
263
        ie.revision = self._new_revision_id
 
264
 
 
265
    def _require_root_change(self, tree):
 
266
        """Enforce an appropriate root object change.
 
267
 
 
268
        This is called once when record_iter_changes is called, if and only if
 
269
        the root was not in the delta calculated by record_iter_changes.
 
270
 
 
271
        :param tree: The tree which is being committed.
 
272
        """
 
273
        # NB: if there are no parents then this method is not called, so no
 
274
        # need to guard on parents having length.
 
275
        entry = entry_factory['directory'](tree.path2id(''), '',
 
276
            None)
 
277
        entry.revision = self._new_revision_id
 
278
        self._basis_delta.append(('', '', entry.file_id, entry))
 
279
 
 
280
    def _get_delta(self, ie, basis_inv, path):
 
281
        """Get a delta against the basis inventory for ie."""
 
282
        if ie.file_id not in basis_inv:
 
283
            # add
 
284
            result = (None, path, ie.file_id, ie)
 
285
            self._basis_delta.append(result)
 
286
            return result
 
287
        elif ie != basis_inv[ie.file_id]:
 
288
            # common but altered
 
289
            # TODO: avoid tis id2path call.
 
290
            result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
 
291
            self._basis_delta.append(result)
 
292
            return result
 
293
        else:
 
294
            # common, unaltered
 
295
            return None
 
296
 
 
297
    def get_basis_delta(self):
 
298
        """Return the complete inventory delta versus the basis inventory.
 
299
 
 
300
        This has been built up with the calls to record_delete and
 
301
        record_entry_contents. The client must have already called
 
302
        will_record_deletes() to indicate that they will be generating a
 
303
        complete delta.
 
304
 
 
305
        :return: An inventory delta, suitable for use with apply_delta, or
 
306
            Repository.add_inventory_by_delta, etc.
 
307
        """
 
308
        if not self._recording_deletes:
 
309
            raise AssertionError("recording deletes not activated.")
 
310
        return self._basis_delta
 
311
 
 
312
    def record_delete(self, path, file_id):
 
313
        """Record that a delete occured against a basis tree.
 
314
 
 
315
        This is an optional API - when used it adds items to the basis_delta
 
316
        being accumulated by the commit builder. It cannot be called unless the
 
317
        method will_record_deletes() has been called to inform the builder that
 
318
        a delta is being supplied.
 
319
 
 
320
        :param path: The path of the thing deleted.
 
321
        :param file_id: The file id that was deleted.
 
322
        """
 
323
        if not self._recording_deletes:
 
324
            raise AssertionError("recording deletes not activated.")
 
325
        delta = (path, None, file_id, None)
 
326
        self._basis_delta.append(delta)
 
327
        self._any_changes = True
 
328
        return delta
 
329
 
 
330
    def will_record_deletes(self):
 
331
        """Tell the commit builder that deletes are being notified.
 
332
 
 
333
        This enables the accumulation of an inventory delta; for the resulting
 
334
        commit to be valid, deletes against the basis MUST be recorded via
 
335
        builder.record_delete().
 
336
        """
 
337
        self._recording_deletes = True
 
338
        try:
 
339
            basis_id = self.parents[0]
 
340
        except IndexError:
 
341
            basis_id = _mod_revision.NULL_REVISION
 
342
        self.basis_delta_revision = basis_id
 
343
 
 
344
    def record_entry_contents(self, ie, parent_invs, path, tree,
 
345
        content_summary):
 
346
        """Record the content of ie from tree into the commit if needed.
 
347
 
 
348
        Side effect: sets ie.revision when unchanged
 
349
 
 
350
        :param ie: An inventory entry present in the commit.
 
351
        :param parent_invs: The inventories of the parent revisions of the
 
352
            commit.
 
353
        :param path: The path the entry is at in the tree.
 
354
        :param tree: The tree which contains this entry and should be used to
 
355
            obtain content.
 
356
        :param content_summary: Summary data from the tree about the paths
 
357
            content - stat, length, exec, sha/link target. This is only
 
358
            accessed when the entry has a revision of None - that is when it is
 
359
            a candidate to commit.
 
360
        :return: A tuple (change_delta, version_recorded, fs_hash).
 
361
            change_delta is an inventory_delta change for this entry against
 
362
            the basis tree of the commit, or None if no change occured against
 
363
            the basis tree.
 
364
            version_recorded is True if a new version of the entry has been
 
365
            recorded. For instance, committing a merge where a file was only
 
366
            changed on the other side will return (delta, False).
 
367
            fs_hash is either None, or the hash details for the path (currently
 
368
            a tuple of the contents sha1 and the statvalue returned by
 
369
            tree.get_file_with_stat()).
 
370
        """
 
371
        if self.new_inventory.root is None:
 
372
            if ie.parent_id is not None:
 
373
                raise errors.RootMissing()
 
374
            self._check_root(ie, parent_invs, tree)
 
375
        if ie.revision is None:
 
376
            kind = content_summary[0]
 
377
        else:
 
378
            # ie is carried over from a prior commit
 
379
            kind = ie.kind
 
380
        # XXX: repository specific check for nested tree support goes here - if
 
381
        # the repo doesn't want nested trees we skip it ?
 
382
        if (kind == 'tree-reference' and
 
383
            not self.repository._format.supports_tree_reference):
 
384
            # mismatch between commit builder logic and repository:
 
385
            # this needs the entry creation pushed down into the builder.
 
386
            raise NotImplementedError('Missing repository subtree support.')
 
387
        self.new_inventory.add(ie)
 
388
 
 
389
        # TODO: slow, take it out of the inner loop.
 
390
        try:
 
391
            basis_inv = parent_invs[0]
 
392
        except IndexError:
 
393
            basis_inv = Inventory(root_id=None)
 
394
 
 
395
        # ie.revision is always None if the InventoryEntry is considered
 
396
        # for committing. We may record the previous parents revision if the
 
397
        # content is actually unchanged against a sole head.
 
398
        if ie.revision is not None:
 
399
            if not self._versioned_root and path == '':
 
400
                # repositories that do not version the root set the root's
 
401
                # revision to the new commit even when no change occurs (more
 
402
                # specifically, they do not record a revision on the root; and
 
403
                # the rev id is assigned to the root during deserialisation -
 
404
                # this masks when a change may have occurred against the basis.
 
405
                # To match this we always issue a delta, because the revision
 
406
                # of the root will always be changing.
 
407
                if ie.file_id in basis_inv:
 
408
                    delta = (basis_inv.id2path(ie.file_id), path,
 
409
                        ie.file_id, ie)
 
410
                else:
 
411
                    # add
 
412
                    delta = (None, path, ie.file_id, ie)
 
413
                self._basis_delta.append(delta)
 
414
                return delta, False, None
 
415
            else:
 
416
                # we don't need to commit this, because the caller already
 
417
                # determined that an existing revision of this file is
 
418
                # appropriate. If its not being considered for committing then
 
419
                # it and all its parents to the root must be unaltered so
 
420
                # no-change against the basis.
 
421
                if ie.revision == self._new_revision_id:
 
422
                    raise AssertionError("Impossible situation, a skipped "
 
423
                        "inventory entry (%r) claims to be modified in this "
 
424
                        "commit (%r).", (ie, self._new_revision_id))
 
425
                return None, False, None
 
426
        # XXX: Friction: parent_candidates should return a list not a dict
 
427
        #      so that we don't have to walk the inventories again.
 
428
        parent_candiate_entries = ie.parent_candidates(parent_invs)
 
429
        head_set = self._heads(ie.file_id, parent_candiate_entries.keys())
 
430
        heads = []
 
431
        for inv in parent_invs:
 
432
            if ie.file_id in inv:
 
433
                old_rev = inv[ie.file_id].revision
 
434
                if old_rev in head_set:
 
435
                    heads.append(inv[ie.file_id].revision)
 
436
                    head_set.remove(inv[ie.file_id].revision)
 
437
 
 
438
        store = False
 
439
        # now we check to see if we need to write a new record to the
 
440
        # file-graph.
 
441
        # We write a new entry unless there is one head to the ancestors, and
 
442
        # the kind-derived content is unchanged.
 
443
 
 
444
        # Cheapest check first: no ancestors, or more the one head in the
 
445
        # ancestors, we write a new node.
 
446
        if len(heads) != 1:
 
447
            store = True
 
448
        if not store:
 
449
            # There is a single head, look it up for comparison
 
450
            parent_entry = parent_candiate_entries[heads[0]]
 
451
            # if the non-content specific data has changed, we'll be writing a
 
452
            # node:
 
453
            if (parent_entry.parent_id != ie.parent_id or
 
454
                parent_entry.name != ie.name):
 
455
                store = True
 
456
        # now we need to do content specific checks:
 
457
        if not store:
 
458
            # if the kind changed the content obviously has
 
459
            if kind != parent_entry.kind:
 
460
                store = True
 
461
        # Stat cache fingerprint feedback for the caller - None as we usually
 
462
        # don't generate one.
 
463
        fingerprint = None
 
464
        if kind == 'file':
 
465
            if content_summary[2] is None:
 
466
                raise ValueError("Files must not have executable = None")
 
467
            if not store:
 
468
                if (# if the file length changed we have to store:
 
469
                    parent_entry.text_size != content_summary[1] or
 
470
                    # if the exec bit has changed we have to store:
 
471
                    parent_entry.executable != content_summary[2]):
 
472
                    store = True
 
473
                elif parent_entry.text_sha1 == content_summary[3]:
 
474
                    # all meta and content is unchanged (using a hash cache
 
475
                    # hit to check the sha)
 
476
                    ie.revision = parent_entry.revision
 
477
                    ie.text_size = parent_entry.text_size
 
478
                    ie.text_sha1 = parent_entry.text_sha1
 
479
                    ie.executable = parent_entry.executable
 
480
                    return self._get_delta(ie, basis_inv, path), False, None
 
481
                else:
 
482
                    # Either there is only a hash change(no hash cache entry,
 
483
                    # or same size content change), or there is no change on
 
484
                    # this file at all.
 
485
                    # Provide the parent's hash to the store layer, so that the
 
486
                    # content is unchanged we will not store a new node.
 
487
                    nostore_sha = parent_entry.text_sha1
 
488
            if store:
 
489
                # We want to record a new node regardless of the presence or
 
490
                # absence of a content change in the file.
 
491
                nostore_sha = None
 
492
            ie.executable = content_summary[2]
 
493
            file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
 
494
            try:
 
495
                text = file_obj.read()
 
496
            finally:
 
497
                file_obj.close()
 
498
            try:
 
499
                ie.text_sha1, ie.text_size = self._add_text_to_weave(
 
500
                    ie.file_id, text, heads, nostore_sha)
 
501
                # Let the caller know we generated a stat fingerprint.
 
502
                fingerprint = (ie.text_sha1, stat_value)
 
503
            except errors.ExistingContent:
 
504
                # Turns out that the file content was unchanged, and we were
 
505
                # only going to store a new node if it was changed. Carry over
 
506
                # the entry.
 
507
                ie.revision = parent_entry.revision
 
508
                ie.text_size = parent_entry.text_size
 
509
                ie.text_sha1 = parent_entry.text_sha1
 
510
                ie.executable = parent_entry.executable
 
511
                return self._get_delta(ie, basis_inv, path), False, None
 
512
        elif kind == 'directory':
 
513
            if not store:
 
514
                # all data is meta here, nothing specific to directory, so
 
515
                # carry over:
 
516
                ie.revision = parent_entry.revision
 
517
                return self._get_delta(ie, basis_inv, path), False, None
 
518
            self._add_text_to_weave(ie.file_id, '', heads, None)
 
519
        elif kind == 'symlink':
 
520
            current_link_target = content_summary[3]
 
521
            if not store:
 
522
                # symlink target is not generic metadata, check if it has
 
523
                # changed.
 
524
                if current_link_target != parent_entry.symlink_target:
 
525
                    store = True
 
526
            if not store:
 
527
                # unchanged, carry over.
 
528
                ie.revision = parent_entry.revision
 
529
                ie.symlink_target = parent_entry.symlink_target
 
530
                return self._get_delta(ie, basis_inv, path), False, None
 
531
            ie.symlink_target = current_link_target
 
532
            self._add_text_to_weave(ie.file_id, '', heads, None)
 
533
        elif kind == 'tree-reference':
 
534
            if not store:
 
535
                if content_summary[3] != parent_entry.reference_revision:
 
536
                    store = True
 
537
            if not store:
 
538
                # unchanged, carry over.
 
539
                ie.reference_revision = parent_entry.reference_revision
 
540
                ie.revision = parent_entry.revision
 
541
                return self._get_delta(ie, basis_inv, path), False, None
 
542
            ie.reference_revision = content_summary[3]
 
543
            self._add_text_to_weave(ie.file_id, '', heads, None)
 
544
        else:
 
545
            raise NotImplementedError('unknown kind')
 
546
        ie.revision = self._new_revision_id
 
547
        self._any_changes = True
 
548
        return self._get_delta(ie, basis_inv, path), True, fingerprint
 
549
 
 
550
    def record_iter_changes(self, tree, basis_revision_id, iter_changes,
 
551
        _entry_factory=entry_factory):
 
552
        """Record a new tree via iter_changes.
 
553
 
 
554
        :param tree: The tree to obtain text contents from for changed objects.
 
555
        :param basis_revision_id: The revision id of the tree the iter_changes
 
556
            has been generated against. Currently assumed to be the same
 
557
            as self.parents[0] - if it is not, errors may occur.
 
558
        :param iter_changes: An iter_changes iterator with the changes to apply
 
559
            to basis_revision_id. The iterator must not include any items with
 
560
            a current kind of None - missing items must be either filtered out
 
561
            or errored-on beefore record_iter_changes sees the item.
 
562
        :param _entry_factory: Private method to bind entry_factory locally for
 
563
            performance.
 
564
        :return: A generator of (file_id, relpath, fs_hash) tuples for use with
 
565
            tree._observed_sha1.
 
566
        """
 
567
        # Create an inventory delta based on deltas between all the parents and
 
568
        # deltas between all the parent inventories. We use inventory delta's 
 
569
        # between the inventory objects because iter_changes masks
 
570
        # last-changed-field only changes.
 
571
        # Working data:
 
572
        # file_id -> change map, change is fileid, paths, changed, versioneds,
 
573
        # parents, names, kinds, executables
 
574
        merged_ids = {}
 
575
        # {file_id -> revision_id -> inventory entry, for entries in parent
 
576
        # trees that are not parents[0]
 
577
        parent_entries = {}
 
578
        ghost_basis = False
 
579
        try:
 
580
            revtrees = list(self.repository.revision_trees(self.parents))
 
581
        except errors.NoSuchRevision:
 
582
            # one or more ghosts, slow path.
 
583
            revtrees = []
 
584
            for revision_id in self.parents:
 
585
                try:
 
586
                    revtrees.append(self.repository.revision_tree(revision_id))
 
587
                except errors.NoSuchRevision:
 
588
                    if not revtrees:
 
589
                        basis_revision_id = _mod_revision.NULL_REVISION
 
590
                        ghost_basis = True
 
591
                    revtrees.append(self.repository.revision_tree(
 
592
                        _mod_revision.NULL_REVISION))
 
593
        # The basis inventory from a repository 
 
594
        if revtrees:
 
595
            basis_inv = revtrees[0].inventory
 
596
        else:
 
597
            basis_inv = self.repository.revision_tree(
 
598
                _mod_revision.NULL_REVISION).inventory
 
599
        if len(self.parents) > 0:
 
600
            if basis_revision_id != self.parents[0] and not ghost_basis:
 
601
                raise Exception(
 
602
                    "arbitrary basis parents not yet supported with merges")
 
603
            for revtree in revtrees[1:]:
 
604
                for change in revtree.inventory._make_delta(basis_inv):
 
605
                    if change[1] is None:
 
606
                        # Not present in this parent.
 
607
                        continue
 
608
                    if change[2] not in merged_ids:
 
609
                        if change[0] is not None:
 
610
                            basis_entry = basis_inv[change[2]]
 
611
                            merged_ids[change[2]] = [
 
612
                                # basis revid
 
613
                                basis_entry.revision,
 
614
                                # new tree revid
 
615
                                change[3].revision]
 
616
                            parent_entries[change[2]] = {
 
617
                                # basis parent
 
618
                                basis_entry.revision:basis_entry,
 
619
                                # this parent 
 
620
                                change[3].revision:change[3],
 
621
                                }
 
622
                        else:
 
623
                            merged_ids[change[2]] = [change[3].revision]
 
624
                            parent_entries[change[2]] = {change[3].revision:change[3]}
 
625
                    else:
 
626
                        merged_ids[change[2]].append(change[3].revision)
 
627
                        parent_entries[change[2]][change[3].revision] = change[3]
 
628
        else:
 
629
            merged_ids = {}
 
630
        # Setup the changes from the tree:
 
631
        # changes maps file_id -> (change, [parent revision_ids])
 
632
        changes= {}
 
633
        for change in iter_changes:
 
634
            # This probably looks up in basis_inv way to much.
 
635
            if change[1][0] is not None:
 
636
                head_candidate = [basis_inv[change[0]].revision]
 
637
            else:
 
638
                head_candidate = []
 
639
            changes[change[0]] = change, merged_ids.get(change[0],
 
640
                head_candidate)
 
641
        unchanged_merged = set(merged_ids) - set(changes)
 
642
        # Extend the changes dict with synthetic changes to record merges of
 
643
        # texts.
 
644
        for file_id in unchanged_merged:
 
645
            # Record a merged version of these items that did not change vs the
 
646
            # basis. This can be either identical parallel changes, or a revert
 
647
            # of a specific file after a merge. The recorded content will be
 
648
            # that of the current tree (which is the same as the basis), but
 
649
            # the per-file graph will reflect a merge.
 
650
            # NB:XXX: We are reconstructing path information we had, this
 
651
            # should be preserved instead.
 
652
            # inv delta  change: (file_id, (path_in_source, path_in_target),
 
653
            #   changed_content, versioned, parent, name, kind,
 
654
            #   executable)
 
655
            try:
 
656
                basis_entry = basis_inv[file_id]
 
657
            except errors.NoSuchId:
 
658
                # a change from basis->some_parents but file_id isn't in basis
 
659
                # so was new in the merge, which means it must have changed
 
660
                # from basis -> current, and as it hasn't the add was reverted
 
661
                # by the user. So we discard this change.
 
662
                pass
 
663
            else:
 
664
                change = (file_id,
 
665
                    (basis_inv.id2path(file_id), tree.id2path(file_id)),
 
666
                    False, (True, True),
 
667
                    (basis_entry.parent_id, basis_entry.parent_id),
 
668
                    (basis_entry.name, basis_entry.name),
 
669
                    (basis_entry.kind, basis_entry.kind),
 
670
                    (basis_entry.executable, basis_entry.executable))
 
671
                changes[file_id] = (change, merged_ids[file_id])
 
672
        # changes contains tuples with the change and a set of inventory
 
673
        # candidates for the file.
 
674
        # inv delta is:
 
675
        # old_path, new_path, file_id, new_inventory_entry
 
676
        seen_root = False # Is the root in the basis delta?
 
677
        inv_delta = self._basis_delta
 
678
        modified_rev = self._new_revision_id
 
679
        for change, head_candidates in changes.values():
 
680
            if change[3][1]: # versioned in target.
 
681
                # Several things may be happening here:
 
682
                # We may have a fork in the per-file graph
 
683
                #  - record a change with the content from tree
 
684
                # We may have a change against < all trees  
 
685
                #  - carry over the tree that hasn't changed
 
686
                # We may have a change against all trees
 
687
                #  - record the change with the content from tree
 
688
                kind = change[6][1]
 
689
                file_id = change[0]
 
690
                entry = _entry_factory[kind](file_id, change[5][1],
 
691
                    change[4][1])
 
692
                head_set = self._heads(change[0], set(head_candidates))
 
693
                heads = []
 
694
                # Preserve ordering.
 
695
                for head_candidate in head_candidates:
 
696
                    if head_candidate in head_set:
 
697
                        heads.append(head_candidate)
 
698
                        head_set.remove(head_candidate)
 
699
                carried_over = False
 
700
                if len(heads) == 1:
 
701
                    # Could be a carry-over situation:
 
702
                    parent_entry_revs = parent_entries.get(file_id, None)
 
703
                    if parent_entry_revs:
 
704
                        parent_entry = parent_entry_revs.get(heads[0], None)
 
705
                    else:
 
706
                        parent_entry = None
 
707
                    if parent_entry is None:
 
708
                        # The parent iter_changes was called against is the one
 
709
                        # that is the per-file head, so any change is relevant
 
710
                        # iter_changes is valid.
 
711
                        carry_over_possible = False
 
712
                    else:
 
713
                        # could be a carry over situation
 
714
                        # A change against the basis may just indicate a merge,
 
715
                        # we need to check the content against the source of the
 
716
                        # merge to determine if it was changed after the merge
 
717
                        # or carried over.
 
718
                        if (parent_entry.kind != entry.kind or
 
719
                            parent_entry.parent_id != entry.parent_id or
 
720
                            parent_entry.name != entry.name):
 
721
                            # Metadata common to all entries has changed
 
722
                            # against per-file parent
 
723
                            carry_over_possible = False
 
724
                        else:
 
725
                            carry_over_possible = True
 
726
                        # per-type checks for changes against the parent_entry
 
727
                        # are done below.
 
728
                else:
 
729
                    # Cannot be a carry-over situation
 
730
                    carry_over_possible = False
 
731
                # Populate the entry in the delta
 
732
                if kind == 'file':
 
733
                    # XXX: There is still a small race here: If someone reverts the content of a file
 
734
                    # after iter_changes examines and decides it has changed,
 
735
                    # we will unconditionally record a new version even if some
 
736
                    # other process reverts it while commit is running (with
 
737
                    # the revert happening after iter_changes did it's
 
738
                    # examination).
 
739
                    if change[7][1]:
 
740
                        entry.executable = True
 
741
                    else:
 
742
                        entry.executable = False
 
743
                    if (carry_over_possible and
 
744
                        parent_entry.executable == entry.executable):
 
745
                            # Check the file length, content hash after reading
 
746
                            # the file.
 
747
                            nostore_sha = parent_entry.text_sha1
 
748
                    else:
 
749
                        nostore_sha = None
 
750
                    file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
 
751
                    try:
 
752
                        text = file_obj.read()
 
753
                    finally:
 
754
                        file_obj.close()
 
755
                    try:
 
756
                        entry.text_sha1, entry.text_size = self._add_text_to_weave(
 
757
                            file_id, text, heads, nostore_sha)
 
758
                        yield file_id, change[1][1], (entry.text_sha1, stat_value)
 
759
                    except errors.ExistingContent:
 
760
                        # No content change against a carry_over parent
 
761
                        # Perhaps this should also yield a fs hash update?
 
762
                        carried_over = True
 
763
                        entry.text_size = parent_entry.text_size
 
764
                        entry.text_sha1 = parent_entry.text_sha1
 
765
                elif kind == 'symlink':
 
766
                    # Wants a path hint?
 
767
                    entry.symlink_target = tree.get_symlink_target(file_id)
 
768
                    if (carry_over_possible and
 
769
                        parent_entry.symlink_target == entry.symlink_target):
 
770
                        carried_over = True
 
771
                    else:
 
772
                        self._add_text_to_weave(change[0], '', heads, None)
 
773
                elif kind == 'directory':
 
774
                    if carry_over_possible:
 
775
                        carried_over = True
 
776
                    else:
 
777
                        # Nothing to set on the entry.
 
778
                        # XXX: split into the Root and nonRoot versions.
 
779
                        if change[1][1] != '' or self.repository.supports_rich_root():
 
780
                            self._add_text_to_weave(change[0], '', heads, None)
 
781
                elif kind == 'tree-reference':
 
782
                    if not self.repository._format.supports_tree_reference:
 
783
                        # This isn't quite sane as an error, but we shouldn't
 
784
                        # ever see this code path in practice: tree's don't
 
785
                        # permit references when the repo doesn't support tree
 
786
                        # references.
 
787
                        raise errors.UnsupportedOperation(tree.add_reference,
 
788
                            self.repository)
 
789
                    reference_revision = tree.get_reference_revision(change[0])
 
790
                    entry.reference_revision = reference_revision
 
791
                    if (carry_over_possible and
 
792
                        parent_entry.reference_revision == reference_revision):
 
793
                        carried_over = True
 
794
                    else:
 
795
                        self._add_text_to_weave(change[0], '', heads, None)
 
796
                else:
 
797
                    raise AssertionError('unknown kind %r' % kind)
 
798
                if not carried_over:
 
799
                    entry.revision = modified_rev
 
800
                else:
 
801
                    entry.revision = parent_entry.revision
 
802
            else:
 
803
                entry = None
 
804
            new_path = change[1][1]
 
805
            inv_delta.append((change[1][0], new_path, change[0], entry))
 
806
            if new_path == '':
 
807
                seen_root = True
 
808
        self.new_inventory = None
 
809
        if len(inv_delta):
 
810
            self._any_changes = True
 
811
        if not seen_root:
 
812
            # housekeeping root entry changes do not affect no-change commits.
 
813
            self._require_root_change(tree)
 
814
        self.basis_delta_revision = basis_revision_id
 
815
 
 
816
    def _add_text_to_weave(self, file_id, new_text, parents, nostore_sha):
 
817
        parent_keys = tuple([(file_id, parent) for parent in parents])
 
818
        return self.repository.texts._add_text(
 
819
            (file_id, self._new_revision_id), parent_keys, new_text,
 
820
            nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
 
821
 
 
822
 
 
823
class RootCommitBuilder(CommitBuilder):
 
824
    """This commitbuilder actually records the root id"""
 
825
 
 
826
    # the root entry gets versioned properly by this builder.
 
827
    _versioned_root = True
 
828
 
 
829
    def _check_root(self, ie, parent_invs, tree):
 
830
        """Helper for record_entry_contents.
 
831
 
 
832
        :param ie: An entry being added.
 
833
        :param parent_invs: The inventories of the parent revisions of the
 
834
            commit.
 
835
        :param tree: The tree that is being committed.
 
836
        """
 
837
 
 
838
    def _require_root_change(self, tree):
 
839
        """Enforce an appropriate root object change.
 
840
 
 
841
        This is called once when record_iter_changes is called, if and only if
 
842
        the root was not in the delta calculated by record_iter_changes.
 
843
 
 
844
        :param tree: The tree which is being committed.
 
845
        """
 
846
        # versioned roots do not change unless the tree found a change.
 
847
 
 
848
 
 
849
######################################################################
 
850
# Repositories
 
851
 
 
852
 
 
853
class Repository(object):
 
854
    """Repository holding history for one or more branches.
 
855
 
 
856
    The repository holds and retrieves historical information including
 
857
    revisions and file history.  It's normally accessed only by the Branch,
 
858
    which views a particular line of development through that history.
 
859
 
 
860
    The Repository builds on top of some byte storage facilies (the revisions,
 
861
    signatures, inventories, texts and chk_bytes attributes) and a Transport,
 
862
    which respectively provide byte storage and a means to access the (possibly
 
863
    remote) disk.
 
864
 
 
865
    The byte storage facilities are addressed via tuples, which we refer to
 
866
    as 'keys' throughout the code base. Revision_keys, inventory_keys and
 
867
    signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
 
868
    (file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
 
869
    byte string made up of a hash identifier and a hash value.
 
870
    We use this interface because it allows low friction with the underlying
 
871
    code that implements disk indices, network encoding and other parts of
 
872
    bzrlib.
 
873
 
 
874
    :ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
 
875
        the serialised revisions for the repository. This can be used to obtain
 
876
        revision graph information or to access raw serialised revisions.
 
877
        The result of trying to insert data into the repository via this store
 
878
        is undefined: it should be considered read-only except for implementors
 
879
        of repositories.
 
880
    :ivar signatures: A bzrlib.versionedfile.VersionedFiles instance containing
 
881
        the serialised signatures for the repository. This can be used to
 
882
        obtain access to raw serialised signatures.  The result of trying to
 
883
        insert data into the repository via this store is undefined: it should
 
884
        be considered read-only except for implementors of repositories.
 
885
    :ivar inventories: A bzrlib.versionedfile.VersionedFiles instance containing
 
886
        the serialised inventories for the repository. This can be used to
 
887
        obtain unserialised inventories.  The result of trying to insert data
 
888
        into the repository via this store is undefined: it should be
 
889
        considered read-only except for implementors of repositories.
 
890
    :ivar texts: A bzrlib.versionedfile.VersionedFiles instance containing the
 
891
        texts of files and directories for the repository. This can be used to
 
892
        obtain file texts or file graphs. Note that Repository.iter_file_bytes
 
893
        is usually a better interface for accessing file texts.
 
894
        The result of trying to insert data into the repository via this store
 
895
        is undefined: it should be considered read-only except for implementors
 
896
        of repositories.
 
897
    :ivar chk_bytes: A bzrlib.versionedfile.VersionedFiles instance containing
 
898
        any data the repository chooses to store or have indexed by its hash.
 
899
        The result of trying to insert data into the repository via this store
 
900
        is undefined: it should be considered read-only except for implementors
 
901
        of repositories.
 
902
    :ivar _transport: Transport for file access to repository, typically
 
903
        pointing to .bzr/repository.
 
904
    """
 
905
 
 
906
    # What class to use for a CommitBuilder. Often its simpler to change this
 
907
    # in a Repository class subclass rather than to override
 
908
    # get_commit_builder.
 
909
    _commit_builder_class = CommitBuilder
 
910
    # The search regex used by xml based repositories to determine what things
 
911
    # where changed in a single commit.
 
912
    _file_ids_altered_regex = lazy_regex.lazy_compile(
 
913
        r'file_id="(?P<file_id>[^"]+)"'
 
914
        r'.* revision="(?P<revision_id>[^"]+)"'
 
915
        )
 
916
 
 
917
    def abort_write_group(self, suppress_errors=False):
 
918
        """Commit the contents accrued within the current write group.
 
919
 
 
920
        :param suppress_errors: if true, abort_write_group will catch and log
 
921
            unexpected errors that happen during the abort, rather than
 
922
            allowing them to propagate.  Defaults to False.
 
923
 
 
924
        :seealso: start_write_group.
 
925
        """
 
926
        if self._write_group is not self.get_transaction():
 
927
            # has an unlock or relock occured ?
 
928
            if suppress_errors:
 
929
                mutter(
 
930
                '(suppressed) mismatched lock context and write group. %r, %r',
 
931
                self._write_group, self.get_transaction())
 
932
                return
 
933
            raise errors.BzrError(
 
934
                'mismatched lock context and write group. %r, %r' %
 
935
                (self._write_group, self.get_transaction()))
 
936
        try:
 
937
            self._abort_write_group()
 
938
        except Exception, exc:
 
939
            self._write_group = None
 
940
            if not suppress_errors:
 
941
                raise
 
942
            mutter('abort_write_group failed')
 
943
            log_exception_quietly()
 
944
            note('bzr: ERROR (ignored): %s', exc)
 
945
        self._write_group = None
 
946
 
 
947
    def _abort_write_group(self):
 
948
        """Template method for per-repository write group cleanup.
 
949
 
 
950
        This is called during abort before the write group is considered to be
 
951
        finished and should cleanup any internal state accrued during the write
 
952
        group. There is no requirement that data handed to the repository be
 
953
        *not* made available - this is not a rollback - but neither should any
 
954
        attempt be made to ensure that data added is fully commited. Abort is
 
955
        invoked when an error has occured so futher disk or network operations
 
956
        may not be possible or may error and if possible should not be
 
957
        attempted.
 
958
        """
 
959
 
 
960
    def add_fallback_repository(self, repository):
 
961
        """Add a repository to use for looking up data not held locally.
 
962
 
 
963
        :param repository: A repository.
 
964
        """
 
965
        if not self._format.supports_external_lookups:
 
966
            raise errors.UnstackableRepositoryFormat(self._format, self.base)
 
967
        if self.is_locked():
 
968
            # This repository will call fallback.unlock() when we transition to
 
969
            # the unlocked state, so we make sure to increment the lock count
 
970
            repository.lock_read()
 
971
        self._check_fallback_repository(repository)
 
972
        self._fallback_repositories.append(repository)
 
973
        self.texts.add_fallback_versioned_files(repository.texts)
 
974
        self.inventories.add_fallback_versioned_files(repository.inventories)
 
975
        self.revisions.add_fallback_versioned_files(repository.revisions)
 
976
        self.signatures.add_fallback_versioned_files(repository.signatures)
 
977
        if self.chk_bytes is not None:
 
978
            self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
 
979
 
 
980
    def _check_fallback_repository(self, repository):
 
981
        """Check that this repository can fallback to repository safely.
 
982
 
 
983
        Raise an error if not.
 
984
 
 
985
        :param repository: A repository to fallback to.
 
986
        """
 
987
        return InterRepository._assert_same_model(self, repository)
 
988
 
 
989
    def add_inventory(self, revision_id, inv, parents):
 
990
        """Add the inventory inv to the repository as revision_id.
 
991
 
 
992
        :param parents: The revision ids of the parents that revision_id
 
993
                        is known to have and are in the repository already.
 
994
 
 
995
        :returns: The validator(which is a sha1 digest, though what is sha'd is
 
996
            repository format specific) of the serialized inventory.
 
997
        """
 
998
        if not self.is_in_write_group():
 
999
            raise AssertionError("%r not in write group" % (self,))
 
1000
        _mod_revision.check_not_reserved_id(revision_id)
 
1001
        if not (inv.revision_id is None or inv.revision_id == revision_id):
 
1002
            raise AssertionError(
 
1003
                "Mismatch between inventory revision"
 
1004
                " id and insertion revid (%r, %r)"
 
1005
                % (inv.revision_id, revision_id))
 
1006
        if inv.root is None:
 
1007
            raise AssertionError()
 
1008
        return self._add_inventory_checked(revision_id, inv, parents)
 
1009
 
 
1010
    def _add_inventory_checked(self, revision_id, inv, parents):
 
1011
        """Add inv to the repository after checking the inputs.
 
1012
 
 
1013
        This function can be overridden to allow different inventory styles.
 
1014
 
 
1015
        :seealso: add_inventory, for the contract.
 
1016
        """
 
1017
        inv_lines = self._serialise_inventory_to_lines(inv)
 
1018
        return self._inventory_add_lines(revision_id, parents,
 
1019
            inv_lines, check_content=False)
 
1020
 
 
1021
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
 
1022
                               parents, basis_inv=None, propagate_caches=False):
 
1023
        """Add a new inventory expressed as a delta against another revision.
 
1024
 
 
1025
        See the inventory developers documentation for the theory behind
 
1026
        inventory deltas.
 
1027
 
 
1028
        :param basis_revision_id: The inventory id the delta was created
 
1029
            against. (This does not have to be a direct parent.)
 
1030
        :param delta: The inventory delta (see Inventory.apply_delta for
 
1031
            details).
 
1032
        :param new_revision_id: The revision id that the inventory is being
 
1033
            added for.
 
1034
        :param parents: The revision ids of the parents that revision_id is
 
1035
            known to have and are in the repository already. These are supplied
 
1036
            for repositories that depend on the inventory graph for revision
 
1037
            graph access, as well as for those that pun ancestry with delta
 
1038
            compression.
 
1039
        :param basis_inv: The basis inventory if it is already known,
 
1040
            otherwise None.
 
1041
        :param propagate_caches: If True, the caches for this inventory are
 
1042
          copied to and updated for the result if possible.
 
1043
 
 
1044
        :returns: (validator, new_inv)
 
1045
            The validator(which is a sha1 digest, though what is sha'd is
 
1046
            repository format specific) of the serialized inventory, and the
 
1047
            resulting inventory.
 
1048
        """
 
1049
        if not self.is_in_write_group():
 
1050
            raise AssertionError("%r not in write group" % (self,))
 
1051
        _mod_revision.check_not_reserved_id(new_revision_id)
 
1052
        basis_tree = self.revision_tree(basis_revision_id)
 
1053
        basis_tree.lock_read()
 
1054
        try:
 
1055
            # Note that this mutates the inventory of basis_tree, which not all
 
1056
            # inventory implementations may support: A better idiom would be to
 
1057
            # return a new inventory, but as there is no revision tree cache in
 
1058
            # repository this is safe for now - RBC 20081013
 
1059
            if basis_inv is None:
 
1060
                basis_inv = basis_tree.inventory
 
1061
            basis_inv.apply_delta(delta)
 
1062
            basis_inv.revision_id = new_revision_id
 
1063
            return (self.add_inventory(new_revision_id, basis_inv, parents),
 
1064
                    basis_inv)
 
1065
        finally:
 
1066
            basis_tree.unlock()
 
1067
 
 
1068
    def _inventory_add_lines(self, revision_id, parents, lines,
 
1069
        check_content=True):
 
1070
        """Store lines in inv_vf and return the sha1 of the inventory."""
 
1071
        parents = [(parent,) for parent in parents]
 
1072
        result = self.inventories.add_lines((revision_id,), parents, lines,
 
1073
            check_content=check_content)[0]
 
1074
        self.inventories._access.flush()
 
1075
        return result
 
1076
 
 
1077
    def add_revision(self, revision_id, rev, inv=None, config=None):
 
1078
        """Add rev to the revision store as revision_id.
 
1079
 
 
1080
        :param revision_id: the revision id to use.
 
1081
        :param rev: The revision object.
 
1082
        :param inv: The inventory for the revision. if None, it will be looked
 
1083
                    up in the inventory storer
 
1084
        :param config: If None no digital signature will be created.
 
1085
                       If supplied its signature_needed method will be used
 
1086
                       to determine if a signature should be made.
 
1087
        """
 
1088
        # TODO: jam 20070210 Shouldn't we check rev.revision_id and
 
1089
        #       rev.parent_ids?
 
1090
        _mod_revision.check_not_reserved_id(revision_id)
 
1091
        if config is not None and config.signature_needed():
 
1092
            if inv is None:
 
1093
                inv = self.get_inventory(revision_id)
 
1094
            plaintext = Testament(rev, inv).as_short_text()
 
1095
            self.store_revision_signature(
 
1096
                gpg.GPGStrategy(config), plaintext, revision_id)
 
1097
        # check inventory present
 
1098
        if not self.inventories.get_parent_map([(revision_id,)]):
 
1099
            if inv is None:
 
1100
                raise errors.WeaveRevisionNotPresent(revision_id,
 
1101
                                                     self.inventories)
 
1102
            else:
 
1103
                # yes, this is not suitable for adding with ghosts.
 
1104
                rev.inventory_sha1 = self.add_inventory(revision_id, inv,
 
1105
                                                        rev.parent_ids)
 
1106
        else:
 
1107
            key = (revision_id,)
 
1108
            rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
 
1109
        self._add_revision(rev)
 
1110
 
 
1111
    def _add_revision(self, revision):
 
1112
        text = self._serializer.write_revision_to_string(revision)
 
1113
        key = (revision.revision_id,)
 
1114
        parents = tuple((parent,) for parent in revision.parent_ids)
 
1115
        self.revisions.add_lines(key, parents, osutils.split_lines(text))
 
1116
 
 
1117
    def all_revision_ids(self):
 
1118
        """Returns a list of all the revision ids in the repository.
 
1119
 
 
1120
        This is conceptually deprecated because code should generally work on
 
1121
        the graph reachable from a particular revision, and ignore any other
 
1122
        revisions that might be present.  There is no direct replacement
 
1123
        method.
 
1124
        """
 
1125
        if 'evil' in debug.debug_flags:
 
1126
            mutter_callsite(2, "all_revision_ids is linear with history.")
 
1127
        return self._all_revision_ids()
 
1128
 
 
1129
    def _all_revision_ids(self):
 
1130
        """Returns a list of all the revision ids in the repository.
 
1131
 
 
1132
        These are in as much topological order as the underlying store can
 
1133
        present.
 
1134
        """
 
1135
        raise NotImplementedError(self._all_revision_ids)
 
1136
 
 
1137
    def break_lock(self):
 
1138
        """Break a lock if one is present from another instance.
 
1139
 
 
1140
        Uses the ui factory to ask for confirmation if the lock may be from
 
1141
        an active process.
 
1142
        """
 
1143
        self.control_files.break_lock()
 
1144
 
 
1145
    @needs_read_lock
 
1146
    def _eliminate_revisions_not_present(self, revision_ids):
 
1147
        """Check every revision id in revision_ids to see if we have it.
 
1148
 
 
1149
        Returns a set of the present revisions.
 
1150
        """
 
1151
        result = []
 
1152
        graph = self.get_graph()
 
1153
        parent_map = graph.get_parent_map(revision_ids)
 
1154
        # The old API returned a list, should this actually be a set?
 
1155
        return parent_map.keys()
 
1156
 
 
1157
    def _check_inventories(self, checker):
 
1158
        """Check the inventories found from the revision scan.
 
1159
        
 
1160
        This is responsible for verifying the sha1 of inventories and
 
1161
        creating a pending_keys set that covers data referenced by inventories.
 
1162
        """
 
1163
        bar = ui.ui_factory.nested_progress_bar()
 
1164
        try:
 
1165
            self._do_check_inventories(checker, bar)
 
1166
        finally:
 
1167
            bar.finished()
 
1168
 
 
1169
    def _do_check_inventories(self, checker, bar):
 
1170
        """Helper for _check_inventories."""
 
1171
        revno = 0
 
1172
        keys = {'chk_bytes':set(), 'inventories':set(), 'texts':set()}
 
1173
        kinds = ['chk_bytes', 'texts']
 
1174
        count = len(checker.pending_keys)
 
1175
        bar.update("inventories", 0, 2)
 
1176
        current_keys = checker.pending_keys
 
1177
        checker.pending_keys = {}
 
1178
        # Accumulate current checks.
 
1179
        for key in current_keys:
 
1180
            if key[0] != 'inventories' and key[0] not in kinds:
 
1181
                checker._report_items.append('unknown key type %r' % (key,))
 
1182
            keys[key[0]].add(key[1:])
 
1183
        if keys['inventories']:
 
1184
            # NB: output order *should* be roughly sorted - topo or
 
1185
            # inverse topo depending on repository - either way decent
 
1186
            # to just delta against. However, pre-CHK formats didn't
 
1187
            # try to optimise inventory layout on disk. As such the
 
1188
            # pre-CHK code path does not use inventory deltas.
 
1189
            last_object = None
 
1190
            for record in self.inventories.check(keys=keys['inventories']):
 
1191
                if record.storage_kind == 'absent':
 
1192
                    checker._report_items.append(
 
1193
                        'Missing inventory {%s}' % (record.key,))
 
1194
                else:
 
1195
                    last_object = self._check_record('inventories', record,
 
1196
                        checker, last_object,
 
1197
                        current_keys[('inventories',) + record.key])
 
1198
            del keys['inventories']
 
1199
        else:
 
1200
            return
 
1201
        bar.update("texts", 1)
 
1202
        while (checker.pending_keys or keys['chk_bytes']
 
1203
            or keys['texts']):
 
1204
            # Something to check.
 
1205
            current_keys = checker.pending_keys
 
1206
            checker.pending_keys = {}
 
1207
            # Accumulate current checks.
 
1208
            for key in current_keys:
 
1209
                if key[0] not in kinds:
 
1210
                    checker._report_items.append('unknown key type %r' % (key,))
 
1211
                keys[key[0]].add(key[1:])
 
1212
            # Check the outermost kind only - inventories || chk_bytes || texts
 
1213
            for kind in kinds:
 
1214
                if keys[kind]:
 
1215
                    last_object = None
 
1216
                    for record in getattr(self, kind).check(keys=keys[kind]):
 
1217
                        if record.storage_kind == 'absent':
 
1218
                            checker._report_items.append(
 
1219
                                'Missing inventory {%s}' % (record.key,))
 
1220
                        else:
 
1221
                            last_object = self._check_record(kind, record,
 
1222
                                checker, last_object, current_keys[(kind,) + record.key])
 
1223
                    keys[kind] = set()
 
1224
                    break
 
1225
 
 
1226
    def _check_record(self, kind, record, checker, last_object, item_data):
 
1227
        """Check a single text from this repository."""
 
1228
        if kind == 'inventories':
 
1229
            rev_id = record.key[0]
 
1230
            inv = self.deserialise_inventory(rev_id,
 
1231
                record.get_bytes_as('fulltext'))
 
1232
            if last_object is not None:
 
1233
                delta = inv._make_delta(last_object)
 
1234
                for old_path, path, file_id, ie in delta:
 
1235
                    if ie is None:
 
1236
                        continue
 
1237
                    ie.check(checker, rev_id, inv)
 
1238
            else:
 
1239
                for path, ie in inv.iter_entries():
 
1240
                    ie.check(checker, rev_id, inv)
 
1241
            if self._format.fast_deltas:
 
1242
                return inv
 
1243
        elif kind == 'chk_bytes':
 
1244
            # No code written to check chk_bytes for this repo format.
 
1245
            checker._report_items.append(
 
1246
                'unsupported key type chk_bytes for %s' % (record.key,))
 
1247
        elif kind == 'texts':
 
1248
            self._check_text(record, checker, item_data)
 
1249
        else:
 
1250
            checker._report_items.append(
 
1251
                'unknown key type %s for %s' % (kind, record.key))
 
1252
 
 
1253
    def _check_text(self, record, checker, item_data):
 
1254
        """Check a single text."""
 
1255
        # Check it is extractable.
 
1256
        # TODO: check length.
 
1257
        if record.storage_kind == 'chunked':
 
1258
            chunks = record.get_bytes_as(record.storage_kind)
 
1259
            sha1 = osutils.sha_strings(chunks)
 
1260
            length = sum(map(len, chunks))
 
1261
        else:
 
1262
            content = record.get_bytes_as('fulltext')
 
1263
            sha1 = osutils.sha_string(content)
 
1264
            length = len(content)
 
1265
        if item_data and sha1 != item_data[1]:
 
1266
            checker._report_items.append(
 
1267
                'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
 
1268
                (record.key, sha1, item_data[1], item_data[2]))
 
1269
 
 
1270
    @staticmethod
 
1271
    def create(a_bzrdir):
 
1272
        """Construct the current default format repository in a_bzrdir."""
 
1273
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
 
1274
 
 
1275
    def __init__(self, _format, a_bzrdir, control_files):
 
1276
        """instantiate a Repository.
 
1277
 
 
1278
        :param _format: The format of the repository on disk.
 
1279
        :param a_bzrdir: The BzrDir of the repository.
 
1280
 
 
1281
        In the future we will have a single api for all stores for
 
1282
        getting file texts, inventories and revisions, then
 
1283
        this construct will accept instances of those things.
 
1284
        """
 
1285
        super(Repository, self).__init__()
 
1286
        self._format = _format
 
1287
        # the following are part of the public API for Repository:
 
1288
        self.bzrdir = a_bzrdir
 
1289
        self.control_files = control_files
 
1290
        self._transport = control_files._transport
 
1291
        self.base = self._transport.base
 
1292
        # for tests
 
1293
        self._reconcile_does_inventory_gc = True
 
1294
        self._reconcile_fixes_text_parents = False
 
1295
        self._reconcile_backsup_inventory = True
 
1296
        # not right yet - should be more semantically clear ?
 
1297
        #
 
1298
        # TODO: make sure to construct the right store classes, etc, depending
 
1299
        # on whether escaping is required.
 
1300
        self._warn_if_deprecated()
 
1301
        self._write_group = None
 
1302
        # Additional places to query for data.
 
1303
        self._fallback_repositories = []
 
1304
        # An InventoryEntry cache, used during deserialization
 
1305
        self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
 
1306
 
 
1307
    def __repr__(self):
 
1308
        if self._fallback_repositories:
 
1309
            return '%s(%r, fallback_repositories=%r)' % (
 
1310
                self.__class__.__name__,
 
1311
                self.base,
 
1312
                self._fallback_repositories)
 
1313
        else:
 
1314
            return '%s(%r)' % (self.__class__.__name__,
 
1315
                               self.base)
 
1316
 
 
1317
    def _has_same_fallbacks(self, other_repo):
 
1318
        """Returns true if the repositories have the same fallbacks."""
 
1319
        my_fb = self._fallback_repositories
 
1320
        other_fb = other_repo._fallback_repositories
 
1321
        if len(my_fb) != len(other_fb):
 
1322
            return False
 
1323
        for f, g in zip(my_fb, other_fb):
 
1324
            if not f.has_same_location(g):
 
1325
                return False
 
1326
        return True
 
1327
 
 
1328
    def has_same_location(self, other):
 
1329
        """Returns a boolean indicating if this repository is at the same
 
1330
        location as another repository.
 
1331
 
 
1332
        This might return False even when two repository objects are accessing
 
1333
        the same physical repository via different URLs.
 
1334
        """
 
1335
        if self.__class__ is not other.__class__:
 
1336
            return False
 
1337
        return (self._transport.base == other._transport.base)
 
1338
 
 
1339
    def is_in_write_group(self):
 
1340
        """Return True if there is an open write group.
 
1341
 
 
1342
        :seealso: start_write_group.
 
1343
        """
 
1344
        return self._write_group is not None
 
1345
 
 
1346
    def is_locked(self):
 
1347
        return self.control_files.is_locked()
 
1348
 
 
1349
    def is_write_locked(self):
 
1350
        """Return True if this object is write locked."""
 
1351
        return self.is_locked() and self.control_files._lock_mode == 'w'
 
1352
 
 
1353
    def lock_write(self, token=None):
 
1354
        """Lock this repository for writing.
 
1355
 
 
1356
        This causes caching within the repository obejct to start accumlating
 
1357
        data during reads, and allows a 'write_group' to be obtained. Write
 
1358
        groups must be used for actual data insertion.
 
1359
 
 
1360
        :param token: if this is already locked, then lock_write will fail
 
1361
            unless the token matches the existing lock.
 
1362
        :returns: a token if this instance supports tokens, otherwise None.
 
1363
        :raises TokenLockingNotSupported: when a token is given but this
 
1364
            instance doesn't support using token locks.
 
1365
        :raises MismatchedToken: if the specified token doesn't match the token
 
1366
            of the existing lock.
 
1367
        :seealso: start_write_group.
 
1368
 
 
1369
        A token should be passed in if you know that you have locked the object
 
1370
        some other way, and need to synchronise this object's state with that
 
1371
        fact.
 
1372
 
 
1373
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
 
1374
        """
 
1375
        locked = self.is_locked()
 
1376
        result = self.control_files.lock_write(token=token)
 
1377
        if not locked:
 
1378
            for repo in self._fallback_repositories:
 
1379
                # Writes don't affect fallback repos
 
1380
                repo.lock_read()
 
1381
            self._refresh_data()
 
1382
        return result
 
1383
 
 
1384
    def lock_read(self):
 
1385
        locked = self.is_locked()
 
1386
        self.control_files.lock_read()
 
1387
        if not locked:
 
1388
            for repo in self._fallback_repositories:
 
1389
                repo.lock_read()
 
1390
            self._refresh_data()
 
1391
 
 
1392
    def get_physical_lock_status(self):
 
1393
        return self.control_files.get_physical_lock_status()
 
1394
 
 
1395
    def leave_lock_in_place(self):
 
1396
        """Tell this repository not to release the physical lock when this
 
1397
        object is unlocked.
 
1398
 
 
1399
        If lock_write doesn't return a token, then this method is not supported.
 
1400
        """
 
1401
        self.control_files.leave_in_place()
 
1402
 
 
1403
    def dont_leave_lock_in_place(self):
 
1404
        """Tell this repository to release the physical lock when this
 
1405
        object is unlocked, even if it didn't originally acquire it.
 
1406
 
 
1407
        If lock_write doesn't return a token, then this method is not supported.
 
1408
        """
 
1409
        self.control_files.dont_leave_in_place()
 
1410
 
 
1411
    @needs_read_lock
 
1412
    def gather_stats(self, revid=None, committers=None):
 
1413
        """Gather statistics from a revision id.
 
1414
 
 
1415
        :param revid: The revision id to gather statistics from, if None, then
 
1416
            no revision specific statistics are gathered.
 
1417
        :param committers: Optional parameter controlling whether to grab
 
1418
            a count of committers from the revision specific statistics.
 
1419
        :return: A dictionary of statistics. Currently this contains:
 
1420
            committers: The number of committers if requested.
 
1421
            firstrev: A tuple with timestamp, timezone for the penultimate left
 
1422
                most ancestor of revid, if revid is not the NULL_REVISION.
 
1423
            latestrev: A tuple with timestamp, timezone for revid, if revid is
 
1424
                not the NULL_REVISION.
 
1425
            revisions: The total revision count in the repository.
 
1426
            size: An estimate disk size of the repository in bytes.
 
1427
        """
 
1428
        result = {}
 
1429
        if revid and committers:
 
1430
            result['committers'] = 0
 
1431
        if revid and revid != _mod_revision.NULL_REVISION:
 
1432
            if committers:
 
1433
                all_committers = set()
 
1434
            revisions = self.get_ancestry(revid)
 
1435
            # pop the leading None
 
1436
            revisions.pop(0)
 
1437
            first_revision = None
 
1438
            if not committers:
 
1439
                # ignore the revisions in the middle - just grab first and last
 
1440
                revisions = revisions[0], revisions[-1]
 
1441
            for revision in self.get_revisions(revisions):
 
1442
                if not first_revision:
 
1443
                    first_revision = revision
 
1444
                if committers:
 
1445
                    all_committers.add(revision.committer)
 
1446
            last_revision = revision
 
1447
            if committers:
 
1448
                result['committers'] = len(all_committers)
 
1449
            result['firstrev'] = (first_revision.timestamp,
 
1450
                first_revision.timezone)
 
1451
            result['latestrev'] = (last_revision.timestamp,
 
1452
                last_revision.timezone)
 
1453
 
 
1454
        # now gather global repository information
 
1455
        # XXX: This is available for many repos regardless of listability.
 
1456
        if self.bzrdir.root_transport.listable():
 
1457
            # XXX: do we want to __define len__() ?
 
1458
            # Maybe the versionedfiles object should provide a different
 
1459
            # method to get the number of keys.
 
1460
            result['revisions'] = len(self.revisions.keys())
 
1461
            # result['size'] = t
 
1462
        return result
 
1463
 
 
1464
    def find_branches(self, using=False):
 
1465
        """Find branches underneath this repository.
 
1466
 
 
1467
        This will include branches inside other branches.
 
1468
 
 
1469
        :param using: If True, list only branches using this repository.
 
1470
        """
 
1471
        if using and not self.is_shared():
 
1472
            try:
 
1473
                return [self.bzrdir.open_branch()]
 
1474
            except errors.NotBranchError:
 
1475
                return []
 
1476
        class Evaluator(object):
 
1477
 
 
1478
            def __init__(self):
 
1479
                self.first_call = True
 
1480
 
 
1481
            def __call__(self, bzrdir):
 
1482
                # On the first call, the parameter is always the bzrdir
 
1483
                # containing the current repo.
 
1484
                if not self.first_call:
 
1485
                    try:
 
1486
                        repository = bzrdir.open_repository()
 
1487
                    except errors.NoRepositoryPresent:
 
1488
                        pass
 
1489
                    else:
 
1490
                        return False, (None, repository)
 
1491
                self.first_call = False
 
1492
                try:
 
1493
                    value = (bzrdir.open_branch(), None)
 
1494
                except errors.NotBranchError:
 
1495
                    value = (None, None)
 
1496
                return True, value
 
1497
 
 
1498
        branches = []
 
1499
        for branch, repository in bzrdir.BzrDir.find_bzrdirs(
 
1500
                self.bzrdir.root_transport, evaluate=Evaluator()):
 
1501
            if branch is not None:
 
1502
                branches.append(branch)
 
1503
            if not using and repository is not None:
 
1504
                branches.extend(repository.find_branches())
 
1505
        return branches
 
1506
 
 
1507
    @needs_read_lock
 
1508
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
 
1509
        """Return the revision ids that other has that this does not.
 
1510
 
 
1511
        These are returned in topological order.
 
1512
 
 
1513
        revision_id: only return revision ids included by revision_id.
 
1514
        """
 
1515
        return InterRepository.get(other, self).search_missing_revision_ids(
 
1516
            revision_id, find_ghosts)
 
1517
 
 
1518
    @staticmethod
 
1519
    def open(base):
 
1520
        """Open the repository rooted at base.
 
1521
 
 
1522
        For instance, if the repository is at URL/.bzr/repository,
 
1523
        Repository.open(URL) -> a Repository instance.
 
1524
        """
 
1525
        control = bzrdir.BzrDir.open(base)
 
1526
        return control.open_repository()
 
1527
 
 
1528
    def copy_content_into(self, destination, revision_id=None):
 
1529
        """Make a complete copy of the content in self into destination.
 
1530
 
 
1531
        This is a destructive operation! Do not use it on existing
 
1532
        repositories.
 
1533
        """
 
1534
        return InterRepository.get(self, destination).copy_content(revision_id)
 
1535
 
 
1536
    def commit_write_group(self):
 
1537
        """Commit the contents accrued within the current write group.
 
1538
 
 
1539
        :seealso: start_write_group.
 
1540
        
 
1541
        :return: it may return an opaque hint that can be passed to 'pack'.
 
1542
        """
 
1543
        if self._write_group is not self.get_transaction():
 
1544
            # has an unlock or relock occured ?
 
1545
            raise errors.BzrError('mismatched lock context %r and '
 
1546
                'write group %r.' %
 
1547
                (self.get_transaction(), self._write_group))
 
1548
        result = self._commit_write_group()
 
1549
        self._write_group = None
 
1550
        return result
 
1551
 
 
1552
    def _commit_write_group(self):
 
1553
        """Template method for per-repository write group cleanup.
 
1554
 
 
1555
        This is called before the write group is considered to be
 
1556
        finished and should ensure that all data handed to the repository
 
1557
        for writing during the write group is safely committed (to the
 
1558
        extent possible considering file system caching etc).
 
1559
        """
 
1560
 
 
1561
    def suspend_write_group(self):
 
1562
        raise errors.UnsuspendableWriteGroup(self)
 
1563
 
 
1564
    def get_missing_parent_inventories(self, check_for_missing_texts=True):
 
1565
        """Return the keys of missing inventory parents for revisions added in
 
1566
        this write group.
 
1567
 
 
1568
        A revision is not complete if the inventory delta for that revision
 
1569
        cannot be calculated.  Therefore if the parent inventories of a
 
1570
        revision are not present, the revision is incomplete, and e.g. cannot
 
1571
        be streamed by a smart server.  This method finds missing inventory
 
1572
        parents for revisions added in this write group.
 
1573
        """
 
1574
        if not self._format.supports_external_lookups:
 
1575
            # This is only an issue for stacked repositories
 
1576
            return set()
 
1577
        if not self.is_in_write_group():
 
1578
            raise AssertionError('not in a write group')
 
1579
 
 
1580
        # XXX: We assume that every added revision already has its
 
1581
        # corresponding inventory, so we only check for parent inventories that
 
1582
        # might be missing, rather than all inventories.
 
1583
        parents = set(self.revisions._index.get_missing_parents())
 
1584
        parents.discard(_mod_revision.NULL_REVISION)
 
1585
        unstacked_inventories = self.inventories._index
 
1586
        present_inventories = unstacked_inventories.get_parent_map(
 
1587
            key[-1:] for key in parents)
 
1588
        parents.difference_update(present_inventories)
 
1589
        if len(parents) == 0:
 
1590
            # No missing parent inventories.
 
1591
            return set()
 
1592
        if not check_for_missing_texts:
 
1593
            return set(('inventories', rev_id) for (rev_id,) in parents)
 
1594
        # Ok, now we have a list of missing inventories.  But these only matter
 
1595
        # if the inventories that reference them are missing some texts they
 
1596
        # appear to introduce.
 
1597
        # XXX: Texts referenced by all added inventories need to be present,
 
1598
        # but at the moment we're only checking for texts referenced by
 
1599
        # inventories at the graph's edge.
 
1600
        key_deps = self.revisions._index._key_dependencies
 
1601
        key_deps.add_keys(present_inventories)
 
1602
        referrers = frozenset(r[0] for r in key_deps.get_referrers())
 
1603
        file_ids = self.fileids_altered_by_revision_ids(referrers)
 
1604
        missing_texts = set()
 
1605
        for file_id, version_ids in file_ids.iteritems():
 
1606
            missing_texts.update(
 
1607
                (file_id, version_id) for version_id in version_ids)
 
1608
        present_texts = self.texts.get_parent_map(missing_texts)
 
1609
        missing_texts.difference_update(present_texts)
 
1610
        if not missing_texts:
 
1611
            # No texts are missing, so all revisions and their deltas are
 
1612
            # reconstructable.
 
1613
            return set()
 
1614
        # Alternatively the text versions could be returned as the missing
 
1615
        # keys, but this is likely to be less data.
 
1616
        missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
 
1617
        return missing_keys
 
1618
 
 
1619
    def refresh_data(self):
 
1620
        """Re-read any data needed to to synchronise with disk.
 
1621
 
 
1622
        This method is intended to be called after another repository instance
 
1623
        (such as one used by a smart server) has inserted data into the
 
1624
        repository. It may not be called during a write group, but may be
 
1625
        called at any other time.
 
1626
        """
 
1627
        if self.is_in_write_group():
 
1628
            raise errors.InternalBzrError(
 
1629
                "May not refresh_data while in a write group.")
 
1630
        self._refresh_data()
 
1631
 
 
1632
    def resume_write_group(self, tokens):
 
1633
        if not self.is_write_locked():
 
1634
            raise errors.NotWriteLocked(self)
 
1635
        if self._write_group:
 
1636
            raise errors.BzrError('already in a write group')
 
1637
        self._resume_write_group(tokens)
 
1638
        # so we can detect unlock/relock - the write group is now entered.
 
1639
        self._write_group = self.get_transaction()
 
1640
 
 
1641
    def _resume_write_group(self, tokens):
 
1642
        raise errors.UnsuspendableWriteGroup(self)
 
1643
 
 
1644
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
 
1645
            fetch_spec=None):
 
1646
        """Fetch the content required to construct revision_id from source.
 
1647
 
 
1648
        If revision_id is None and fetch_spec is None, then all content is
 
1649
        copied.
 
1650
 
 
1651
        fetch() may not be used when the repository is in a write group -
 
1652
        either finish the current write group before using fetch, or use
 
1653
        fetch before starting the write group.
 
1654
 
 
1655
        :param find_ghosts: Find and copy revisions in the source that are
 
1656
            ghosts in the target (and not reachable directly by walking out to
 
1657
            the first-present revision in target from revision_id).
 
1658
        :param revision_id: If specified, all the content needed for this
 
1659
            revision ID will be copied to the target.  Fetch will determine for
 
1660
            itself which content needs to be copied.
 
1661
        :param fetch_spec: If specified, a SearchResult or
 
1662
            PendingAncestryResult that describes which revisions to copy.  This
 
1663
            allows copying multiple heads at once.  Mutually exclusive with
 
1664
            revision_id.
 
1665
        """
 
1666
        if fetch_spec is not None and revision_id is not None:
 
1667
            raise AssertionError(
 
1668
                "fetch_spec and revision_id are mutually exclusive.")
 
1669
        if self.is_in_write_group():
 
1670
            raise errors.InternalBzrError(
 
1671
                "May not fetch while in a write group.")
 
1672
        # fast path same-url fetch operations
 
1673
        # TODO: lift out to somewhere common with RemoteRepository
 
1674
        # <https://bugs.edge.launchpad.net/bzr/+bug/401646>
 
1675
        if (self.has_same_location(source)
 
1676
            and fetch_spec is None
 
1677
            and self._has_same_fallbacks(source)):
 
1678
            # check that last_revision is in 'from' and then return a
 
1679
            # no-operation.
 
1680
            if (revision_id is not None and
 
1681
                not _mod_revision.is_null(revision_id)):
 
1682
                self.get_revision(revision_id)
 
1683
            return 0, []
 
1684
        # if there is no specific appropriate InterRepository, this will get
 
1685
        # the InterRepository base class, which raises an
 
1686
        # IncompatibleRepositories when asked to fetch.
 
1687
        inter = InterRepository.get(source, self)
 
1688
        return inter.fetch(revision_id=revision_id, pb=pb,
 
1689
            find_ghosts=find_ghosts, fetch_spec=fetch_spec)
 
1690
 
 
1691
    def create_bundle(self, target, base, fileobj, format=None):
 
1692
        return serializer.write_bundle(self, target, base, fileobj, format)
 
1693
 
 
1694
    def get_commit_builder(self, branch, parents, config, timestamp=None,
 
1695
                           timezone=None, committer=None, revprops=None,
 
1696
                           revision_id=None):
 
1697
        """Obtain a CommitBuilder for this repository.
 
1698
 
 
1699
        :param branch: Branch to commit to.
 
1700
        :param parents: Revision ids of the parents of the new revision.
 
1701
        :param config: Configuration to use.
 
1702
        :param timestamp: Optional timestamp recorded for commit.
 
1703
        :param timezone: Optional timezone for timestamp.
 
1704
        :param committer: Optional committer to set for commit.
 
1705
        :param revprops: Optional dictionary of revision properties.
 
1706
        :param revision_id: Optional revision id.
 
1707
        """
 
1708
        if self._fallback_repositories:
 
1709
            raise errors.BzrError("Cannot commit from a lightweight checkout "
 
1710
                "to a stacked branch. See "
 
1711
                "https://bugs.launchpad.net/bzr/+bug/375013 for details.")
 
1712
        result = self._commit_builder_class(self, parents, config,
 
1713
            timestamp, timezone, committer, revprops, revision_id)
 
1714
        self.start_write_group()
 
1715
        return result
 
1716
 
 
1717
    def unlock(self):
 
1718
        if (self.control_files._lock_count == 1 and
 
1719
            self.control_files._lock_mode == 'w'):
 
1720
            if self._write_group is not None:
 
1721
                self.abort_write_group()
 
1722
                self.control_files.unlock()
 
1723
                raise errors.BzrError(
 
1724
                    'Must end write groups before releasing write locks.')
 
1725
        self.control_files.unlock()
 
1726
        if self.control_files._lock_count == 0:
 
1727
            self._inventory_entry_cache.clear()
 
1728
            for repo in self._fallback_repositories:
 
1729
                repo.unlock()
 
1730
 
 
1731
    @needs_read_lock
 
1732
    def clone(self, a_bzrdir, revision_id=None):
 
1733
        """Clone this repository into a_bzrdir using the current format.
 
1734
 
 
1735
        Currently no check is made that the format of this repository and
 
1736
        the bzrdir format are compatible. FIXME RBC 20060201.
 
1737
 
 
1738
        :return: The newly created destination repository.
 
1739
        """
 
1740
        # TODO: deprecate after 0.16; cloning this with all its settings is
 
1741
        # probably not very useful -- mbp 20070423
 
1742
        dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
 
1743
        self.copy_content_into(dest_repo, revision_id)
 
1744
        return dest_repo
 
1745
 
 
1746
    def start_write_group(self):
 
1747
        """Start a write group in the repository.
 
1748
 
 
1749
        Write groups are used by repositories which do not have a 1:1 mapping
 
1750
        between file ids and backend store to manage the insertion of data from
 
1751
        both fetch and commit operations.
 
1752
 
 
1753
        A write lock is required around the start_write_group/commit_write_group
 
1754
        for the support of lock-requiring repository formats.
 
1755
 
 
1756
        One can only insert data into a repository inside a write group.
 
1757
 
 
1758
        :return: None.
 
1759
        """
 
1760
        if not self.is_write_locked():
 
1761
            raise errors.NotWriteLocked(self)
 
1762
        if self._write_group:
 
1763
            raise errors.BzrError('already in a write group')
 
1764
        self._start_write_group()
 
1765
        # so we can detect unlock/relock - the write group is now entered.
 
1766
        self._write_group = self.get_transaction()
 
1767
 
 
1768
    def _start_write_group(self):
 
1769
        """Template method for per-repository write group startup.
 
1770
 
 
1771
        This is called before the write group is considered to be
 
1772
        entered.
 
1773
        """
 
1774
 
 
1775
    @needs_read_lock
 
1776
    def sprout(self, to_bzrdir, revision_id=None):
 
1777
        """Create a descendent repository for new development.
 
1778
 
 
1779
        Unlike clone, this does not copy the settings of the repository.
 
1780
        """
 
1781
        dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
 
1782
        dest_repo.fetch(self, revision_id=revision_id)
 
1783
        return dest_repo
 
1784
 
 
1785
    def _create_sprouting_repo(self, a_bzrdir, shared):
 
1786
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
 
1787
            # use target default format.
 
1788
            dest_repo = a_bzrdir.create_repository()
 
1789
        else:
 
1790
            # Most control formats need the repository to be specifically
 
1791
            # created, but on some old all-in-one formats it's not needed
 
1792
            try:
 
1793
                dest_repo = self._format.initialize(a_bzrdir, shared=shared)
 
1794
            except errors.UninitializableFormat:
 
1795
                dest_repo = a_bzrdir.open_repository()
 
1796
        return dest_repo
 
1797
 
 
1798
    def _get_sink(self):
 
1799
        """Return a sink for streaming into this repository."""
 
1800
        return StreamSink(self)
 
1801
 
 
1802
    def _get_source(self, to_format):
 
1803
        """Return a source for streaming from this repository."""
 
1804
        return StreamSource(self, to_format)
 
1805
 
 
1806
    @needs_read_lock
 
1807
    def has_revision(self, revision_id):
 
1808
        """True if this repository has a copy of the revision."""
 
1809
        return revision_id in self.has_revisions((revision_id,))
 
1810
 
 
1811
    @needs_read_lock
 
1812
    def has_revisions(self, revision_ids):
 
1813
        """Probe to find out the presence of multiple revisions.
 
1814
 
 
1815
        :param revision_ids: An iterable of revision_ids.
 
1816
        :return: A set of the revision_ids that were present.
 
1817
        """
 
1818
        parent_map = self.revisions.get_parent_map(
 
1819
            [(rev_id,) for rev_id in revision_ids])
 
1820
        result = set()
 
1821
        if _mod_revision.NULL_REVISION in revision_ids:
 
1822
            result.add(_mod_revision.NULL_REVISION)
 
1823
        result.update([key[0] for key in parent_map])
 
1824
        return result
 
1825
 
 
1826
    @needs_read_lock
 
1827
    def get_revision(self, revision_id):
 
1828
        """Return the Revision object for a named revision."""
 
1829
        return self.get_revisions([revision_id])[0]
 
1830
 
 
1831
    @needs_read_lock
 
1832
    def get_revision_reconcile(self, revision_id):
 
1833
        """'reconcile' helper routine that allows access to a revision always.
 
1834
 
 
1835
        This variant of get_revision does not cross check the weave graph
 
1836
        against the revision one as get_revision does: but it should only
 
1837
        be used by reconcile, or reconcile-alike commands that are correcting
 
1838
        or testing the revision graph.
 
1839
        """
 
1840
        return self._get_revisions([revision_id])[0]
 
1841
 
 
1842
    @needs_read_lock
 
1843
    def get_revisions(self, revision_ids):
 
1844
        """Get many revisions at once.
 
1845
        
 
1846
        Repositories that need to check data on every revision read should 
 
1847
        subclass this method.
 
1848
        """
 
1849
        return self._get_revisions(revision_ids)
 
1850
 
 
1851
    @needs_read_lock
 
1852
    def _get_revisions(self, revision_ids):
 
1853
        """Core work logic to get many revisions without sanity checks."""
 
1854
        revs = {}
 
1855
        for revid, rev in self._iter_revisions(revision_ids):
 
1856
            if rev is None:
 
1857
                raise errors.NoSuchRevision(self, revid)
 
1858
            revs[revid] = rev
 
1859
        return [revs[revid] for revid in revision_ids]
 
1860
 
 
1861
    def _iter_revisions(self, revision_ids):
 
1862
        """Iterate over revision objects.
 
1863
 
 
1864
        :param revision_ids: An iterable of revisions to examine. None may be
 
1865
            passed to request all revisions known to the repository. Note that
 
1866
            not all repositories can find unreferenced revisions; for those
 
1867
            repositories only referenced ones will be returned.
 
1868
        :return: An iterator of (revid, revision) tuples. Absent revisions (
 
1869
            those asked for but not available) are returned as (revid, None).
 
1870
        """
 
1871
        if revision_ids is None:
 
1872
            revision_ids = self.all_revision_ids()
 
1873
        else:
 
1874
            for rev_id in revision_ids:
 
1875
                if not rev_id or not isinstance(rev_id, basestring):
 
1876
                    raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
 
1877
        keys = [(key,) for key in revision_ids]
 
1878
        stream = self.revisions.get_record_stream(keys, 'unordered', True)
 
1879
        for record in stream:
 
1880
            revid = record.key[0]
 
1881
            if record.storage_kind == 'absent':
 
1882
                yield (revid, None)
 
1883
            else:
 
1884
                text = record.get_bytes_as('fulltext')
 
1885
                rev = self._serializer.read_revision_from_string(text)
 
1886
                yield (revid, rev)
 
1887
 
 
1888
    @needs_read_lock
 
1889
    def get_revision_xml(self, revision_id):
 
1890
        # TODO: jam 20070210 This shouldn't be necessary since get_revision
 
1891
        #       would have already do it.
 
1892
        # TODO: jam 20070210 Just use _serializer.write_revision_to_string()
 
1893
        # TODO: this can't just be replaced by:
 
1894
        # return self._serializer.write_revision_to_string(
 
1895
        #     self.get_revision(revision_id))
 
1896
        # as cStringIO preservers the encoding unlike write_revision_to_string
 
1897
        # or some other call down the path.
 
1898
        rev = self.get_revision(revision_id)
 
1899
        rev_tmp = cStringIO.StringIO()
 
1900
        # the current serializer..
 
1901
        self._serializer.write_revision(rev, rev_tmp)
 
1902
        rev_tmp.seek(0)
 
1903
        return rev_tmp.getvalue()
 
1904
 
 
1905
    def get_deltas_for_revisions(self, revisions, specific_fileids=None):
 
1906
        """Produce a generator of revision deltas.
 
1907
 
 
1908
        Note that the input is a sequence of REVISIONS, not revision_ids.
 
1909
        Trees will be held in memory until the generator exits.
 
1910
        Each delta is relative to the revision's lefthand predecessor.
 
1911
 
 
1912
        :param specific_fileids: if not None, the result is filtered
 
1913
          so that only those file-ids, their parents and their
 
1914
          children are included.
 
1915
        """
 
1916
        # Get the revision-ids of interest
 
1917
        required_trees = set()
 
1918
        for revision in revisions:
 
1919
            required_trees.add(revision.revision_id)
 
1920
            required_trees.update(revision.parent_ids[:1])
 
1921
 
 
1922
        # Get the matching filtered trees. Note that it's more
 
1923
        # efficient to pass filtered trees to changes_from() rather
 
1924
        # than doing the filtering afterwards. changes_from() could
 
1925
        # arguably do the filtering itself but it's path-based, not
 
1926
        # file-id based, so filtering before or afterwards is
 
1927
        # currently easier.
 
1928
        if specific_fileids is None:
 
1929
            trees = dict((t.get_revision_id(), t) for
 
1930
                t in self.revision_trees(required_trees))
 
1931
        else:
 
1932
            trees = dict((t.get_revision_id(), t) for
 
1933
                t in self._filtered_revision_trees(required_trees,
 
1934
                specific_fileids))
 
1935
 
 
1936
        # Calculate the deltas
 
1937
        for revision in revisions:
 
1938
            if not revision.parent_ids:
 
1939
                old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
 
1940
            else:
 
1941
                old_tree = trees[revision.parent_ids[0]]
 
1942
            yield trees[revision.revision_id].changes_from(old_tree)
 
1943
 
 
1944
    @needs_read_lock
 
1945
    def get_revision_delta(self, revision_id, specific_fileids=None):
 
1946
        """Return the delta for one revision.
 
1947
 
 
1948
        The delta is relative to the left-hand predecessor of the
 
1949
        revision.
 
1950
 
 
1951
        :param specific_fileids: if not None, the result is filtered
 
1952
          so that only those file-ids, their parents and their
 
1953
          children are included.
 
1954
        """
 
1955
        r = self.get_revision(revision_id)
 
1956
        return list(self.get_deltas_for_revisions([r],
 
1957
            specific_fileids=specific_fileids))[0]
 
1958
 
 
1959
    @needs_write_lock
 
1960
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
1961
        signature = gpg_strategy.sign(plaintext)
 
1962
        self.add_signature_text(revision_id, signature)
 
1963
 
 
1964
    @needs_write_lock
 
1965
    def add_signature_text(self, revision_id, signature):
 
1966
        self.signatures.add_lines((revision_id,), (),
 
1967
            osutils.split_lines(signature))
 
1968
 
 
1969
    def find_text_key_references(self):
 
1970
        """Find the text key references within the repository.
 
1971
 
 
1972
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
 
1973
            to whether they were referred to by the inventory of the
 
1974
            revision_id that they contain. The inventory texts from all present
 
1975
            revision ids are assessed to generate this report.
 
1976
        """
 
1977
        revision_keys = self.revisions.keys()
 
1978
        w = self.inventories
 
1979
        pb = ui.ui_factory.nested_progress_bar()
 
1980
        try:
 
1981
            return self._find_text_key_references_from_xml_inventory_lines(
 
1982
                w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
 
1983
        finally:
 
1984
            pb.finished()
 
1985
 
 
1986
    def _find_text_key_references_from_xml_inventory_lines(self,
 
1987
        line_iterator):
 
1988
        """Core routine for extracting references to texts from inventories.
 
1989
 
 
1990
        This performs the translation of xml lines to revision ids.
 
1991
 
 
1992
        :param line_iterator: An iterator of lines, origin_version_id
 
1993
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
 
1994
            to whether they were referred to by the inventory of the
 
1995
            revision_id that they contain. Note that if that revision_id was
 
1996
            not part of the line_iterator's output then False will be given -
 
1997
            even though it may actually refer to that key.
 
1998
        """
 
1999
        if not self._serializer.support_altered_by_hack:
 
2000
            raise AssertionError(
 
2001
                "_find_text_key_references_from_xml_inventory_lines only "
 
2002
                "supported for branches which store inventory as unnested xml"
 
2003
                ", not on %r" % self)
 
2004
        result = {}
 
2005
 
 
2006
        # this code needs to read every new line in every inventory for the
 
2007
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
 
2008
        # not present in one of those inventories is unnecessary but not
 
2009
        # harmful because we are filtering by the revision id marker in the
 
2010
        # inventory lines : we only select file ids altered in one of those
 
2011
        # revisions. We don't need to see all lines in the inventory because
 
2012
        # only those added in an inventory in rev X can contain a revision=X
 
2013
        # line.
 
2014
        unescape_revid_cache = {}
 
2015
        unescape_fileid_cache = {}
 
2016
 
 
2017
        # jam 20061218 In a big fetch, this handles hundreds of thousands
 
2018
        # of lines, so it has had a lot of inlining and optimizing done.
 
2019
        # Sorry that it is a little bit messy.
 
2020
        # Move several functions to be local variables, since this is a long
 
2021
        # running loop.
 
2022
        search = self._file_ids_altered_regex.search
 
2023
        unescape = _unescape_xml
 
2024
        setdefault = result.setdefault
 
2025
        for line, line_key in line_iterator:
 
2026
            match = search(line)
 
2027
            if match is None:
 
2028
                continue
 
2029
            # One call to match.group() returning multiple items is quite a
 
2030
            # bit faster than 2 calls to match.group() each returning 1
 
2031
            file_id, revision_id = match.group('file_id', 'revision_id')
 
2032
 
 
2033
            # Inlining the cache lookups helps a lot when you make 170,000
 
2034
            # lines and 350k ids, versus 8.4 unique ids.
 
2035
            # Using a cache helps in 2 ways:
 
2036
            #   1) Avoids unnecessary decoding calls
 
2037
            #   2) Re-uses cached strings, which helps in future set and
 
2038
            #      equality checks.
 
2039
            # (2) is enough that removing encoding entirely along with
 
2040
            # the cache (so we are using plain strings) results in no
 
2041
            # performance improvement.
 
2042
            try:
 
2043
                revision_id = unescape_revid_cache[revision_id]
 
2044
            except KeyError:
 
2045
                unescaped = unescape(revision_id)
 
2046
                unescape_revid_cache[revision_id] = unescaped
 
2047
                revision_id = unescaped
 
2048
 
 
2049
            # Note that unconditionally unescaping means that we deserialise
 
2050
            # every fileid, which for general 'pull' is not great, but we don't
 
2051
            # really want to have some many fulltexts that this matters anyway.
 
2052
            # RBC 20071114.
 
2053
            try:
 
2054
                file_id = unescape_fileid_cache[file_id]
 
2055
            except KeyError:
 
2056
                unescaped = unescape(file_id)
 
2057
                unescape_fileid_cache[file_id] = unescaped
 
2058
                file_id = unescaped
 
2059
 
 
2060
            key = (file_id, revision_id)
 
2061
            setdefault(key, False)
 
2062
            if revision_id == line_key[-1]:
 
2063
                result[key] = True
 
2064
        return result
 
2065
 
 
2066
    def _inventory_xml_lines_for_keys(self, keys):
 
2067
        """Get a line iterator of the sort needed for findind references.
 
2068
 
 
2069
        Not relevant for non-xml inventory repositories.
 
2070
 
 
2071
        Ghosts in revision_keys are ignored.
 
2072
 
 
2073
        :param revision_keys: The revision keys for the inventories to inspect.
 
2074
        :return: An iterator over (inventory line, revid) for the fulltexts of
 
2075
            all of the xml inventories specified by revision_keys.
 
2076
        """
 
2077
        stream = self.inventories.get_record_stream(keys, 'unordered', True)
 
2078
        for record in stream:
 
2079
            if record.storage_kind != 'absent':
 
2080
                chunks = record.get_bytes_as('chunked')
 
2081
                revid = record.key[-1]
 
2082
                lines = osutils.chunks_to_lines(chunks)
 
2083
                for line in lines:
 
2084
                    yield line, revid
 
2085
 
 
2086
    def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
 
2087
        revision_keys):
 
2088
        """Helper routine for fileids_altered_by_revision_ids.
 
2089
 
 
2090
        This performs the translation of xml lines to revision ids.
 
2091
 
 
2092
        :param line_iterator: An iterator of lines, origin_version_id
 
2093
        :param revision_keys: The revision ids to filter for. This should be a
 
2094
            set or other type which supports efficient __contains__ lookups, as
 
2095
            the revision key from each parsed line will be looked up in the
 
2096
            revision_keys filter.
 
2097
        :return: a dictionary mapping altered file-ids to an iterable of
 
2098
        revision_ids. Each altered file-ids has the exact revision_ids that
 
2099
        altered it listed explicitly.
 
2100
        """
 
2101
        seen = set(self._find_text_key_references_from_xml_inventory_lines(
 
2102
                line_iterator).iterkeys())
 
2103
        parent_keys = self._find_parent_keys_of_revisions(revision_keys)
 
2104
        parent_seen = set(self._find_text_key_references_from_xml_inventory_lines(
 
2105
            self._inventory_xml_lines_for_keys(parent_keys)))
 
2106
        new_keys = seen - parent_seen
 
2107
        result = {}
 
2108
        setdefault = result.setdefault
 
2109
        for key in new_keys:
 
2110
            setdefault(key[0], set()).add(key[-1])
 
2111
        return result
 
2112
 
 
2113
    def _find_parent_ids_of_revisions(self, revision_ids):
 
2114
        """Find all parent ids that are mentioned in the revision graph.
 
2115
 
 
2116
        :return: set of revisions that are parents of revision_ids which are
 
2117
            not part of revision_ids themselves
 
2118
        """
 
2119
        parent_map = self.get_parent_map(revision_ids)
 
2120
        parent_ids = set()
 
2121
        map(parent_ids.update, parent_map.itervalues())
 
2122
        parent_ids.difference_update(revision_ids)
 
2123
        parent_ids.discard(_mod_revision.NULL_REVISION)
 
2124
        return parent_ids
 
2125
 
 
2126
    def _find_parent_keys_of_revisions(self, revision_keys):
 
2127
        """Similar to _find_parent_ids_of_revisions, but used with keys.
 
2128
 
 
2129
        :param revision_keys: An iterable of revision_keys.
 
2130
        :return: The parents of all revision_keys that are not already in
 
2131
            revision_keys
 
2132
        """
 
2133
        parent_map = self.revisions.get_parent_map(revision_keys)
 
2134
        parent_keys = set()
 
2135
        map(parent_keys.update, parent_map.itervalues())
 
2136
        parent_keys.difference_update(revision_keys)
 
2137
        parent_keys.discard(_mod_revision.NULL_REVISION)
 
2138
        return parent_keys
 
2139
 
 
2140
    def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
 
2141
        """Find the file ids and versions affected by revisions.
 
2142
 
 
2143
        :param revisions: an iterable containing revision ids.
 
2144
        :param _inv_weave: The inventory weave from this repository or None.
 
2145
            If None, the inventory weave will be opened automatically.
 
2146
        :return: a dictionary mapping altered file-ids to an iterable of
 
2147
        revision_ids. Each altered file-ids has the exact revision_ids that
 
2148
        altered it listed explicitly.
 
2149
        """
 
2150
        selected_keys = set((revid,) for revid in revision_ids)
 
2151
        w = _inv_weave or self.inventories
 
2152
        pb = ui.ui_factory.nested_progress_bar()
 
2153
        try:
 
2154
            return self._find_file_ids_from_xml_inventory_lines(
 
2155
                w.iter_lines_added_or_present_in_keys(
 
2156
                    selected_keys, pb=pb),
 
2157
                selected_keys)
 
2158
        finally:
 
2159
            pb.finished()
 
2160
 
 
2161
    def iter_files_bytes(self, desired_files):
 
2162
        """Iterate through file versions.
 
2163
 
 
2164
        Files will not necessarily be returned in the order they occur in
 
2165
        desired_files.  No specific order is guaranteed.
 
2166
 
 
2167
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
 
2168
        value supplied by the caller as part of desired_files.  It should
 
2169
        uniquely identify the file version in the caller's context.  (Examples:
 
2170
        an index number or a TreeTransform trans_id.)
 
2171
 
 
2172
        bytes_iterator is an iterable of bytestrings for the file.  The
 
2173
        kind of iterable and length of the bytestrings are unspecified, but for
 
2174
        this implementation, it is a list of bytes produced by
 
2175
        VersionedFile.get_record_stream().
 
2176
 
 
2177
        :param desired_files: a list of (file_id, revision_id, identifier)
 
2178
            triples
 
2179
        """
 
2180
        text_keys = {}
 
2181
        for file_id, revision_id, callable_data in desired_files:
 
2182
            text_keys[(file_id, revision_id)] = callable_data
 
2183
        for record in self.texts.get_record_stream(text_keys, 'unordered', True):
 
2184
            if record.storage_kind == 'absent':
 
2185
                raise errors.RevisionNotPresent(record.key, self)
 
2186
            yield text_keys[record.key], record.get_bytes_as('chunked')
 
2187
 
 
2188
    def _generate_text_key_index(self, text_key_references=None,
 
2189
        ancestors=None):
 
2190
        """Generate a new text key index for the repository.
 
2191
 
 
2192
        This is an expensive function that will take considerable time to run.
 
2193
 
 
2194
        :return: A dict mapping text keys ((file_id, revision_id) tuples) to a
 
2195
            list of parents, also text keys. When a given key has no parents,
 
2196
            the parents list will be [NULL_REVISION].
 
2197
        """
 
2198
        # All revisions, to find inventory parents.
 
2199
        if ancestors is None:
 
2200
            graph = self.get_graph()
 
2201
            ancestors = graph.get_parent_map(self.all_revision_ids())
 
2202
        if text_key_references is None:
 
2203
            text_key_references = self.find_text_key_references()
 
2204
        pb = ui.ui_factory.nested_progress_bar()
 
2205
        try:
 
2206
            return self._do_generate_text_key_index(ancestors,
 
2207
                text_key_references, pb)
 
2208
        finally:
 
2209
            pb.finished()
 
2210
 
 
2211
    def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
 
2212
        """Helper for _generate_text_key_index to avoid deep nesting."""
 
2213
        revision_order = tsort.topo_sort(ancestors)
 
2214
        invalid_keys = set()
 
2215
        revision_keys = {}
 
2216
        for revision_id in revision_order:
 
2217
            revision_keys[revision_id] = set()
 
2218
        text_count = len(text_key_references)
 
2219
        # a cache of the text keys to allow reuse; costs a dict of all the
 
2220
        # keys, but saves a 2-tuple for every child of a given key.
 
2221
        text_key_cache = {}
 
2222
        for text_key, valid in text_key_references.iteritems():
 
2223
            if not valid:
 
2224
                invalid_keys.add(text_key)
 
2225
            else:
 
2226
                revision_keys[text_key[1]].add(text_key)
 
2227
            text_key_cache[text_key] = text_key
 
2228
        del text_key_references
 
2229
        text_index = {}
 
2230
        text_graph = graph.Graph(graph.DictParentsProvider(text_index))
 
2231
        NULL_REVISION = _mod_revision.NULL_REVISION
 
2232
        # Set a cache with a size of 10 - this suffices for bzr.dev but may be
 
2233
        # too small for large or very branchy trees. However, for 55K path
 
2234
        # trees, it would be easy to use too much memory trivially. Ideally we
 
2235
        # could gauge this by looking at available real memory etc, but this is
 
2236
        # always a tricky proposition.
 
2237
        inventory_cache = lru_cache.LRUCache(10)
 
2238
        batch_size = 10 # should be ~150MB on a 55K path tree
 
2239
        batch_count = len(revision_order) / batch_size + 1
 
2240
        processed_texts = 0
 
2241
        pb.update("Calculating text parents", processed_texts, text_count)
 
2242
        for offset in xrange(batch_count):
 
2243
            to_query = revision_order[offset * batch_size:(offset + 1) *
 
2244
                batch_size]
 
2245
            if not to_query:
 
2246
                break
 
2247
            for revision_id in to_query:
 
2248
                parent_ids = ancestors[revision_id]
 
2249
                for text_key in revision_keys[revision_id]:
 
2250
                    pb.update("Calculating text parents", processed_texts)
 
2251
                    processed_texts += 1
 
2252
                    candidate_parents = []
 
2253
                    for parent_id in parent_ids:
 
2254
                        parent_text_key = (text_key[0], parent_id)
 
2255
                        try:
 
2256
                            check_parent = parent_text_key not in \
 
2257
                                revision_keys[parent_id]
 
2258
                        except KeyError:
 
2259
                            # the parent parent_id is a ghost:
 
2260
                            check_parent = False
 
2261
                            # truncate the derived graph against this ghost.
 
2262
                            parent_text_key = None
 
2263
                        if check_parent:
 
2264
                            # look at the parent commit details inventories to
 
2265
                            # determine possible candidates in the per file graph.
 
2266
                            # TODO: cache here.
 
2267
                            try:
 
2268
                                inv = inventory_cache[parent_id]
 
2269
                            except KeyError:
 
2270
                                inv = self.revision_tree(parent_id).inventory
 
2271
                                inventory_cache[parent_id] = inv
 
2272
                            try:
 
2273
                                parent_entry = inv[text_key[0]]
 
2274
                            except (KeyError, errors.NoSuchId):
 
2275
                                parent_entry = None
 
2276
                            if parent_entry is not None:
 
2277
                                parent_text_key = (
 
2278
                                    text_key[0], parent_entry.revision)
 
2279
                            else:
 
2280
                                parent_text_key = None
 
2281
                        if parent_text_key is not None:
 
2282
                            candidate_parents.append(
 
2283
                                text_key_cache[parent_text_key])
 
2284
                    parent_heads = text_graph.heads(candidate_parents)
 
2285
                    new_parents = list(parent_heads)
 
2286
                    new_parents.sort(key=lambda x:candidate_parents.index(x))
 
2287
                    if new_parents == []:
 
2288
                        new_parents = [NULL_REVISION]
 
2289
                    text_index[text_key] = new_parents
 
2290
 
 
2291
        for text_key in invalid_keys:
 
2292
            text_index[text_key] = [NULL_REVISION]
 
2293
        return text_index
 
2294
 
 
2295
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
 
2296
        """Get an iterable listing the keys of all the data introduced by a set
 
2297
        of revision IDs.
 
2298
 
 
2299
        The keys will be ordered so that the corresponding items can be safely
 
2300
        fetched and inserted in that order.
 
2301
 
 
2302
        :returns: An iterable producing tuples of (knit-kind, file-id,
 
2303
            versions).  knit-kind is one of 'file', 'inventory', 'signatures',
 
2304
            'revisions'.  file-id is None unless knit-kind is 'file'.
 
2305
        """
 
2306
        for result in self._find_file_keys_to_fetch(revision_ids, _files_pb):
 
2307
            yield result
 
2308
        del _files_pb
 
2309
        for result in self._find_non_file_keys_to_fetch(revision_ids):
 
2310
            yield result
 
2311
 
 
2312
    def _find_file_keys_to_fetch(self, revision_ids, pb):
 
2313
        # XXX: it's a bit weird to control the inventory weave caching in this
 
2314
        # generator.  Ideally the caching would be done in fetch.py I think.  Or
 
2315
        # maybe this generator should explicitly have the contract that it
 
2316
        # should not be iterated until the previously yielded item has been
 
2317
        # processed?
 
2318
        inv_w = self.inventories
 
2319
 
 
2320
        # file ids that changed
 
2321
        file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
 
2322
        count = 0
 
2323
        num_file_ids = len(file_ids)
 
2324
        for file_id, altered_versions in file_ids.iteritems():
 
2325
            if pb is not None:
 
2326
                pb.update("fetch texts", count, num_file_ids)
 
2327
            count += 1
 
2328
            yield ("file", file_id, altered_versions)
 
2329
 
 
2330
    def _find_non_file_keys_to_fetch(self, revision_ids):
 
2331
        # inventory
 
2332
        yield ("inventory", None, revision_ids)
 
2333
 
 
2334
        # signatures
 
2335
        # XXX: Note ATM no callers actually pay attention to this return
 
2336
        #      instead they just use the list of revision ids and ignore
 
2337
        #      missing sigs. Consider removing this work entirely
 
2338
        revisions_with_signatures = set(self.signatures.get_parent_map(
 
2339
            [(r,) for r in revision_ids]))
 
2340
        revisions_with_signatures = set(
 
2341
            [r for (r,) in revisions_with_signatures])
 
2342
        revisions_with_signatures.intersection_update(revision_ids)
 
2343
        yield ("signatures", None, revisions_with_signatures)
 
2344
 
 
2345
        # revisions
 
2346
        yield ("revisions", None, revision_ids)
 
2347
 
 
2348
    @needs_read_lock
 
2349
    def get_inventory(self, revision_id):
 
2350
        """Get Inventory object by revision id."""
 
2351
        return self.iter_inventories([revision_id]).next()
 
2352
 
 
2353
    def iter_inventories(self, revision_ids, ordering=None):
 
2354
        """Get many inventories by revision_ids.
 
2355
 
 
2356
        This will buffer some or all of the texts used in constructing the
 
2357
        inventories in memory, but will only parse a single inventory at a
 
2358
        time.
 
2359
 
 
2360
        :param revision_ids: The expected revision ids of the inventories.
 
2361
        :param ordering: optional ordering, e.g. 'topological'.  If not
 
2362
            specified, the order of revision_ids will be preserved (by
 
2363
            buffering if necessary).
 
2364
        :return: An iterator of inventories.
 
2365
        """
 
2366
        if ((None in revision_ids)
 
2367
            or (_mod_revision.NULL_REVISION in revision_ids)):
 
2368
            raise ValueError('cannot get null revision inventory')
 
2369
        return self._iter_inventories(revision_ids, ordering)
 
2370
 
 
2371
    def _iter_inventories(self, revision_ids, ordering):
 
2372
        """single-document based inventory iteration."""
 
2373
        inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
 
2374
        for text, revision_id in inv_xmls:
 
2375
            yield self.deserialise_inventory(revision_id, text)
 
2376
 
 
2377
    def _iter_inventory_xmls(self, revision_ids, ordering):
 
2378
        if ordering is None:
 
2379
            order_as_requested = True
 
2380
            ordering = 'unordered'
 
2381
        else:
 
2382
            order_as_requested = False
 
2383
        keys = [(revision_id,) for revision_id in revision_ids]
 
2384
        if not keys:
 
2385
            return
 
2386
        if order_as_requested:
 
2387
            key_iter = iter(keys)
 
2388
            next_key = key_iter.next()
 
2389
        stream = self.inventories.get_record_stream(keys, ordering, True)
 
2390
        text_chunks = {}
 
2391
        for record in stream:
 
2392
            if record.storage_kind != 'absent':
 
2393
                chunks = record.get_bytes_as('chunked')
 
2394
                if order_as_requested:
 
2395
                    text_chunks[record.key] = chunks
 
2396
                else:
 
2397
                    yield ''.join(chunks), record.key[-1]
 
2398
            else:
 
2399
                raise errors.NoSuchRevision(self, record.key)
 
2400
            if order_as_requested:
 
2401
                # Yield as many results as we can while preserving order.
 
2402
                while next_key in text_chunks:
 
2403
                    chunks = text_chunks.pop(next_key)
 
2404
                    yield ''.join(chunks), next_key[-1]
 
2405
                    try:
 
2406
                        next_key = key_iter.next()
 
2407
                    except StopIteration:
 
2408
                        # We still want to fully consume the get_record_stream,
 
2409
                        # just in case it is not actually finished at this point
 
2410
                        next_key = None
 
2411
                        break
 
2412
 
 
2413
    def deserialise_inventory(self, revision_id, xml):
 
2414
        """Transform the xml into an inventory object.
 
2415
 
 
2416
        :param revision_id: The expected revision id of the inventory.
 
2417
        :param xml: A serialised inventory.
 
2418
        """
 
2419
        result = self._serializer.read_inventory_from_string(xml, revision_id,
 
2420
                    entry_cache=self._inventory_entry_cache)
 
2421
        if result.revision_id != revision_id:
 
2422
            raise AssertionError('revision id mismatch %s != %s' % (
 
2423
                result.revision_id, revision_id))
 
2424
        return result
 
2425
 
 
2426
    def serialise_inventory(self, inv):
 
2427
        return self._serializer.write_inventory_to_string(inv)
 
2428
 
 
2429
    def _serialise_inventory_to_lines(self, inv):
 
2430
        return self._serializer.write_inventory_to_lines(inv)
 
2431
 
 
2432
    def get_serializer_format(self):
 
2433
        return self._serializer.format_num
 
2434
 
 
2435
    @needs_read_lock
 
2436
    def get_inventory_xml(self, revision_id):
 
2437
        """Get inventory XML as a file object."""
 
2438
        texts = self._iter_inventory_xmls([revision_id], 'unordered')
 
2439
        try:
 
2440
            text, revision_id = texts.next()
 
2441
        except StopIteration:
 
2442
            raise errors.HistoryMissing(self, 'inventory', revision_id)
 
2443
        return text
 
2444
 
 
2445
    @needs_read_lock
 
2446
    def get_inventory_sha1(self, revision_id):
 
2447
        """Return the sha1 hash of the inventory entry
 
2448
        """
 
2449
        return self.get_revision(revision_id).inventory_sha1
 
2450
 
 
2451
    def get_rev_id_for_revno(self, revno, known_pair):
 
2452
        """Return the revision id of a revno, given a later (revno, revid)
 
2453
        pair in the same history.
 
2454
 
 
2455
        :return: if found (True, revid).  If the available history ran out
 
2456
            before reaching the revno, then this returns
 
2457
            (False, (closest_revno, closest_revid)).
 
2458
        """
 
2459
        known_revno, known_revid = known_pair
 
2460
        partial_history = [known_revid]
 
2461
        distance_from_known = known_revno - revno
 
2462
        if distance_from_known < 0:
 
2463
            raise ValueError(
 
2464
                'requested revno (%d) is later than given known revno (%d)'
 
2465
                % (revno, known_revno))
 
2466
        try:
 
2467
            _iter_for_revno(
 
2468
                self, partial_history, stop_index=distance_from_known)
 
2469
        except errors.RevisionNotPresent, err:
 
2470
            if err.revision_id == known_revid:
 
2471
                # The start revision (known_revid) wasn't found.
 
2472
                raise
 
2473
            # This is a stacked repository with no fallbacks, or a there's a
 
2474
            # left-hand ghost.  Either way, even though the revision named in
 
2475
            # the error isn't in this repo, we know it's the next step in this
 
2476
            # left-hand history.
 
2477
            partial_history.append(err.revision_id)
 
2478
        if len(partial_history) <= distance_from_known:
 
2479
            # Didn't find enough history to get a revid for the revno.
 
2480
            earliest_revno = known_revno - len(partial_history) + 1
 
2481
            return (False, (earliest_revno, partial_history[-1]))
 
2482
        if len(partial_history) - 1 > distance_from_known:
 
2483
            raise AssertionError('_iter_for_revno returned too much history')
 
2484
        return (True, partial_history[-1])
 
2485
 
 
2486
    def iter_reverse_revision_history(self, revision_id):
 
2487
        """Iterate backwards through revision ids in the lefthand history
 
2488
 
 
2489
        :param revision_id: The revision id to start with.  All its lefthand
 
2490
            ancestors will be traversed.
 
2491
        """
 
2492
        graph = self.get_graph()
 
2493
        next_id = revision_id
 
2494
        while True:
 
2495
            if next_id in (None, _mod_revision.NULL_REVISION):
 
2496
                return
 
2497
            try:
 
2498
                parents = graph.get_parent_map([next_id])[next_id]
 
2499
            except KeyError:
 
2500
                raise errors.RevisionNotPresent(next_id, self)
 
2501
            yield next_id
 
2502
            if len(parents) == 0:
 
2503
                return
 
2504
            else:
 
2505
                next_id = parents[0]
 
2506
 
 
2507
    @needs_read_lock
 
2508
    def get_revision_inventory(self, revision_id):
 
2509
        """Return inventory of a past revision."""
 
2510
        # TODO: Unify this with get_inventory()
 
2511
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
 
2512
        # must be the same as its revision, so this is trivial.
 
2513
        if revision_id is None:
 
2514
            # This does not make sense: if there is no revision,
 
2515
            # then it is the current tree inventory surely ?!
 
2516
            # and thus get_root_id() is something that looks at the last
 
2517
            # commit on the branch, and the get_root_id is an inventory check.
 
2518
            raise NotImplementedError
 
2519
            # return Inventory(self.get_root_id())
 
2520
        else:
 
2521
            return self.get_inventory(revision_id)
 
2522
 
 
2523
    def is_shared(self):
 
2524
        """Return True if this repository is flagged as a shared repository."""
 
2525
        raise NotImplementedError(self.is_shared)
 
2526
 
 
2527
    @needs_write_lock
 
2528
    def reconcile(self, other=None, thorough=False):
 
2529
        """Reconcile this repository."""
 
2530
        from bzrlib.reconcile import RepoReconciler
 
2531
        reconciler = RepoReconciler(self, thorough=thorough)
 
2532
        reconciler.reconcile()
 
2533
        return reconciler
 
2534
 
 
2535
    def _refresh_data(self):
 
2536
        """Helper called from lock_* to ensure coherency with disk.
 
2537
 
 
2538
        The default implementation does nothing; it is however possible
 
2539
        for repositories to maintain loaded indices across multiple locks
 
2540
        by checking inside their implementation of this method to see
 
2541
        whether their indices are still valid. This depends of course on
 
2542
        the disk format being validatable in this manner. This method is
 
2543
        also called by the refresh_data() public interface to cause a refresh
 
2544
        to occur while in a write lock so that data inserted by a smart server
 
2545
        push operation is visible on the client's instance of the physical
 
2546
        repository.
 
2547
        """
 
2548
 
 
2549
    @needs_read_lock
 
2550
    def revision_tree(self, revision_id):
 
2551
        """Return Tree for a revision on this branch.
 
2552
 
 
2553
        `revision_id` may be NULL_REVISION for the empty tree revision.
 
2554
        """
 
2555
        revision_id = _mod_revision.ensure_null(revision_id)
 
2556
        # TODO: refactor this to use an existing revision object
 
2557
        # so we don't need to read it in twice.
 
2558
        if revision_id == _mod_revision.NULL_REVISION:
 
2559
            return RevisionTree(self, Inventory(root_id=None),
 
2560
                                _mod_revision.NULL_REVISION)
 
2561
        else:
 
2562
            inv = self.get_revision_inventory(revision_id)
 
2563
            return RevisionTree(self, inv, revision_id)
 
2564
 
 
2565
    def revision_trees(self, revision_ids):
 
2566
        """Return Trees for revisions in this repository.
 
2567
 
 
2568
        :param revision_ids: a sequence of revision-ids;
 
2569
          a revision-id may not be None or 'null:'
 
2570
        """
 
2571
        inventories = self.iter_inventories(revision_ids)
 
2572
        for inv in inventories:
 
2573
            yield RevisionTree(self, inv, inv.revision_id)
 
2574
 
 
2575
    def _filtered_revision_trees(self, revision_ids, file_ids):
 
2576
        """Return Tree for a revision on this branch with only some files.
 
2577
 
 
2578
        :param revision_ids: a sequence of revision-ids;
 
2579
          a revision-id may not be None or 'null:'
 
2580
        :param file_ids: if not None, the result is filtered
 
2581
          so that only those file-ids, their parents and their
 
2582
          children are included.
 
2583
        """
 
2584
        inventories = self.iter_inventories(revision_ids)
 
2585
        for inv in inventories:
 
2586
            # Should we introduce a FilteredRevisionTree class rather
 
2587
            # than pre-filter the inventory here?
 
2588
            filtered_inv = inv.filter(file_ids)
 
2589
            yield RevisionTree(self, filtered_inv, filtered_inv.revision_id)
 
2590
 
 
2591
    @needs_read_lock
 
2592
    def get_ancestry(self, revision_id, topo_sorted=True):
 
2593
        """Return a list of revision-ids integrated by a revision.
 
2594
 
 
2595
        The first element of the list is always None, indicating the origin
 
2596
        revision.  This might change when we have history horizons, or
 
2597
        perhaps we should have a new API.
 
2598
 
 
2599
        This is topologically sorted.
 
2600
        """
 
2601
        if _mod_revision.is_null(revision_id):
 
2602
            return [None]
 
2603
        if not self.has_revision(revision_id):
 
2604
            raise errors.NoSuchRevision(self, revision_id)
 
2605
        graph = self.get_graph()
 
2606
        keys = set()
 
2607
        search = graph._make_breadth_first_searcher([revision_id])
 
2608
        while True:
 
2609
            try:
 
2610
                found, ghosts = search.next_with_ghosts()
 
2611
            except StopIteration:
 
2612
                break
 
2613
            keys.update(found)
 
2614
        if _mod_revision.NULL_REVISION in keys:
 
2615
            keys.remove(_mod_revision.NULL_REVISION)
 
2616
        if topo_sorted:
 
2617
            parent_map = graph.get_parent_map(keys)
 
2618
            keys = tsort.topo_sort(parent_map)
 
2619
        return [None] + list(keys)
 
2620
 
 
2621
    def pack(self, hint=None):
 
2622
        """Compress the data within the repository.
 
2623
 
 
2624
        This operation only makes sense for some repository types. For other
 
2625
        types it should be a no-op that just returns.
 
2626
 
 
2627
        This stub method does not require a lock, but subclasses should use
 
2628
        @needs_write_lock as this is a long running call its reasonable to
 
2629
        implicitly lock for the user.
 
2630
 
 
2631
        :param hint: If not supplied, the whole repository is packed.
 
2632
            If supplied, the repository may use the hint parameter as a
 
2633
            hint for the parts of the repository to pack. A hint can be
 
2634
            obtained from the result of commit_write_group(). Out of
 
2635
            date hints are simply ignored, because concurrent operations
 
2636
            can obsolete them rapidly.
 
2637
        """
 
2638
 
 
2639
    def get_transaction(self):
 
2640
        return self.control_files.get_transaction()
 
2641
 
 
2642
    def get_parent_map(self, revision_ids):
 
2643
        """See graph.StackedParentsProvider.get_parent_map"""
 
2644
        # revisions index works in keys; this just works in revisions
 
2645
        # therefore wrap and unwrap
 
2646
        query_keys = []
 
2647
        result = {}
 
2648
        for revision_id in revision_ids:
 
2649
            if revision_id == _mod_revision.NULL_REVISION:
 
2650
                result[revision_id] = ()
 
2651
            elif revision_id is None:
 
2652
                raise ValueError('get_parent_map(None) is not valid')
 
2653
            else:
 
2654
                query_keys.append((revision_id ,))
 
2655
        for ((revision_id,), parent_keys) in \
 
2656
                self.revisions.get_parent_map(query_keys).iteritems():
 
2657
            if parent_keys:
 
2658
                result[revision_id] = tuple(parent_revid
 
2659
                    for (parent_revid,) in parent_keys)
 
2660
            else:
 
2661
                result[revision_id] = (_mod_revision.NULL_REVISION,)
 
2662
        return result
 
2663
 
 
2664
    def _make_parents_provider(self):
 
2665
        return self
 
2666
 
 
2667
    def get_graph(self, other_repository=None):
 
2668
        """Return the graph walker for this repository format"""
 
2669
        parents_provider = self._make_parents_provider()
 
2670
        if (other_repository is not None and
 
2671
            not self.has_same_location(other_repository)):
 
2672
            parents_provider = graph.StackedParentsProvider(
 
2673
                [parents_provider, other_repository._make_parents_provider()])
 
2674
        return graph.Graph(parents_provider)
 
2675
 
 
2676
    def _get_versioned_file_checker(self, text_key_references=None,
 
2677
        ancestors=None):
 
2678
        """Return an object suitable for checking versioned files.
 
2679
        
 
2680
        :param text_key_references: if non-None, an already built
 
2681
            dictionary mapping text keys ((fileid, revision_id) tuples)
 
2682
            to whether they were referred to by the inventory of the
 
2683
            revision_id that they contain. If None, this will be
 
2684
            calculated.
 
2685
        :param ancestors: Optional result from
 
2686
            self.get_graph().get_parent_map(self.all_revision_ids()) if already
 
2687
            available.
 
2688
        """
 
2689
        return _VersionedFileChecker(self,
 
2690
            text_key_references=text_key_references, ancestors=ancestors)
 
2691
 
 
2692
    def revision_ids_to_search_result(self, result_set):
 
2693
        """Convert a set of revision ids to a graph SearchResult."""
 
2694
        result_parents = set()
 
2695
        for parents in self.get_graph().get_parent_map(
 
2696
            result_set).itervalues():
 
2697
            result_parents.update(parents)
 
2698
        included_keys = result_set.intersection(result_parents)
 
2699
        start_keys = result_set.difference(included_keys)
 
2700
        exclude_keys = result_parents.difference(result_set)
 
2701
        result = graph.SearchResult(start_keys, exclude_keys,
 
2702
            len(result_set), result_set)
 
2703
        return result
 
2704
 
 
2705
    @needs_write_lock
 
2706
    def set_make_working_trees(self, new_value):
 
2707
        """Set the policy flag for making working trees when creating branches.
 
2708
 
 
2709
        This only applies to branches that use this repository.
 
2710
 
 
2711
        The default is 'True'.
 
2712
        :param new_value: True to restore the default, False to disable making
 
2713
                          working trees.
 
2714
        """
 
2715
        raise NotImplementedError(self.set_make_working_trees)
 
2716
 
 
2717
    def make_working_trees(self):
 
2718
        """Returns the policy for making working trees on new branches."""
 
2719
        raise NotImplementedError(self.make_working_trees)
 
2720
 
 
2721
    @needs_write_lock
 
2722
    def sign_revision(self, revision_id, gpg_strategy):
 
2723
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
 
2724
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
 
2725
 
 
2726
    @needs_read_lock
 
2727
    def has_signature_for_revision_id(self, revision_id):
 
2728
        """Query for a revision signature for revision_id in the repository."""
 
2729
        if not self.has_revision(revision_id):
 
2730
            raise errors.NoSuchRevision(self, revision_id)
 
2731
        sig_present = (1 == len(
 
2732
            self.signatures.get_parent_map([(revision_id,)])))
 
2733
        return sig_present
 
2734
 
 
2735
    @needs_read_lock
 
2736
    def get_signature_text(self, revision_id):
 
2737
        """Return the text for a signature."""
 
2738
        stream = self.signatures.get_record_stream([(revision_id,)],
 
2739
            'unordered', True)
 
2740
        record = stream.next()
 
2741
        if record.storage_kind == 'absent':
 
2742
            raise errors.NoSuchRevision(self, revision_id)
 
2743
        return record.get_bytes_as('fulltext')
 
2744
 
 
2745
    @needs_read_lock
 
2746
    def check(self, revision_ids=None, callback_refs=None, check_repo=True):
 
2747
        """Check consistency of all history of given revision_ids.
 
2748
 
 
2749
        Different repository implementations should override _check().
 
2750
 
 
2751
        :param revision_ids: A non-empty list of revision_ids whose ancestry
 
2752
             will be checked.  Typically the last revision_id of a branch.
 
2753
        :param callback_refs: A dict of check-refs to resolve and callback
 
2754
            the check/_check method on the items listed as wanting the ref.
 
2755
            see bzrlib.check.
 
2756
        :param check_repo: If False do not check the repository contents, just 
 
2757
            calculate the data callback_refs requires and call them back.
 
2758
        """
 
2759
        return self._check(revision_ids, callback_refs=callback_refs,
 
2760
            check_repo=check_repo)
 
2761
 
 
2762
    def _check(self, revision_ids, callback_refs, check_repo):
 
2763
        result = check.Check(self, check_repo=check_repo)
 
2764
        result.check(callback_refs)
 
2765
        return result
 
2766
 
 
2767
    def _warn_if_deprecated(self):
 
2768
        global _deprecation_warning_done
 
2769
        if _deprecation_warning_done:
 
2770
            return
 
2771
        _deprecation_warning_done = True
 
2772
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
 
2773
                % (self._format, self.bzrdir.transport.base))
 
2774
 
 
2775
    def supports_rich_root(self):
 
2776
        return self._format.rich_root_data
 
2777
 
 
2778
    def _check_ascii_revisionid(self, revision_id, method):
 
2779
        """Private helper for ascii-only repositories."""
 
2780
        # weave repositories refuse to store revisionids that are non-ascii.
 
2781
        if revision_id is not None:
 
2782
            # weaves require ascii revision ids.
 
2783
            if isinstance(revision_id, unicode):
 
2784
                try:
 
2785
                    revision_id.encode('ascii')
 
2786
                except UnicodeEncodeError:
 
2787
                    raise errors.NonAsciiRevisionId(method, self)
 
2788
            else:
 
2789
                try:
 
2790
                    revision_id.decode('ascii')
 
2791
                except UnicodeDecodeError:
 
2792
                    raise errors.NonAsciiRevisionId(method, self)
 
2793
 
 
2794
    def revision_graph_can_have_wrong_parents(self):
 
2795
        """Is it possible for this repository to have a revision graph with
 
2796
        incorrect parents?
 
2797
 
 
2798
        If True, then this repository must also implement
 
2799
        _find_inconsistent_revision_parents so that check and reconcile can
 
2800
        check for inconsistencies before proceeding with other checks that may
 
2801
        depend on the revision index being consistent.
 
2802
        """
 
2803
        raise NotImplementedError(self.revision_graph_can_have_wrong_parents)
 
2804
 
 
2805
 
 
2806
# remove these delegates a while after bzr 0.15
 
2807
def __make_delegated(name, from_module):
 
2808
    def _deprecated_repository_forwarder():
 
2809
        symbol_versioning.warn('%s moved to %s in bzr 0.15'
 
2810
            % (name, from_module),
 
2811
            DeprecationWarning,
 
2812
            stacklevel=2)
 
2813
        m = __import__(from_module, globals(), locals(), [name])
 
2814
        try:
 
2815
            return getattr(m, name)
 
2816
        except AttributeError:
 
2817
            raise AttributeError('module %s has no name %s'
 
2818
                    % (m, name))
 
2819
    globals()[name] = _deprecated_repository_forwarder
 
2820
 
 
2821
for _name in [
 
2822
        'AllInOneRepository',
 
2823
        'WeaveMetaDirRepository',
 
2824
        'PreSplitOutRepositoryFormat',
 
2825
        'RepositoryFormat4',
 
2826
        'RepositoryFormat5',
 
2827
        'RepositoryFormat6',
 
2828
        'RepositoryFormat7',
 
2829
        ]:
 
2830
    __make_delegated(_name, 'bzrlib.repofmt.weaverepo')
 
2831
 
 
2832
for _name in [
 
2833
        'KnitRepository',
 
2834
        'RepositoryFormatKnit',
 
2835
        'RepositoryFormatKnit1',
 
2836
        ]:
 
2837
    __make_delegated(_name, 'bzrlib.repofmt.knitrepo')
 
2838
 
 
2839
 
 
2840
def install_revision(repository, rev, revision_tree):
 
2841
    """Install all revision data into a repository."""
 
2842
    install_revisions(repository, [(rev, revision_tree, None)])
 
2843
 
 
2844
 
 
2845
def install_revisions(repository, iterable, num_revisions=None, pb=None):
 
2846
    """Install all revision data into a repository.
 
2847
 
 
2848
    Accepts an iterable of revision, tree, signature tuples.  The signature
 
2849
    may be None.
 
2850
    """
 
2851
    repository.start_write_group()
 
2852
    try:
 
2853
        inventory_cache = lru_cache.LRUCache(10)
 
2854
        for n, (revision, revision_tree, signature) in enumerate(iterable):
 
2855
            _install_revision(repository, revision, revision_tree, signature,
 
2856
                inventory_cache)
 
2857
            if pb is not None:
 
2858
                pb.update('Transferring revisions', n + 1, num_revisions)
 
2859
    except:
 
2860
        repository.abort_write_group()
 
2861
        raise
 
2862
    else:
 
2863
        repository.commit_write_group()
 
2864
 
 
2865
 
 
2866
def _install_revision(repository, rev, revision_tree, signature,
 
2867
    inventory_cache):
 
2868
    """Install all revision data into a repository."""
 
2869
    present_parents = []
 
2870
    parent_trees = {}
 
2871
    for p_id in rev.parent_ids:
 
2872
        if repository.has_revision(p_id):
 
2873
            present_parents.append(p_id)
 
2874
            parent_trees[p_id] = repository.revision_tree(p_id)
 
2875
        else:
 
2876
            parent_trees[p_id] = repository.revision_tree(
 
2877
                                     _mod_revision.NULL_REVISION)
 
2878
 
 
2879
    inv = revision_tree.inventory
 
2880
    entries = inv.iter_entries()
 
2881
    # backwards compatibility hack: skip the root id.
 
2882
    if not repository.supports_rich_root():
 
2883
        path, root = entries.next()
 
2884
        if root.revision != rev.revision_id:
 
2885
            raise errors.IncompatibleRevision(repr(repository))
 
2886
    text_keys = {}
 
2887
    for path, ie in entries:
 
2888
        text_keys[(ie.file_id, ie.revision)] = ie
 
2889
    text_parent_map = repository.texts.get_parent_map(text_keys)
 
2890
    missing_texts = set(text_keys) - set(text_parent_map)
 
2891
    # Add the texts that are not already present
 
2892
    for text_key in missing_texts:
 
2893
        ie = text_keys[text_key]
 
2894
        text_parents = []
 
2895
        # FIXME: TODO: The following loop overlaps/duplicates that done by
 
2896
        # commit to determine parents. There is a latent/real bug here where
 
2897
        # the parents inserted are not those commit would do - in particular
 
2898
        # they are not filtered by heads(). RBC, AB
 
2899
        for revision, tree in parent_trees.iteritems():
 
2900
            if ie.file_id not in tree:
 
2901
                continue
 
2902
            parent_id = tree.inventory[ie.file_id].revision
 
2903
            if parent_id in text_parents:
 
2904
                continue
 
2905
            text_parents.append((ie.file_id, parent_id))
 
2906
        lines = revision_tree.get_file(ie.file_id).readlines()
 
2907
        repository.texts.add_lines(text_key, text_parents, lines)
 
2908
    try:
 
2909
        # install the inventory
 
2910
        if repository._format._commit_inv_deltas and len(rev.parent_ids):
 
2911
            # Cache this inventory
 
2912
            inventory_cache[rev.revision_id] = inv
 
2913
            try:
 
2914
                basis_inv = inventory_cache[rev.parent_ids[0]]
 
2915
            except KeyError:
 
2916
                repository.add_inventory(rev.revision_id, inv, present_parents)
 
2917
            else:
 
2918
                delta = inv._make_delta(basis_inv)
 
2919
                repository.add_inventory_by_delta(rev.parent_ids[0], delta,
 
2920
                    rev.revision_id, present_parents)
 
2921
        else:
 
2922
            repository.add_inventory(rev.revision_id, inv, present_parents)
 
2923
    except errors.RevisionAlreadyPresent:
 
2924
        pass
 
2925
    if signature is not None:
 
2926
        repository.add_signature_text(rev.revision_id, signature)
 
2927
    repository.add_revision(rev.revision_id, rev, inv)
 
2928
 
 
2929
 
 
2930
class MetaDirRepository(Repository):
 
2931
    """Repositories in the new meta-dir layout.
 
2932
 
 
2933
    :ivar _transport: Transport for access to repository control files,
 
2934
        typically pointing to .bzr/repository.
 
2935
    """
 
2936
 
 
2937
    def __init__(self, _format, a_bzrdir, control_files):
 
2938
        super(MetaDirRepository, self).__init__(_format, a_bzrdir, control_files)
 
2939
        self._transport = control_files._transport
 
2940
 
 
2941
    def is_shared(self):
 
2942
        """Return True if this repository is flagged as a shared repository."""
 
2943
        return self._transport.has('shared-storage')
 
2944
 
 
2945
    @needs_write_lock
 
2946
    def set_make_working_trees(self, new_value):
 
2947
        """Set the policy flag for making working trees when creating branches.
 
2948
 
 
2949
        This only applies to branches that use this repository.
 
2950
 
 
2951
        The default is 'True'.
 
2952
        :param new_value: True to restore the default, False to disable making
 
2953
                          working trees.
 
2954
        """
 
2955
        if new_value:
 
2956
            try:
 
2957
                self._transport.delete('no-working-trees')
 
2958
            except errors.NoSuchFile:
 
2959
                pass
 
2960
        else:
 
2961
            self._transport.put_bytes('no-working-trees', '',
 
2962
                mode=self.bzrdir._get_file_mode())
 
2963
 
 
2964
    def make_working_trees(self):
 
2965
        """Returns the policy for making working trees on new branches."""
 
2966
        return not self._transport.has('no-working-trees')
 
2967
 
 
2968
 
 
2969
class MetaDirVersionedFileRepository(MetaDirRepository):
 
2970
    """Repositories in a meta-dir, that work via versioned file objects."""
 
2971
 
 
2972
    def __init__(self, _format, a_bzrdir, control_files):
 
2973
        super(MetaDirVersionedFileRepository, self).__init__(_format, a_bzrdir,
 
2974
            control_files)
 
2975
 
 
2976
 
 
2977
network_format_registry = registry.FormatRegistry()
 
2978
"""Registry of formats indexed by their network name.
 
2979
 
 
2980
The network name for a repository format is an identifier that can be used when
 
2981
referring to formats with smart server operations. See
 
2982
RepositoryFormat.network_name() for more detail.
 
2983
"""
 
2984
 
 
2985
 
 
2986
format_registry = registry.FormatRegistry(network_format_registry)
 
2987
"""Registry of formats, indexed by their BzrDirMetaFormat format string.
 
2988
 
 
2989
This can contain either format instances themselves, or classes/factories that
 
2990
can be called to obtain one.
 
2991
"""
 
2992
 
 
2993
 
 
2994
#####################################################################
 
2995
# Repository Formats
 
2996
 
 
2997
class RepositoryFormat(object):
 
2998
    """A repository format.
 
2999
 
 
3000
    Formats provide four things:
 
3001
     * An initialization routine to construct repository data on disk.
 
3002
     * a optional format string which is used when the BzrDir supports
 
3003
       versioned children.
 
3004
     * an open routine which returns a Repository instance.
 
3005
     * A network name for referring to the format in smart server RPC
 
3006
       methods.
 
3007
 
 
3008
    There is one and only one Format subclass for each on-disk format. But
 
3009
    there can be one Repository subclass that is used for several different
 
3010
    formats. The _format attribute on a Repository instance can be used to
 
3011
    determine the disk format.
 
3012
 
 
3013
    Formats are placed in a registry by their format string for reference
 
3014
    during opening. These should be subclasses of RepositoryFormat for
 
3015
    consistency.
 
3016
 
 
3017
    Once a format is deprecated, just deprecate the initialize and open
 
3018
    methods on the format class. Do not deprecate the object, as the
 
3019
    object may be created even when a repository instance hasn't been
 
3020
    created.
 
3021
 
 
3022
    Common instance attributes:
 
3023
    _matchingbzrdir - the bzrdir format that the repository format was
 
3024
    originally written to work with. This can be used if manually
 
3025
    constructing a bzrdir and repository, or more commonly for test suite
 
3026
    parameterization.
 
3027
    """
 
3028
 
 
3029
    # Set to True or False in derived classes. True indicates that the format
 
3030
    # supports ghosts gracefully.
 
3031
    supports_ghosts = None
 
3032
    # Can this repository be given external locations to lookup additional
 
3033
    # data. Set to True or False in derived classes.
 
3034
    supports_external_lookups = None
 
3035
    # Does this format support CHK bytestring lookups. Set to True or False in
 
3036
    # derived classes.
 
3037
    supports_chks = None
 
3038
    # Should commit add an inventory, or an inventory delta to the repository.
 
3039
    _commit_inv_deltas = True
 
3040
    # What order should fetch operations request streams in?
 
3041
    # The default is unordered as that is the cheapest for an origin to
 
3042
    # provide.
 
3043
    _fetch_order = 'unordered'
 
3044
    # Does this repository format use deltas that can be fetched as-deltas ?
 
3045
    # (E.g. knits, where the knit deltas can be transplanted intact.
 
3046
    # We default to False, which will ensure that enough data to get
 
3047
    # a full text out of any fetch stream will be grabbed.
 
3048
    _fetch_uses_deltas = False
 
3049
    # Should fetch trigger a reconcile after the fetch? Only needed for
 
3050
    # some repository formats that can suffer internal inconsistencies.
 
3051
    _fetch_reconcile = False
 
3052
    # Does this format have < O(tree_size) delta generation. Used to hint what
 
3053
    # code path for commit, amongst other things.
 
3054
    fast_deltas = None
 
3055
    # Does doing a pack operation compress data? Useful for the pack UI command
 
3056
    # (so if there is one pack, the operation can still proceed because it may
 
3057
    # help), and for fetching when data won't have come from the same
 
3058
    # compressor.
 
3059
    pack_compresses = False
 
3060
 
 
3061
    def __str__(self):
 
3062
        return "<%s>" % self.__class__.__name__
 
3063
 
 
3064
    def __eq__(self, other):
 
3065
        # format objects are generally stateless
 
3066
        return isinstance(other, self.__class__)
 
3067
 
 
3068
    def __ne__(self, other):
 
3069
        return not self == other
 
3070
 
 
3071
    @classmethod
 
3072
    def find_format(klass, a_bzrdir):
 
3073
        """Return the format for the repository object in a_bzrdir.
 
3074
 
 
3075
        This is used by bzr native formats that have a "format" file in
 
3076
        the repository.  Other methods may be used by different types of
 
3077
        control directory.
 
3078
        """
 
3079
        try:
 
3080
            transport = a_bzrdir.get_repository_transport(None)
 
3081
            format_string = transport.get("format").read()
 
3082
            return format_registry.get(format_string)
 
3083
        except errors.NoSuchFile:
 
3084
            raise errors.NoRepositoryPresent(a_bzrdir)
 
3085
        except KeyError:
 
3086
            raise errors.UnknownFormatError(format=format_string,
 
3087
                                            kind='repository')
 
3088
 
 
3089
    @classmethod
 
3090
    def register_format(klass, format):
 
3091
        format_registry.register(format.get_format_string(), format)
 
3092
 
 
3093
    @classmethod
 
3094
    def unregister_format(klass, format):
 
3095
        format_registry.remove(format.get_format_string())
 
3096
 
 
3097
    @classmethod
 
3098
    def get_default_format(klass):
 
3099
        """Return the current default format."""
 
3100
        from bzrlib import bzrdir
 
3101
        return bzrdir.format_registry.make_bzrdir('default').repository_format
 
3102
 
 
3103
    def get_format_string(self):
 
3104
        """Return the ASCII format string that identifies this format.
 
3105
 
 
3106
        Note that in pre format ?? repositories the format string is
 
3107
        not permitted nor written to disk.
 
3108
        """
 
3109
        raise NotImplementedError(self.get_format_string)
 
3110
 
 
3111
    def get_format_description(self):
 
3112
        """Return the short description for this format."""
 
3113
        raise NotImplementedError(self.get_format_description)
 
3114
 
 
3115
    # TODO: this shouldn't be in the base class, it's specific to things that
 
3116
    # use weaves or knits -- mbp 20070207
 
3117
    def _get_versioned_file_store(self,
 
3118
                                  name,
 
3119
                                  transport,
 
3120
                                  control_files,
 
3121
                                  prefixed=True,
 
3122
                                  versionedfile_class=None,
 
3123
                                  versionedfile_kwargs={},
 
3124
                                  escaped=False):
 
3125
        if versionedfile_class is None:
 
3126
            versionedfile_class = self._versionedfile_class
 
3127
        weave_transport = control_files._transport.clone(name)
 
3128
        dir_mode = control_files._dir_mode
 
3129
        file_mode = control_files._file_mode
 
3130
        return VersionedFileStore(weave_transport, prefixed=prefixed,
 
3131
                                  dir_mode=dir_mode,
 
3132
                                  file_mode=file_mode,
 
3133
                                  versionedfile_class=versionedfile_class,
 
3134
                                  versionedfile_kwargs=versionedfile_kwargs,
 
3135
                                  escaped=escaped)
 
3136
 
 
3137
    def initialize(self, a_bzrdir, shared=False):
 
3138
        """Initialize a repository of this format in a_bzrdir.
 
3139
 
 
3140
        :param a_bzrdir: The bzrdir to put the new repository in it.
 
3141
        :param shared: The repository should be initialized as a sharable one.
 
3142
        :returns: The new repository object.
 
3143
 
 
3144
        This may raise UninitializableFormat if shared repository are not
 
3145
        compatible the a_bzrdir.
 
3146
        """
 
3147
        raise NotImplementedError(self.initialize)
 
3148
 
 
3149
    def is_supported(self):
 
3150
        """Is this format supported?
 
3151
 
 
3152
        Supported formats must be initializable and openable.
 
3153
        Unsupported formats may not support initialization or committing or
 
3154
        some other features depending on the reason for not being supported.
 
3155
        """
 
3156
        return True
 
3157
 
 
3158
    def network_name(self):
 
3159
        """A simple byte string uniquely identifying this format for RPC calls.
 
3160
 
 
3161
        MetaDir repository formats use their disk format string to identify the
 
3162
        repository over the wire. All in one formats such as bzr < 0.8, and
 
3163
        foreign formats like svn/git and hg should use some marker which is
 
3164
        unique and immutable.
 
3165
        """
 
3166
        raise NotImplementedError(self.network_name)
 
3167
 
 
3168
    def check_conversion_target(self, target_format):
 
3169
        if self.rich_root_data and not target_format.rich_root_data:
 
3170
            raise errors.BadConversionTarget(
 
3171
                'Does not support rich root data.', target_format,
 
3172
                from_format=self)
 
3173
        if (self.supports_tree_reference and 
 
3174
            not getattr(target_format, 'supports_tree_reference', False)):
 
3175
            raise errors.BadConversionTarget(
 
3176
                'Does not support nested trees', target_format,
 
3177
                from_format=self)
 
3178
 
 
3179
    def open(self, a_bzrdir, _found=False):
 
3180
        """Return an instance of this format for the bzrdir a_bzrdir.
 
3181
 
 
3182
        _found is a private parameter, do not use it.
 
3183
        """
 
3184
        raise NotImplementedError(self.open)
 
3185
 
 
3186
 
 
3187
class MetaDirRepositoryFormat(RepositoryFormat):
 
3188
    """Common base class for the new repositories using the metadir layout."""
 
3189
 
 
3190
    rich_root_data = False
 
3191
    supports_tree_reference = False
 
3192
    supports_external_lookups = False
 
3193
 
 
3194
    @property
 
3195
    def _matchingbzrdir(self):
 
3196
        matching = bzrdir.BzrDirMetaFormat1()
 
3197
        matching.repository_format = self
 
3198
        return matching
 
3199
 
 
3200
    def __init__(self):
 
3201
        super(MetaDirRepositoryFormat, self).__init__()
 
3202
 
 
3203
    def _create_control_files(self, a_bzrdir):
 
3204
        """Create the required files and the initial control_files object."""
 
3205
        # FIXME: RBC 20060125 don't peek under the covers
 
3206
        # NB: no need to escape relative paths that are url safe.
 
3207
        repository_transport = a_bzrdir.get_repository_transport(self)
 
3208
        control_files = lockable_files.LockableFiles(repository_transport,
 
3209
                                'lock', lockdir.LockDir)
 
3210
        control_files.create_lock()
 
3211
        return control_files
 
3212
 
 
3213
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
 
3214
        """Upload the initial blank content."""
 
3215
        control_files = self._create_control_files(a_bzrdir)
 
3216
        control_files.lock_write()
 
3217
        transport = control_files._transport
 
3218
        if shared == True:
 
3219
            utf8_files += [('shared-storage', '')]
 
3220
        try:
 
3221
            transport.mkdir_multi(dirs, mode=a_bzrdir._get_dir_mode())
 
3222
            for (filename, content_stream) in files:
 
3223
                transport.put_file(filename, content_stream,
 
3224
                    mode=a_bzrdir._get_file_mode())
 
3225
            for (filename, content_bytes) in utf8_files:
 
3226
                transport.put_bytes_non_atomic(filename, content_bytes,
 
3227
                    mode=a_bzrdir._get_file_mode())
 
3228
        finally:
 
3229
            control_files.unlock()
 
3230
 
 
3231
    def network_name(self):
 
3232
        """Metadir formats have matching disk and network format strings."""
 
3233
        return self.get_format_string()
 
3234
 
 
3235
 
 
3236
# Pre-0.8 formats that don't have a disk format string (because they are
 
3237
# versioned by the matching control directory). We use the control directories
 
3238
# disk format string as a key for the network_name because they meet the
 
3239
# constraints (simple string, unique, immutable).
 
3240
network_format_registry.register_lazy(
 
3241
    "Bazaar-NG branch, format 5\n",
 
3242
    'bzrlib.repofmt.weaverepo',
 
3243
    'RepositoryFormat5',
 
3244
)
 
3245
network_format_registry.register_lazy(
 
3246
    "Bazaar-NG branch, format 6\n",
 
3247
    'bzrlib.repofmt.weaverepo',
 
3248
    'RepositoryFormat6',
 
3249
)
 
3250
 
 
3251
# formats which have no format string are not discoverable or independently
 
3252
# creatable on disk, so are not registered in format_registry.  They're
 
3253
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
 
3254
# needed, it's constructed directly by the BzrDir.  Non-native formats where
 
3255
# the repository is not separately opened are similar.
 
3256
 
 
3257
format_registry.register_lazy(
 
3258
    'Bazaar-NG Repository format 7',
 
3259
    'bzrlib.repofmt.weaverepo',
 
3260
    'RepositoryFormat7'
 
3261
    )
 
3262
 
 
3263
format_registry.register_lazy(
 
3264
    'Bazaar-NG Knit Repository Format 1',
 
3265
    'bzrlib.repofmt.knitrepo',
 
3266
    'RepositoryFormatKnit1',
 
3267
    )
 
3268
 
 
3269
format_registry.register_lazy(
 
3270
    'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
 
3271
    'bzrlib.repofmt.knitrepo',
 
3272
    'RepositoryFormatKnit3',
 
3273
    )
 
3274
 
 
3275
format_registry.register_lazy(
 
3276
    'Bazaar Knit Repository Format 4 (bzr 1.0)\n',
 
3277
    'bzrlib.repofmt.knitrepo',
 
3278
    'RepositoryFormatKnit4',
 
3279
    )
 
3280
 
 
3281
# Pack-based formats. There is one format for pre-subtrees, and one for
 
3282
# post-subtrees to allow ease of testing.
 
3283
# NOTE: These are experimental in 0.92. Stable in 1.0 and above
 
3284
format_registry.register_lazy(
 
3285
    'Bazaar pack repository format 1 (needs bzr 0.92)\n',
 
3286
    'bzrlib.repofmt.pack_repo',
 
3287
    'RepositoryFormatKnitPack1',
 
3288
    )
 
3289
format_registry.register_lazy(
 
3290
    'Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n',
 
3291
    'bzrlib.repofmt.pack_repo',
 
3292
    'RepositoryFormatKnitPack3',
 
3293
    )
 
3294
format_registry.register_lazy(
 
3295
    'Bazaar pack repository format 1 with rich root (needs bzr 1.0)\n',
 
3296
    'bzrlib.repofmt.pack_repo',
 
3297
    'RepositoryFormatKnitPack4',
 
3298
    )
 
3299
format_registry.register_lazy(
 
3300
    'Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n',
 
3301
    'bzrlib.repofmt.pack_repo',
 
3302
    'RepositoryFormatKnitPack5',
 
3303
    )
 
3304
format_registry.register_lazy(
 
3305
    'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n',
 
3306
    'bzrlib.repofmt.pack_repo',
 
3307
    'RepositoryFormatKnitPack5RichRoot',
 
3308
    )
 
3309
format_registry.register_lazy(
 
3310
    'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n',
 
3311
    'bzrlib.repofmt.pack_repo',
 
3312
    'RepositoryFormatKnitPack5RichRootBroken',
 
3313
    )
 
3314
format_registry.register_lazy(
 
3315
    'Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n',
 
3316
    'bzrlib.repofmt.pack_repo',
 
3317
    'RepositoryFormatKnitPack6',
 
3318
    )
 
3319
format_registry.register_lazy(
 
3320
    'Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n',
 
3321
    'bzrlib.repofmt.pack_repo',
 
3322
    'RepositoryFormatKnitPack6RichRoot',
 
3323
    )
 
3324
 
 
3325
# Development formats.
 
3326
# Obsolete but kept pending a CHK based subtree format.
 
3327
format_registry.register_lazy(
 
3328
    ("Bazaar development format 2 with subtree support "
 
3329
        "(needs bzr.dev from before 1.8)\n"),
 
3330
    'bzrlib.repofmt.pack_repo',
 
3331
    'RepositoryFormatPackDevelopment2Subtree',
 
3332
    )
 
3333
 
 
3334
# 1.14->1.16 go below here
 
3335
format_registry.register_lazy(
 
3336
    'Bazaar development format - group compression and chk inventory'
 
3337
        ' (needs bzr.dev from 1.14)\n',
 
3338
    'bzrlib.repofmt.groupcompress_repo',
 
3339
    'RepositoryFormatCHK1',
 
3340
    )
 
3341
 
 
3342
format_registry.register_lazy(
 
3343
    'Bazaar development format - chk repository with bencode revision '
 
3344
        'serialization (needs bzr.dev from 1.16)\n',
 
3345
    'bzrlib.repofmt.groupcompress_repo',
 
3346
    'RepositoryFormatCHK2',
 
3347
    )
 
3348
format_registry.register_lazy(
 
3349
    'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
 
3350
    'bzrlib.repofmt.groupcompress_repo',
 
3351
    'RepositoryFormat2a',
 
3352
    )
 
3353
 
 
3354
 
 
3355
class InterRepository(InterObject):
 
3356
    """This class represents operations taking place between two repositories.
 
3357
 
 
3358
    Its instances have methods like copy_content and fetch, and contain
 
3359
    references to the source and target repositories these operations can be
 
3360
    carried out on.
 
3361
 
 
3362
    Often we will provide convenience methods on 'repository' which carry out
 
3363
    operations with another repository - they will always forward to
 
3364
    InterRepository.get(other).method_name(parameters).
 
3365
    """
 
3366
 
 
3367
    _walk_to_common_revisions_batch_size = 50
 
3368
    _optimisers = []
 
3369
    """The available optimised InterRepository types."""
 
3370
 
 
3371
    @needs_write_lock
 
3372
    def copy_content(self, revision_id=None):
 
3373
        """Make a complete copy of the content in self into destination.
 
3374
 
 
3375
        This is a destructive operation! Do not use it on existing
 
3376
        repositories.
 
3377
 
 
3378
        :param revision_id: Only copy the content needed to construct
 
3379
                            revision_id and its parents.
 
3380
        """
 
3381
        try:
 
3382
            self.target.set_make_working_trees(self.source.make_working_trees())
 
3383
        except NotImplementedError:
 
3384
            pass
 
3385
        self.target.fetch(self.source, revision_id=revision_id)
 
3386
 
 
3387
    @needs_write_lock
 
3388
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
3389
            fetch_spec=None):
 
3390
        """Fetch the content required to construct revision_id.
 
3391
 
 
3392
        The content is copied from self.source to self.target.
 
3393
 
 
3394
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
3395
                            content is copied.
 
3396
        :param pb: optional progress bar to use for progress reports. If not
 
3397
                   provided a default one will be created.
 
3398
        :return: None.
 
3399
        """
 
3400
        from bzrlib.fetch import RepoFetcher
 
3401
        f = RepoFetcher(to_repository=self.target,
 
3402
                               from_repository=self.source,
 
3403
                               last_revision=revision_id,
 
3404
                               fetch_spec=fetch_spec,
 
3405
                               pb=pb, find_ghosts=find_ghosts)
 
3406
 
 
3407
    def _walk_to_common_revisions(self, revision_ids):
 
3408
        """Walk out from revision_ids in source to revisions target has.
 
3409
 
 
3410
        :param revision_ids: The start point for the search.
 
3411
        :return: A set of revision ids.
 
3412
        """
 
3413
        target_graph = self.target.get_graph()
 
3414
        revision_ids = frozenset(revision_ids)
 
3415
        missing_revs = set()
 
3416
        source_graph = self.source.get_graph()
 
3417
        # ensure we don't pay silly lookup costs.
 
3418
        searcher = source_graph._make_breadth_first_searcher(revision_ids)
 
3419
        null_set = frozenset([_mod_revision.NULL_REVISION])
 
3420
        searcher_exhausted = False
 
3421
        while True:
 
3422
            next_revs = set()
 
3423
            ghosts = set()
 
3424
            # Iterate the searcher until we have enough next_revs
 
3425
            while len(next_revs) < self._walk_to_common_revisions_batch_size:
 
3426
                try:
 
3427
                    next_revs_part, ghosts_part = searcher.next_with_ghosts()
 
3428
                    next_revs.update(next_revs_part)
 
3429
                    ghosts.update(ghosts_part)
 
3430
                except StopIteration:
 
3431
                    searcher_exhausted = True
 
3432
                    break
 
3433
            # If there are ghosts in the source graph, and the caller asked for
 
3434
            # them, make sure that they are present in the target.
 
3435
            # We don't care about other ghosts as we can't fetch them and
 
3436
            # haven't been asked to.
 
3437
            ghosts_to_check = set(revision_ids.intersection(ghosts))
 
3438
            revs_to_get = set(next_revs).union(ghosts_to_check)
 
3439
            if revs_to_get:
 
3440
                have_revs = set(target_graph.get_parent_map(revs_to_get))
 
3441
                # we always have NULL_REVISION present.
 
3442
                have_revs = have_revs.union(null_set)
 
3443
                # Check if the target is missing any ghosts we need.
 
3444
                ghosts_to_check.difference_update(have_revs)
 
3445
                if ghosts_to_check:
 
3446
                    # One of the caller's revision_ids is a ghost in both the
 
3447
                    # source and the target.
 
3448
                    raise errors.NoSuchRevision(
 
3449
                        self.source, ghosts_to_check.pop())
 
3450
                missing_revs.update(next_revs - have_revs)
 
3451
                # Because we may have walked past the original stop point, make
 
3452
                # sure everything is stopped
 
3453
                stop_revs = searcher.find_seen_ancestors(have_revs)
 
3454
                searcher.stop_searching_any(stop_revs)
 
3455
            if searcher_exhausted:
 
3456
                break
 
3457
        return searcher.get_result()
 
3458
 
 
3459
    @needs_read_lock
 
3460
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
 
3461
        """Return the revision ids that source has that target does not.
 
3462
 
 
3463
        :param revision_id: only return revision ids included by this
 
3464
                            revision_id.
 
3465
        :param find_ghosts: If True find missing revisions in deep history
 
3466
            rather than just finding the surface difference.
 
3467
        :return: A bzrlib.graph.SearchResult.
 
3468
        """
 
3469
        # stop searching at found target revisions.
 
3470
        if not find_ghosts and revision_id is not None:
 
3471
            return self._walk_to_common_revisions([revision_id])
 
3472
        # generic, possibly worst case, slow code path.
 
3473
        target_ids = set(self.target.all_revision_ids())
 
3474
        if revision_id is not None:
 
3475
            source_ids = self.source.get_ancestry(revision_id)
 
3476
            if source_ids[0] is not None:
 
3477
                raise AssertionError()
 
3478
            source_ids.pop(0)
 
3479
        else:
 
3480
            source_ids = self.source.all_revision_ids()
 
3481
        result_set = set(source_ids).difference(target_ids)
 
3482
        return self.source.revision_ids_to_search_result(result_set)
 
3483
 
 
3484
    @staticmethod
 
3485
    def _same_model(source, target):
 
3486
        """True if source and target have the same data representation.
 
3487
 
 
3488
        Note: this is always called on the base class; overriding it in a
 
3489
        subclass will have no effect.
 
3490
        """
 
3491
        try:
 
3492
            InterRepository._assert_same_model(source, target)
 
3493
            return True
 
3494
        except errors.IncompatibleRepositories, e:
 
3495
            return False
 
3496
 
 
3497
    @staticmethod
 
3498
    def _assert_same_model(source, target):
 
3499
        """Raise an exception if two repositories do not use the same model.
 
3500
        """
 
3501
        if source.supports_rich_root() != target.supports_rich_root():
 
3502
            raise errors.IncompatibleRepositories(source, target,
 
3503
                "different rich-root support")
 
3504
        if source._serializer != target._serializer:
 
3505
            raise errors.IncompatibleRepositories(source, target,
 
3506
                "different serializers")
 
3507
 
 
3508
 
 
3509
class InterSameDataRepository(InterRepository):
 
3510
    """Code for converting between repositories that represent the same data.
 
3511
 
 
3512
    Data format and model must match for this to work.
 
3513
    """
 
3514
 
 
3515
    @classmethod
 
3516
    def _get_repo_format_to_test(self):
 
3517
        """Repository format for testing with.
 
3518
 
 
3519
        InterSameData can pull from subtree to subtree and from non-subtree to
 
3520
        non-subtree, so we test this with the richest repository format.
 
3521
        """
 
3522
        from bzrlib.repofmt import knitrepo
 
3523
        return knitrepo.RepositoryFormatKnit3()
 
3524
 
 
3525
    @staticmethod
 
3526
    def is_compatible(source, target):
 
3527
        return InterRepository._same_model(source, target)
 
3528
 
 
3529
 
 
3530
class InterWeaveRepo(InterSameDataRepository):
 
3531
    """Optimised code paths between Weave based repositories.
 
3532
 
 
3533
    This should be in bzrlib/repofmt/weaverepo.py but we have not yet
 
3534
    implemented lazy inter-object optimisation.
 
3535
    """
 
3536
 
 
3537
    @classmethod
 
3538
    def _get_repo_format_to_test(self):
 
3539
        from bzrlib.repofmt import weaverepo
 
3540
        return weaverepo.RepositoryFormat7()
 
3541
 
 
3542
    @staticmethod
 
3543
    def is_compatible(source, target):
 
3544
        """Be compatible with known Weave formats.
 
3545
 
 
3546
        We don't test for the stores being of specific types because that
 
3547
        could lead to confusing results, and there is no need to be
 
3548
        overly general.
 
3549
        """
 
3550
        from bzrlib.repofmt.weaverepo import (
 
3551
                RepositoryFormat5,
 
3552
                RepositoryFormat6,
 
3553
                RepositoryFormat7,
 
3554
                )
 
3555
        try:
 
3556
            return (isinstance(source._format, (RepositoryFormat5,
 
3557
                                                RepositoryFormat6,
 
3558
                                                RepositoryFormat7)) and
 
3559
                    isinstance(target._format, (RepositoryFormat5,
 
3560
                                                RepositoryFormat6,
 
3561
                                                RepositoryFormat7)))
 
3562
        except AttributeError:
 
3563
            return False
 
3564
 
 
3565
    @needs_write_lock
 
3566
    def copy_content(self, revision_id=None):
 
3567
        """See InterRepository.copy_content()."""
 
3568
        # weave specific optimised path:
 
3569
        try:
 
3570
            self.target.set_make_working_trees(self.source.make_working_trees())
 
3571
        except (errors.RepositoryUpgradeRequired, NotImplemented):
 
3572
            pass
 
3573
        # FIXME do not peek!
 
3574
        if self.source._transport.listable():
 
3575
            pb = ui.ui_factory.nested_progress_bar()
 
3576
            try:
 
3577
                self.target.texts.insert_record_stream(
 
3578
                    self.source.texts.get_record_stream(
 
3579
                        self.source.texts.keys(), 'topological', False))
 
3580
                pb.update('copying inventory', 0, 1)
 
3581
                self.target.inventories.insert_record_stream(
 
3582
                    self.source.inventories.get_record_stream(
 
3583
                        self.source.inventories.keys(), 'topological', False))
 
3584
                self.target.signatures.insert_record_stream(
 
3585
                    self.source.signatures.get_record_stream(
 
3586
                        self.source.signatures.keys(),
 
3587
                        'unordered', True))
 
3588
                self.target.revisions.insert_record_stream(
 
3589
                    self.source.revisions.get_record_stream(
 
3590
                        self.source.revisions.keys(),
 
3591
                        'topological', True))
 
3592
            finally:
 
3593
                pb.finished()
 
3594
        else:
 
3595
            self.target.fetch(self.source, revision_id=revision_id)
 
3596
 
 
3597
    @needs_read_lock
 
3598
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
 
3599
        """See InterRepository.missing_revision_ids()."""
 
3600
        # we want all revisions to satisfy revision_id in source.
 
3601
        # but we don't want to stat every file here and there.
 
3602
        # we want then, all revisions other needs to satisfy revision_id
 
3603
        # checked, but not those that we have locally.
 
3604
        # so the first thing is to get a subset of the revisions to
 
3605
        # satisfy revision_id in source, and then eliminate those that
 
3606
        # we do already have.
 
3607
        # this is slow on high latency connection to self, but as this
 
3608
        # disk format scales terribly for push anyway due to rewriting
 
3609
        # inventory.weave, this is considered acceptable.
 
3610
        # - RBC 20060209
 
3611
        if revision_id is not None:
 
3612
            source_ids = self.source.get_ancestry(revision_id)
 
3613
            if source_ids[0] is not None:
 
3614
                raise AssertionError()
 
3615
            source_ids.pop(0)
 
3616
        else:
 
3617
            source_ids = self.source._all_possible_ids()
 
3618
        source_ids_set = set(source_ids)
 
3619
        # source_ids is the worst possible case we may need to pull.
 
3620
        # now we want to filter source_ids against what we actually
 
3621
        # have in target, but don't try to check for existence where we know
 
3622
        # we do not have a revision as that would be pointless.
 
3623
        target_ids = set(self.target._all_possible_ids())
 
3624
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
3625
        actually_present_revisions = set(
 
3626
            self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
3627
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
3628
        if revision_id is not None:
 
3629
            # we used get_ancestry to determine source_ids then we are assured all
 
3630
            # revisions referenced are present as they are installed in topological order.
 
3631
            # and the tip revision was validated by get_ancestry.
 
3632
            result_set = required_revisions
 
3633
        else:
 
3634
            # if we just grabbed the possibly available ids, then
 
3635
            # we only have an estimate of whats available and need to validate
 
3636
            # that against the revision records.
 
3637
            result_set = set(
 
3638
                self.source._eliminate_revisions_not_present(required_revisions))
 
3639
        return self.source.revision_ids_to_search_result(result_set)
 
3640
 
 
3641
 
 
3642
class InterKnitRepo(InterSameDataRepository):
 
3643
    """Optimised code paths between Knit based repositories."""
 
3644
 
 
3645
    @classmethod
 
3646
    def _get_repo_format_to_test(self):
 
3647
        from bzrlib.repofmt import knitrepo
 
3648
        return knitrepo.RepositoryFormatKnit1()
 
3649
 
 
3650
    @staticmethod
 
3651
    def is_compatible(source, target):
 
3652
        """Be compatible with known Knit formats.
 
3653
 
 
3654
        We don't test for the stores being of specific types because that
 
3655
        could lead to confusing results, and there is no need to be
 
3656
        overly general.
 
3657
        """
 
3658
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit
 
3659
        try:
 
3660
            are_knits = (isinstance(source._format, RepositoryFormatKnit) and
 
3661
                isinstance(target._format, RepositoryFormatKnit))
 
3662
        except AttributeError:
 
3663
            return False
 
3664
        return are_knits and InterRepository._same_model(source, target)
 
3665
 
 
3666
    @needs_read_lock
 
3667
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
 
3668
        """See InterRepository.missing_revision_ids()."""
 
3669
        if revision_id is not None:
 
3670
            source_ids = self.source.get_ancestry(revision_id)
 
3671
            if source_ids[0] is not None:
 
3672
                raise AssertionError()
 
3673
            source_ids.pop(0)
 
3674
        else:
 
3675
            source_ids = self.source.all_revision_ids()
 
3676
        source_ids_set = set(source_ids)
 
3677
        # source_ids is the worst possible case we may need to pull.
 
3678
        # now we want to filter source_ids against what we actually
 
3679
        # have in target, but don't try to check for existence where we know
 
3680
        # we do not have a revision as that would be pointless.
 
3681
        target_ids = set(self.target.all_revision_ids())
 
3682
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
3683
        actually_present_revisions = set(
 
3684
            self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
3685
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
3686
        if revision_id is not None:
 
3687
            # we used get_ancestry to determine source_ids then we are assured all
 
3688
            # revisions referenced are present as they are installed in topological order.
 
3689
            # and the tip revision was validated by get_ancestry.
 
3690
            result_set = required_revisions
 
3691
        else:
 
3692
            # if we just grabbed the possibly available ids, then
 
3693
            # we only have an estimate of whats available and need to validate
 
3694
            # that against the revision records.
 
3695
            result_set = set(
 
3696
                self.source._eliminate_revisions_not_present(required_revisions))
 
3697
        return self.source.revision_ids_to_search_result(result_set)
 
3698
 
 
3699
 
 
3700
class InterDifferingSerializer(InterRepository):
 
3701
 
 
3702
    @classmethod
 
3703
    def _get_repo_format_to_test(self):
 
3704
        return None
 
3705
 
 
3706
    @staticmethod
 
3707
    def is_compatible(source, target):
 
3708
        """Be compatible with Knit2 source and Knit3 target"""
 
3709
        # This is redundant with format.check_conversion_target(), however that
 
3710
        # raises an exception, and we just want to say "False" as in we won't
 
3711
        # support converting between these formats.
 
3712
        if 'IDS_never' in debug.debug_flags:
 
3713
            return False
 
3714
        if source.supports_rich_root() and not target.supports_rich_root():
 
3715
            return False
 
3716
        if (source._format.supports_tree_reference
 
3717
            and not target._format.supports_tree_reference):
 
3718
            return False
 
3719
        if target._fallback_repositories and target._format.supports_chks:
 
3720
            # IDS doesn't know how to copy CHKs for the parent inventories it
 
3721
            # adds to stacked repos.
 
3722
            return False
 
3723
        if 'IDS_always' in debug.debug_flags:
 
3724
            return True
 
3725
        # Only use this code path for local source and target.  IDS does far
 
3726
        # too much IO (both bandwidth and roundtrips) over a network.
 
3727
        if not source.bzrdir.transport.base.startswith('file:///'):
 
3728
            return False
 
3729
        if not target.bzrdir.transport.base.startswith('file:///'):
 
3730
            return False
 
3731
        return True
 
3732
 
 
3733
    def _get_delta_for_revision(self, tree, parent_ids, basis_id, cache):
 
3734
        """Get the best delta and base for this revision.
 
3735
 
 
3736
        :return: (basis_id, delta)
 
3737
        """
 
3738
        possible_trees = [(parent_id, cache[parent_id])
 
3739
                          for parent_id in parent_ids
 
3740
                           if parent_id in cache]
 
3741
        if len(possible_trees) == 0:
 
3742
            # There either aren't any parents, or the parents aren't in the
 
3743
            # cache, so just use the last converted tree
 
3744
            possible_trees.append((basis_id, cache[basis_id]))
 
3745
        deltas = []
 
3746
        for basis_id, basis_tree in possible_trees:
 
3747
            delta = tree.inventory._make_delta(basis_tree.inventory)
 
3748
            deltas.append((len(delta), basis_id, delta))
 
3749
        deltas.sort()
 
3750
        return deltas[0][1:]
 
3751
 
 
3752
    def _fetch_batch(self, revision_ids, basis_id, cache):
 
3753
        """Fetch across a few revisions.
 
3754
 
 
3755
        :param revision_ids: The revisions to copy
 
3756
        :param basis_id: The revision_id of a tree that must be in cache, used
 
3757
            as a basis for delta when no other base is available
 
3758
        :param cache: A cache of RevisionTrees that we can use.
 
3759
        :return: The revision_id of the last converted tree. The RevisionTree
 
3760
            for it will be in cache
 
3761
        """
 
3762
        # Walk though all revisions; get inventory deltas, copy referenced
 
3763
        # texts that delta references, insert the delta, revision and
 
3764
        # signature.
 
3765
        root_keys_to_create = set()
 
3766
        text_keys = set()
 
3767
        pending_deltas = []
 
3768
        pending_revisions = []
 
3769
        parent_map = self.source.get_parent_map(revision_ids)
 
3770
        for tree in self.source.revision_trees(revision_ids):
 
3771
            current_revision_id = tree.get_revision_id()
 
3772
            parent_ids = parent_map.get(current_revision_id, ())
 
3773
            basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
 
3774
                                                           basis_id, cache)
 
3775
            if self._converting_to_rich_root:
 
3776
                self._revision_id_to_root_id[current_revision_id] = \
 
3777
                    tree.get_root_id()
 
3778
            # Find text entries that need to be copied
 
3779
            for old_path, new_path, file_id, entry in delta:
 
3780
                if new_path is not None:
 
3781
                    if not new_path:
 
3782
                        # This is the root
 
3783
                        if not self.target.supports_rich_root():
 
3784
                            # The target doesn't support rich root, so we don't
 
3785
                            # copy
 
3786
                            continue
 
3787
                        if self._converting_to_rich_root:
 
3788
                            # This can't be copied normally, we have to insert
 
3789
                            # it specially
 
3790
                            root_keys_to_create.add((file_id, entry.revision))
 
3791
                            continue
 
3792
                    text_keys.add((file_id, entry.revision))
 
3793
            revision = self.source.get_revision(current_revision_id)
 
3794
            pending_deltas.append((basis_id, delta,
 
3795
                current_revision_id, revision.parent_ids))
 
3796
            pending_revisions.append(revision)
 
3797
            cache[current_revision_id] = tree
 
3798
            basis_id = current_revision_id
 
3799
        # Copy file texts
 
3800
        from_texts = self.source.texts
 
3801
        to_texts = self.target.texts
 
3802
        if root_keys_to_create:
 
3803
            from bzrlib.fetch import _new_root_data_stream
 
3804
            root_stream = _new_root_data_stream(
 
3805
                root_keys_to_create, self._revision_id_to_root_id, parent_map,
 
3806
                self.source)
 
3807
            to_texts.insert_record_stream(root_stream)
 
3808
        to_texts.insert_record_stream(from_texts.get_record_stream(
 
3809
            text_keys, self.target._format._fetch_order,
 
3810
            not self.target._format._fetch_uses_deltas))
 
3811
        # insert inventory deltas
 
3812
        for delta in pending_deltas:
 
3813
            self.target.add_inventory_by_delta(*delta)
 
3814
        if self.target._fallback_repositories:
 
3815
            # Make sure this stacked repository has all the parent inventories
 
3816
            # for the new revisions that we are about to insert.  We do this
 
3817
            # before adding the revisions so that no revision is added until
 
3818
            # all the inventories it may depend on are added.
 
3819
            # Note that this is overzealous, as we may have fetched these in an
 
3820
            # earlier batch.
 
3821
            parent_ids = set()
 
3822
            revision_ids = set()
 
3823
            for revision in pending_revisions:
 
3824
                revision_ids.add(revision.revision_id)
 
3825
                parent_ids.update(revision.parent_ids)
 
3826
            parent_ids.difference_update(revision_ids)
 
3827
            parent_ids.discard(_mod_revision.NULL_REVISION)
 
3828
            parent_map = self.source.get_parent_map(parent_ids)
 
3829
            # we iterate over parent_map and not parent_ids because we don't
 
3830
            # want to try copying any revision which is a ghost
 
3831
            for parent_tree in self.source.revision_trees(parent_map):
 
3832
                current_revision_id = parent_tree.get_revision_id()
 
3833
                parents_parents = parent_map[current_revision_id]
 
3834
                basis_id, delta = self._get_delta_for_revision(parent_tree,
 
3835
                    parents_parents, basis_id, cache)
 
3836
                self.target.add_inventory_by_delta(
 
3837
                    basis_id, delta, current_revision_id, parents_parents)
 
3838
        # insert signatures and revisions
 
3839
        for revision in pending_revisions:
 
3840
            try:
 
3841
                signature = self.source.get_signature_text(
 
3842
                    revision.revision_id)
 
3843
                self.target.add_signature_text(revision.revision_id,
 
3844
                    signature)
 
3845
            except errors.NoSuchRevision:
 
3846
                pass
 
3847
            self.target.add_revision(revision.revision_id, revision)
 
3848
        return basis_id
 
3849
 
 
3850
    def _fetch_all_revisions(self, revision_ids, pb):
 
3851
        """Fetch everything for the list of revisions.
 
3852
 
 
3853
        :param revision_ids: The list of revisions to fetch. Must be in
 
3854
            topological order.
 
3855
        :param pb: A ProgressTask
 
3856
        :return: None
 
3857
        """
 
3858
        basis_id, basis_tree = self._get_basis(revision_ids[0])
 
3859
        batch_size = 100
 
3860
        cache = lru_cache.LRUCache(100)
 
3861
        cache[basis_id] = basis_tree
 
3862
        del basis_tree # We don't want to hang on to it here
 
3863
        hints = []
 
3864
        for offset in range(0, len(revision_ids), batch_size):
 
3865
            self.target.start_write_group()
 
3866
            try:
 
3867
                pb.update('Transferring revisions', offset,
 
3868
                          len(revision_ids))
 
3869
                batch = revision_ids[offset:offset+batch_size]
 
3870
                basis_id = self._fetch_batch(batch, basis_id, cache)
 
3871
            except:
 
3872
                self.target.abort_write_group()
 
3873
                raise
 
3874
            else:
 
3875
                hint = self.target.commit_write_group()
 
3876
                if hint:
 
3877
                    hints.extend(hint)
 
3878
        if hints and self.target._format.pack_compresses:
 
3879
            self.target.pack(hint=hints)
 
3880
        pb.update('Transferring revisions', len(revision_ids),
 
3881
                  len(revision_ids))
 
3882
 
 
3883
    @needs_write_lock
 
3884
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
3885
            fetch_spec=None):
 
3886
        """See InterRepository.fetch()."""
 
3887
        if fetch_spec is not None:
 
3888
            raise AssertionError("Not implemented yet...")
 
3889
        if (not self.source.supports_rich_root()
 
3890
            and self.target.supports_rich_root()):
 
3891
            self._converting_to_rich_root = True
 
3892
            self._revision_id_to_root_id = {}
 
3893
        else:
 
3894
            self._converting_to_rich_root = False
 
3895
        revision_ids = self.target.search_missing_revision_ids(self.source,
 
3896
            revision_id, find_ghosts=find_ghosts).get_keys()
 
3897
        if not revision_ids:
 
3898
            return 0, 0
 
3899
        revision_ids = tsort.topo_sort(
 
3900
            self.source.get_graph().get_parent_map(revision_ids))
 
3901
        if not revision_ids:
 
3902
            return 0, 0
 
3903
        # Walk though all revisions; get inventory deltas, copy referenced
 
3904
        # texts that delta references, insert the delta, revision and
 
3905
        # signature.
 
3906
        if pb is None:
 
3907
            my_pb = ui.ui_factory.nested_progress_bar()
 
3908
            pb = my_pb
 
3909
        else:
 
3910
            symbol_versioning.warn(
 
3911
                symbol_versioning.deprecated_in((1, 14, 0))
 
3912
                % "pb parameter to fetch()")
 
3913
            my_pb = None
 
3914
        try:
 
3915
            self._fetch_all_revisions(revision_ids, pb)
 
3916
        finally:
 
3917
            if my_pb is not None:
 
3918
                my_pb.finished()
 
3919
        return len(revision_ids), 0
 
3920
 
 
3921
    def _get_basis(self, first_revision_id):
 
3922
        """Get a revision and tree which exists in the target.
 
3923
 
 
3924
        This assumes that first_revision_id is selected for transmission
 
3925
        because all other ancestors are already present. If we can't find an
 
3926
        ancestor we fall back to NULL_REVISION since we know that is safe.
 
3927
 
 
3928
        :return: (basis_id, basis_tree)
 
3929
        """
 
3930
        first_rev = self.source.get_revision(first_revision_id)
 
3931
        try:
 
3932
            basis_id = first_rev.parent_ids[0]
 
3933
            # only valid as a basis if the target has it
 
3934
            self.target.get_revision(basis_id)
 
3935
            # Try to get a basis tree - if its a ghost it will hit the
 
3936
            # NoSuchRevision case.
 
3937
            basis_tree = self.source.revision_tree(basis_id)
 
3938
        except (IndexError, errors.NoSuchRevision):
 
3939
            basis_id = _mod_revision.NULL_REVISION
 
3940
            basis_tree = self.source.revision_tree(basis_id)
 
3941
        return basis_id, basis_tree
 
3942
 
 
3943
 
 
3944
InterRepository.register_optimiser(InterDifferingSerializer)
 
3945
InterRepository.register_optimiser(InterSameDataRepository)
 
3946
InterRepository.register_optimiser(InterWeaveRepo)
 
3947
InterRepository.register_optimiser(InterKnitRepo)
 
3948
 
 
3949
 
 
3950
class CopyConverter(object):
 
3951
    """A repository conversion tool which just performs a copy of the content.
 
3952
 
 
3953
    This is slow but quite reliable.
 
3954
    """
 
3955
 
 
3956
    def __init__(self, target_format):
 
3957
        """Create a CopyConverter.
 
3958
 
 
3959
        :param target_format: The format the resulting repository should be.
 
3960
        """
 
3961
        self.target_format = target_format
 
3962
 
 
3963
    def convert(self, repo, pb):
 
3964
        """Perform the conversion of to_convert, giving feedback via pb.
 
3965
 
 
3966
        :param to_convert: The disk object to convert.
 
3967
        :param pb: a progress bar to use for progress information.
 
3968
        """
 
3969
        self.pb = pb
 
3970
        self.count = 0
 
3971
        self.total = 4
 
3972
        # this is only useful with metadir layouts - separated repo content.
 
3973
        # trigger an assertion if not such
 
3974
        repo._format.get_format_string()
 
3975
        self.repo_dir = repo.bzrdir
 
3976
        self.step('Moving repository to repository.backup')
 
3977
        self.repo_dir.transport.move('repository', 'repository.backup')
 
3978
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
 
3979
        repo._format.check_conversion_target(self.target_format)
 
3980
        self.source_repo = repo._format.open(self.repo_dir,
 
3981
            _found=True,
 
3982
            _override_transport=backup_transport)
 
3983
        self.step('Creating new repository')
 
3984
        converted = self.target_format.initialize(self.repo_dir,
 
3985
                                                  self.source_repo.is_shared())
 
3986
        converted.lock_write()
 
3987
        try:
 
3988
            self.step('Copying content into repository.')
 
3989
            self.source_repo.copy_content_into(converted)
 
3990
        finally:
 
3991
            converted.unlock()
 
3992
        self.step('Deleting old repository content.')
 
3993
        self.repo_dir.transport.delete_tree('repository.backup')
 
3994
        self.pb.note('repository converted')
 
3995
 
 
3996
    def step(self, message):
 
3997
        """Update the pb by a step."""
 
3998
        self.count +=1
 
3999
        self.pb.update(message, self.count, self.total)
 
4000
 
 
4001
 
 
4002
_unescape_map = {
 
4003
    'apos':"'",
 
4004
    'quot':'"',
 
4005
    'amp':'&',
 
4006
    'lt':'<',
 
4007
    'gt':'>'
 
4008
}
 
4009
 
 
4010
 
 
4011
def _unescaper(match, _map=_unescape_map):
 
4012
    code = match.group(1)
 
4013
    try:
 
4014
        return _map[code]
 
4015
    except KeyError:
 
4016
        if not code.startswith('#'):
 
4017
            raise
 
4018
        return unichr(int(code[1:])).encode('utf8')
 
4019
 
 
4020
 
 
4021
_unescape_re = None
 
4022
 
 
4023
 
 
4024
def _unescape_xml(data):
 
4025
    """Unescape predefined XML entities in a string of data."""
 
4026
    global _unescape_re
 
4027
    if _unescape_re is None:
 
4028
        _unescape_re = re.compile('\&([^;]*);')
 
4029
    return _unescape_re.sub(_unescaper, data)
 
4030
 
 
4031
 
 
4032
class _VersionedFileChecker(object):
 
4033
 
 
4034
    def __init__(self, repository, text_key_references=None, ancestors=None):
 
4035
        self.repository = repository
 
4036
        self.text_index = self.repository._generate_text_key_index(
 
4037
            text_key_references=text_key_references, ancestors=ancestors)
 
4038
 
 
4039
    def calculate_file_version_parents(self, text_key):
 
4040
        """Calculate the correct parents for a file version according to
 
4041
        the inventories.
 
4042
        """
 
4043
        parent_keys = self.text_index[text_key]
 
4044
        if parent_keys == [_mod_revision.NULL_REVISION]:
 
4045
            return ()
 
4046
        return tuple(parent_keys)
 
4047
 
 
4048
    def check_file_version_parents(self, texts, progress_bar=None):
 
4049
        """Check the parents stored in a versioned file are correct.
 
4050
 
 
4051
        It also detects file versions that are not referenced by their
 
4052
        corresponding revision's inventory.
 
4053
 
 
4054
        :returns: A tuple of (wrong_parents, dangling_file_versions).
 
4055
            wrong_parents is a dict mapping {revision_id: (stored_parents,
 
4056
            correct_parents)} for each revision_id where the stored parents
 
4057
            are not correct.  dangling_file_versions is a set of (file_id,
 
4058
            revision_id) tuples for versions that are present in this versioned
 
4059
            file, but not used by the corresponding inventory.
 
4060
        """
 
4061
        local_progress = None
 
4062
        if progress_bar is None:
 
4063
            local_progress = ui.ui_factory.nested_progress_bar()
 
4064
            progress_bar = local_progress
 
4065
        try:
 
4066
            return self._check_file_version_parents(texts, progress_bar)
 
4067
        finally:
 
4068
            if local_progress:
 
4069
                local_progress.finished()
 
4070
 
 
4071
    def _check_file_version_parents(self, texts, progress_bar):
 
4072
        """See check_file_version_parents."""
 
4073
        wrong_parents = {}
 
4074
        self.file_ids = set([file_id for file_id, _ in
 
4075
            self.text_index.iterkeys()])
 
4076
        # text keys is now grouped by file_id
 
4077
        n_versions = len(self.text_index)
 
4078
        progress_bar.update('loading text store', 0, n_versions)
 
4079
        parent_map = self.repository.texts.get_parent_map(self.text_index)
 
4080
        # On unlistable transports this could well be empty/error...
 
4081
        text_keys = self.repository.texts.keys()
 
4082
        unused_keys = frozenset(text_keys) - set(self.text_index)
 
4083
        for num, key in enumerate(self.text_index.iterkeys()):
 
4084
            progress_bar.update('checking text graph', num, n_versions)
 
4085
            correct_parents = self.calculate_file_version_parents(key)
 
4086
            try:
 
4087
                knit_parents = parent_map[key]
 
4088
            except errors.RevisionNotPresent:
 
4089
                # Missing text!
 
4090
                knit_parents = None
 
4091
            if correct_parents != knit_parents:
 
4092
                wrong_parents[key] = (knit_parents, correct_parents)
 
4093
        return wrong_parents, unused_keys
 
4094
 
 
4095
 
 
4096
def _old_get_graph(repository, revision_id):
 
4097
    """DO NOT USE. That is all. I'm serious."""
 
4098
    graph = repository.get_graph()
 
4099
    revision_graph = dict(((key, value) for key, value in
 
4100
        graph.iter_ancestry([revision_id]) if value is not None))
 
4101
    return _strip_NULL_ghosts(revision_graph)
 
4102
 
 
4103
 
 
4104
def _strip_NULL_ghosts(revision_graph):
 
4105
    """Also don't use this. more compatibility code for unmigrated clients."""
 
4106
    # Filter ghosts, and null:
 
4107
    if _mod_revision.NULL_REVISION in revision_graph:
 
4108
        del revision_graph[_mod_revision.NULL_REVISION]
 
4109
    for key, parents in revision_graph.items():
 
4110
        revision_graph[key] = tuple(parent for parent in parents if parent
 
4111
            in revision_graph)
 
4112
    return revision_graph
 
4113
 
 
4114
 
 
4115
class StreamSink(object):
 
4116
    """An object that can insert a stream into a repository.
 
4117
 
 
4118
    This interface handles the complexity of reserialising inventories and
 
4119
    revisions from different formats, and allows unidirectional insertion into
 
4120
    stacked repositories without looking for the missing basis parents
 
4121
    beforehand.
 
4122
    """
 
4123
 
 
4124
    def __init__(self, target_repo):
 
4125
        self.target_repo = target_repo
 
4126
 
 
4127
    def insert_stream(self, stream, src_format, resume_tokens):
 
4128
        """Insert a stream's content into the target repository.
 
4129
 
 
4130
        :param src_format: a bzr repository format.
 
4131
 
 
4132
        :return: a list of resume tokens and an  iterable of keys additional
 
4133
            items required before the insertion can be completed.
 
4134
        """
 
4135
        self.target_repo.lock_write()
 
4136
        try:
 
4137
            if resume_tokens:
 
4138
                self.target_repo.resume_write_group(resume_tokens)
 
4139
                is_resume = True
 
4140
            else:
 
4141
                self.target_repo.start_write_group()
 
4142
                is_resume = False
 
4143
            try:
 
4144
                # locked_insert_stream performs a commit|suspend.
 
4145
                return self._locked_insert_stream(stream, src_format, is_resume)
 
4146
            except:
 
4147
                self.target_repo.abort_write_group(suppress_errors=True)
 
4148
                raise
 
4149
        finally:
 
4150
            self.target_repo.unlock()
 
4151
 
 
4152
    def _locked_insert_stream(self, stream, src_format, is_resume):
 
4153
        to_serializer = self.target_repo._format._serializer
 
4154
        src_serializer = src_format._serializer
 
4155
        new_pack = None
 
4156
        if to_serializer == src_serializer:
 
4157
            # If serializers match and the target is a pack repository, set the
 
4158
            # write cache size on the new pack.  This avoids poor performance
 
4159
            # on transports where append is unbuffered (such as
 
4160
            # RemoteTransport).  This is safe to do because nothing should read
 
4161
            # back from the target repository while a stream with matching
 
4162
            # serialization is being inserted.
 
4163
            # The exception is that a delta record from the source that should
 
4164
            # be a fulltext may need to be expanded by the target (see
 
4165
            # test_fetch_revisions_with_deltas_into_pack); but we take care to
 
4166
            # explicitly flush any buffered writes first in that rare case.
 
4167
            try:
 
4168
                new_pack = self.target_repo._pack_collection._new_pack
 
4169
            except AttributeError:
 
4170
                # Not a pack repository
 
4171
                pass
 
4172
            else:
 
4173
                new_pack.set_write_cache_size(1024*1024)
 
4174
        for substream_type, substream in stream:
 
4175
            if 'stream' in debug.debug_flags:
 
4176
                mutter('inserting substream: %s', substream_type)
 
4177
            if substream_type == 'texts':
 
4178
                self.target_repo.texts.insert_record_stream(substream)
 
4179
            elif substream_type == 'inventories':
 
4180
                if src_serializer == to_serializer:
 
4181
                    self.target_repo.inventories.insert_record_stream(
 
4182
                        substream)
 
4183
                else:
 
4184
                    self._extract_and_insert_inventories(
 
4185
                        substream, src_serializer)
 
4186
            elif substream_type == 'inventory-deltas':
 
4187
                self._extract_and_insert_inventory_deltas(
 
4188
                    substream, src_serializer)
 
4189
            elif substream_type == 'chk_bytes':
 
4190
                # XXX: This doesn't support conversions, as it assumes the
 
4191
                #      conversion was done in the fetch code.
 
4192
                self.target_repo.chk_bytes.insert_record_stream(substream)
 
4193
            elif substream_type == 'revisions':
 
4194
                # This may fallback to extract-and-insert more often than
 
4195
                # required if the serializers are different only in terms of
 
4196
                # the inventory.
 
4197
                if src_serializer == to_serializer:
 
4198
                    self.target_repo.revisions.insert_record_stream(
 
4199
                        substream)
 
4200
                else:
 
4201
                    self._extract_and_insert_revisions(substream,
 
4202
                        src_serializer)
 
4203
            elif substream_type == 'signatures':
 
4204
                self.target_repo.signatures.insert_record_stream(substream)
 
4205
            else:
 
4206
                raise AssertionError('kaboom! %s' % (substream_type,))
 
4207
        # Done inserting data, and the missing_keys calculations will try to
 
4208
        # read back from the inserted data, so flush the writes to the new pack
 
4209
        # (if this is pack format).
 
4210
        if new_pack is not None:
 
4211
            new_pack._write_data('', flush=True)
 
4212
        # Find all the new revisions (including ones from resume_tokens)
 
4213
        missing_keys = self.target_repo.get_missing_parent_inventories(
 
4214
            check_for_missing_texts=is_resume)
 
4215
        try:
 
4216
            for prefix, versioned_file in (
 
4217
                ('texts', self.target_repo.texts),
 
4218
                ('inventories', self.target_repo.inventories),
 
4219
                ('revisions', self.target_repo.revisions),
 
4220
                ('signatures', self.target_repo.signatures),
 
4221
                ('chk_bytes', self.target_repo.chk_bytes),
 
4222
                ):
 
4223
                if versioned_file is None:
 
4224
                    continue
 
4225
                missing_keys.update((prefix,) + key for key in
 
4226
                    versioned_file.get_missing_compression_parent_keys())
 
4227
        except NotImplementedError:
 
4228
            # cannot even attempt suspending, and missing would have failed
 
4229
            # during stream insertion.
 
4230
            missing_keys = set()
 
4231
        else:
 
4232
            if missing_keys:
 
4233
                # suspend the write group and tell the caller what we is
 
4234
                # missing. We know we can suspend or else we would not have
 
4235
                # entered this code path. (All repositories that can handle
 
4236
                # missing keys can handle suspending a write group).
 
4237
                write_group_tokens = self.target_repo.suspend_write_group()
 
4238
                return write_group_tokens, missing_keys
 
4239
        hint = self.target_repo.commit_write_group()
 
4240
        if (to_serializer != src_serializer and
 
4241
            self.target_repo._format.pack_compresses):
 
4242
            self.target_repo.pack(hint=hint)
 
4243
        return [], set()
 
4244
 
 
4245
    def _extract_and_insert_inventory_deltas(self, substream, serializer):
 
4246
        target_rich_root = self.target_repo._format.rich_root_data
 
4247
        target_tree_refs = self.target_repo._format.supports_tree_reference
 
4248
        for record in substream:
 
4249
            # Insert the delta directly
 
4250
            inventory_delta_bytes = record.get_bytes_as('fulltext')
 
4251
            deserialiser = inventory_delta.InventoryDeltaDeserializer()
 
4252
            try:
 
4253
                parse_result = deserialiser.parse_text_bytes(
 
4254
                    inventory_delta_bytes)
 
4255
            except inventory_delta.IncompatibleInventoryDelta, err:
 
4256
                trace.mutter("Incompatible delta: %s", err.msg)
 
4257
                raise errors.IncompatibleRevision(self.target_repo._format)
 
4258
            basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
 
4259
            revision_id = new_id
 
4260
            parents = [key[0] for key in record.parents]
 
4261
            self.target_repo.add_inventory_by_delta(
 
4262
                basis_id, inv_delta, revision_id, parents)
 
4263
 
 
4264
    def _extract_and_insert_inventories(self, substream, serializer,
 
4265
            parse_delta=None):
 
4266
        """Generate a new inventory versionedfile in target, converting data.
 
4267
 
 
4268
        The inventory is retrieved from the source, (deserializing it), and
 
4269
        stored in the target (reserializing it in a different format).
 
4270
        """
 
4271
        target_rich_root = self.target_repo._format.rich_root_data
 
4272
        target_tree_refs = self.target_repo._format.supports_tree_reference
 
4273
        for record in substream:
 
4274
            # It's not a delta, so it must be a fulltext in the source
 
4275
            # serializer's format.
 
4276
            bytes = record.get_bytes_as('fulltext')
 
4277
            revision_id = record.key[0]
 
4278
            inv = serializer.read_inventory_from_string(bytes, revision_id)
 
4279
            parents = [key[0] for key in record.parents]
 
4280
            self.target_repo.add_inventory(revision_id, inv, parents)
 
4281
            # No need to keep holding this full inv in memory when the rest of
 
4282
            # the substream is likely to be all deltas.
 
4283
            del inv
 
4284
 
 
4285
    def _extract_and_insert_revisions(self, substream, serializer):
 
4286
        for record in substream:
 
4287
            bytes = record.get_bytes_as('fulltext')
 
4288
            revision_id = record.key[0]
 
4289
            rev = serializer.read_revision_from_string(bytes)
 
4290
            if rev.revision_id != revision_id:
 
4291
                raise AssertionError('wtf: %s != %s' % (rev, revision_id))
 
4292
            self.target_repo.add_revision(revision_id, rev)
 
4293
 
 
4294
    def finished(self):
 
4295
        if self.target_repo._format._fetch_reconcile:
 
4296
            self.target_repo.reconcile()
 
4297
 
 
4298
 
 
4299
class StreamSource(object):
 
4300
    """A source of a stream for fetching between repositories."""
 
4301
 
 
4302
    def __init__(self, from_repository, to_format):
 
4303
        """Create a StreamSource streaming from from_repository."""
 
4304
        self.from_repository = from_repository
 
4305
        self.to_format = to_format
 
4306
 
 
4307
    def delta_on_metadata(self):
 
4308
        """Return True if delta's are permitted on metadata streams.
 
4309
 
 
4310
        That is on revisions and signatures.
 
4311
        """
 
4312
        src_serializer = self.from_repository._format._serializer
 
4313
        target_serializer = self.to_format._serializer
 
4314
        return (self.to_format._fetch_uses_deltas and
 
4315
            src_serializer == target_serializer)
 
4316
 
 
4317
    def _fetch_revision_texts(self, revs):
 
4318
        # fetch signatures first and then the revision texts
 
4319
        # may need to be a InterRevisionStore call here.
 
4320
        from_sf = self.from_repository.signatures
 
4321
        # A missing signature is just skipped.
 
4322
        keys = [(rev_id,) for rev_id in revs]
 
4323
        signatures = versionedfile.filter_absent(from_sf.get_record_stream(
 
4324
            keys,
 
4325
            self.to_format._fetch_order,
 
4326
            not self.to_format._fetch_uses_deltas))
 
4327
        # If a revision has a delta, this is actually expanded inside the
 
4328
        # insert_record_stream code now, which is an alternate fix for
 
4329
        # bug #261339
 
4330
        from_rf = self.from_repository.revisions
 
4331
        revisions = from_rf.get_record_stream(
 
4332
            keys,
 
4333
            self.to_format._fetch_order,
 
4334
            not self.delta_on_metadata())
 
4335
        return [('signatures', signatures), ('revisions', revisions)]
 
4336
 
 
4337
    def _generate_root_texts(self, revs):
 
4338
        """This will be called by get_stream between fetching weave texts and
 
4339
        fetching the inventory weave.
 
4340
        """
 
4341
        if self._rich_root_upgrade():
 
4342
            import bzrlib.fetch
 
4343
            return bzrlib.fetch.Inter1and2Helper(
 
4344
                self.from_repository).generate_root_texts(revs)
 
4345
        else:
 
4346
            return []
 
4347
 
 
4348
    def get_stream(self, search):
 
4349
        phase = 'file'
 
4350
        revs = search.get_keys()
 
4351
        graph = self.from_repository.get_graph()
 
4352
        revs = tsort.topo_sort(graph.get_parent_map(revs))
 
4353
        data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
 
4354
        text_keys = []
 
4355
        for knit_kind, file_id, revisions in data_to_fetch:
 
4356
            if knit_kind != phase:
 
4357
                phase = knit_kind
 
4358
                # Make a new progress bar for this phase
 
4359
            if knit_kind == "file":
 
4360
                # Accumulate file texts
 
4361
                text_keys.extend([(file_id, revision) for revision in
 
4362
                    revisions])
 
4363
            elif knit_kind == "inventory":
 
4364
                # Now copy the file texts.
 
4365
                from_texts = self.from_repository.texts
 
4366
                yield ('texts', from_texts.get_record_stream(
 
4367
                    text_keys, self.to_format._fetch_order,
 
4368
                    not self.to_format._fetch_uses_deltas))
 
4369
                # Cause an error if a text occurs after we have done the
 
4370
                # copy.
 
4371
                text_keys = None
 
4372
                # Before we process the inventory we generate the root
 
4373
                # texts (if necessary) so that the inventories references
 
4374
                # will be valid.
 
4375
                for _ in self._generate_root_texts(revs):
 
4376
                    yield _
 
4377
                # we fetch only the referenced inventories because we do not
 
4378
                # know for unselected inventories whether all their required
 
4379
                # texts are present in the other repository - it could be
 
4380
                # corrupt.
 
4381
                for info in self._get_inventory_stream(revs):
 
4382
                    yield info
 
4383
            elif knit_kind == "signatures":
 
4384
                # Nothing to do here; this will be taken care of when
 
4385
                # _fetch_revision_texts happens.
 
4386
                pass
 
4387
            elif knit_kind == "revisions":
 
4388
                for record in self._fetch_revision_texts(revs):
 
4389
                    yield record
 
4390
            else:
 
4391
                raise AssertionError("Unknown knit kind %r" % knit_kind)
 
4392
 
 
4393
    def get_stream_for_missing_keys(self, missing_keys):
 
4394
        # missing keys can only occur when we are byte copying and not
 
4395
        # translating (because translation means we don't send
 
4396
        # unreconstructable deltas ever).
 
4397
        keys = {}
 
4398
        keys['texts'] = set()
 
4399
        keys['revisions'] = set()
 
4400
        keys['inventories'] = set()
 
4401
        keys['chk_bytes'] = set()
 
4402
        keys['signatures'] = set()
 
4403
        for key in missing_keys:
 
4404
            keys[key[0]].add(key[1:])
 
4405
        if len(keys['revisions']):
 
4406
            # If we allowed copying revisions at this point, we could end up
 
4407
            # copying a revision without copying its required texts: a
 
4408
            # violation of the requirements for repository integrity.
 
4409
            raise AssertionError(
 
4410
                'cannot copy revisions to fill in missing deltas %s' % (
 
4411
                    keys['revisions'],))
 
4412
        for substream_kind, keys in keys.iteritems():
 
4413
            vf = getattr(self.from_repository, substream_kind)
 
4414
            if vf is None and keys:
 
4415
                    raise AssertionError(
 
4416
                        "cannot fill in keys for a versioned file we don't"
 
4417
                        " have: %s needs %s" % (substream_kind, keys))
 
4418
            if not keys:
 
4419
                # No need to stream something we don't have
 
4420
                continue
 
4421
            if substream_kind == 'inventories':
 
4422
                # Some missing keys are genuinely ghosts, filter those out.
 
4423
                present = self.from_repository.inventories.get_parent_map(keys)
 
4424
                revs = [key[0] for key in present]
 
4425
                # Get the inventory stream more-or-less as we do for the
 
4426
                # original stream; there's no reason to assume that records
 
4427
                # direct from the source will be suitable for the sink.  (Think
 
4428
                # e.g. 2a -> 1.9-rich-root).
 
4429
                for info in self._get_inventory_stream(revs, missing=True):
 
4430
                    yield info
 
4431
                continue
 
4432
 
 
4433
            # Ask for full texts always so that we don't need more round trips
 
4434
            # after this stream.
 
4435
            # Some of the missing keys are genuinely ghosts, so filter absent
 
4436
            # records. The Sink is responsible for doing another check to
 
4437
            # ensure that ghosts don't introduce missing data for future
 
4438
            # fetches.
 
4439
            stream = versionedfile.filter_absent(vf.get_record_stream(keys,
 
4440
                self.to_format._fetch_order, True))
 
4441
            yield substream_kind, stream
 
4442
 
 
4443
    def inventory_fetch_order(self):
 
4444
        if self._rich_root_upgrade():
 
4445
            return 'topological'
 
4446
        else:
 
4447
            return self.to_format._fetch_order
 
4448
 
 
4449
    def _rich_root_upgrade(self):
 
4450
        return (not self.from_repository._format.rich_root_data and
 
4451
            self.to_format.rich_root_data)
 
4452
 
 
4453
    def _get_inventory_stream(self, revision_ids, missing=False):
 
4454
        from_format = self.from_repository._format
 
4455
        if (from_format.supports_chks and self.to_format.supports_chks and
 
4456
            from_format.network_name() == self.to_format.network_name()):
 
4457
            raise AssertionError(
 
4458
                "this case should be handled by GroupCHKStreamSource")
 
4459
        elif 'forceinvdeltas' in debug.debug_flags:
 
4460
            return self._get_convertable_inventory_stream(revision_ids,
 
4461
                    delta_versus_null=missing)
 
4462
        elif from_format.network_name() == self.to_format.network_name():
 
4463
            # Same format.
 
4464
            return self._get_simple_inventory_stream(revision_ids,
 
4465
                    missing=missing)
 
4466
        elif (not from_format.supports_chks and not self.to_format.supports_chks
 
4467
                and from_format._serializer == self.to_format._serializer):
 
4468
            # Essentially the same format.
 
4469
            return self._get_simple_inventory_stream(revision_ids,
 
4470
                    missing=missing)
 
4471
        else:
 
4472
            # Any time we switch serializations, we want to use an
 
4473
            # inventory-delta based approach.
 
4474
            return self._get_convertable_inventory_stream(revision_ids,
 
4475
                    delta_versus_null=missing)
 
4476
 
 
4477
    def _get_simple_inventory_stream(self, revision_ids, missing=False):
 
4478
        # NB: This currently reopens the inventory weave in source;
 
4479
        # using a single stream interface instead would avoid this.
 
4480
        from_weave = self.from_repository.inventories
 
4481
        if missing:
 
4482
            delta_closure = True
 
4483
        else:
 
4484
            delta_closure = not self.delta_on_metadata()
 
4485
        yield ('inventories', from_weave.get_record_stream(
 
4486
            [(rev_id,) for rev_id in revision_ids],
 
4487
            self.inventory_fetch_order(), delta_closure))
 
4488
 
 
4489
    def _get_convertable_inventory_stream(self, revision_ids,
 
4490
                                          delta_versus_null=False):
 
4491
        # The source is using CHKs, but the target either doesn't or it has a
 
4492
        # different serializer.  The StreamSink code expects to be able to
 
4493
        # convert on the target, so we need to put bytes-on-the-wire that can
 
4494
        # be converted.  That means inventory deltas (if the remote is <1.19,
 
4495
        # RemoteStreamSink will fallback to VFS to insert the deltas).
 
4496
        yield ('inventory-deltas',
 
4497
           self._stream_invs_as_deltas(revision_ids,
 
4498
                                       delta_versus_null=delta_versus_null))
 
4499
 
 
4500
    def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
 
4501
        """Return a stream of inventory-deltas for the given rev ids.
 
4502
 
 
4503
        :param revision_ids: The list of inventories to transmit
 
4504
        :param delta_versus_null: Don't try to find a minimal delta for this
 
4505
            entry, instead compute the delta versus the NULL_REVISION. This
 
4506
            effectively streams a complete inventory. Used for stuff like
 
4507
            filling in missing parents, etc.
 
4508
        """
 
4509
        from_repo = self.from_repository
 
4510
        revision_keys = [(rev_id,) for rev_id in revision_ids]
 
4511
        parent_map = from_repo.inventories.get_parent_map(revision_keys)
 
4512
        # XXX: possibly repos could implement a more efficient iter_inv_deltas
 
4513
        # method...
 
4514
        inventories = self.from_repository.iter_inventories(
 
4515
            revision_ids, 'topological')
 
4516
        format = from_repo._format
 
4517
        invs_sent_so_far = set([_mod_revision.NULL_REVISION])
 
4518
        inventory_cache = lru_cache.LRUCache(50)
 
4519
        null_inventory = from_repo.revision_tree(
 
4520
            _mod_revision.NULL_REVISION).inventory
 
4521
        # XXX: ideally the rich-root/tree-refs flags would be per-revision, not
 
4522
        # per-repo (e.g.  streaming a non-rich-root revision out of a rich-root
 
4523
        # repo back into a non-rich-root repo ought to be allowed)
 
4524
        serializer = inventory_delta.InventoryDeltaSerializer(
 
4525
            versioned_root=format.rich_root_data,
 
4526
            tree_references=format.supports_tree_reference)
 
4527
        for inv in inventories:
 
4528
            key = (inv.revision_id,)
 
4529
            parent_keys = parent_map.get(key, ())
 
4530
            delta = None
 
4531
            if not delta_versus_null and parent_keys:
 
4532
                # The caller did not ask for complete inventories and we have
 
4533
                # some parents that we can delta against.  Make a delta against
 
4534
                # each parent so that we can find the smallest.
 
4535
                parent_ids = [parent_key[0] for parent_key in parent_keys]
 
4536
                for parent_id in parent_ids:
 
4537
                    if parent_id not in invs_sent_so_far:
 
4538
                        # We don't know that the remote side has this basis, so
 
4539
                        # we can't use it.
 
4540
                        continue
 
4541
                    if parent_id == _mod_revision.NULL_REVISION:
 
4542
                        parent_inv = null_inventory
 
4543
                    else:
 
4544
                        parent_inv = inventory_cache.get(parent_id, None)
 
4545
                        if parent_inv is None:
 
4546
                            parent_inv = from_repo.get_inventory(parent_id)
 
4547
                    candidate_delta = inv._make_delta(parent_inv)
 
4548
                    if (delta is None or
 
4549
                        len(delta) > len(candidate_delta)):
 
4550
                        delta = candidate_delta
 
4551
                        basis_id = parent_id
 
4552
            if delta is None:
 
4553
                # Either none of the parents ended up being suitable, or we
 
4554
                # were asked to delta against NULL
 
4555
                basis_id = _mod_revision.NULL_REVISION
 
4556
                delta = inv._make_delta(null_inventory)
 
4557
            invs_sent_so_far.add(inv.revision_id)
 
4558
            inventory_cache[inv.revision_id] = inv
 
4559
            delta_serialized = ''.join(
 
4560
                serializer.delta_to_lines(basis_id, key[-1], delta))
 
4561
            yield versionedfile.FulltextContentFactory(
 
4562
                key, parent_keys, None, delta_serialized)
 
4563
 
 
4564
 
 
4565
def _iter_for_revno(repo, partial_history_cache, stop_index=None,
 
4566
                    stop_revision=None):
 
4567
    """Extend the partial history to include a given index
 
4568
 
 
4569
    If a stop_index is supplied, stop when that index has been reached.
 
4570
    If a stop_revision is supplied, stop when that revision is
 
4571
    encountered.  Otherwise, stop when the beginning of history is
 
4572
    reached.
 
4573
 
 
4574
    :param stop_index: The index which should be present.  When it is
 
4575
        present, history extension will stop.
 
4576
    :param stop_revision: The revision id which should be present.  When
 
4577
        it is encountered, history extension will stop.
 
4578
    """
 
4579
    start_revision = partial_history_cache[-1]
 
4580
    iterator = repo.iter_reverse_revision_history(start_revision)
 
4581
    try:
 
4582
        #skip the last revision in the list
 
4583
        iterator.next()
 
4584
        while True:
 
4585
            if (stop_index is not None and
 
4586
                len(partial_history_cache) > stop_index):
 
4587
                break
 
4588
            if partial_history_cache[-1] == stop_revision:
 
4589
                break
 
4590
            revision_id = iterator.next()
 
4591
            partial_history_cache.append(revision_id)
 
4592
    except StopIteration:
 
4593
        # No more history
 
4594
        return
 
4595