~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-08-06 08:55:54 UTC
  • mfrom: (3607.1.1 integration)
  • Revision ID: pqm@pqm.ubuntu.com-20080806085554-9e0l5crd6yv0kxy8
(mbp) start 1.7

Show diffs side-by-side

added added

removed removed

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