/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Martin Pool
  • Date: 2008-06-18 05:35:02 UTC
  • mto: This revision was merged to the branch mainline in revision 3510.
  • Revision ID: mbp@sourcefrog.net-20080618053502-9ogi5d5tx7w5ybf6
Change stray pdb calls to exceptions

Show diffs side-by-side

added added

removed removed

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