~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Tarmac
  • Author(s): Vincent Ladeuil
  • Date: 2017-01-30 14:42:05 UTC
  • mfrom: (6620.1.1 trunk)
  • Revision ID: tarmac-20170130144205-r8fh2xpmiuxyozpv
Merge  2.7 into trunk including fix for bug #1657238 [r=vila]

Show diffs side-by-side

added added

removed removed

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