~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

Merged Martin

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 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 binascii import hexlify
18
 
from copy import deepcopy
19
 
from cStringIO import StringIO
20
 
import re
21
 
import time
22
 
from unittest import TestSuite
23
 
 
24
 
import bzrlib.bzrdir as bzrdir
25
 
from bzrlib.decorators import needs_read_lock, needs_write_lock
26
 
import bzrlib.errors as errors
27
 
from bzrlib.errors import InvalidRevisionId
28
 
import bzrlib.gpg as gpg
29
 
from bzrlib.graph import Graph
30
 
from bzrlib.inter import InterObject
31
 
from bzrlib.inventory import Inventory
32
 
from bzrlib.knit import KnitVersionedFile, KnitPlainFactory
33
 
from bzrlib.lockable_files import LockableFiles, TransportLock
34
 
from bzrlib.lockdir import LockDir
35
 
from bzrlib.osutils import (safe_unicode, rand_bytes, compact_date, 
36
 
                            local_time_offset)
37
 
from bzrlib.revision import NULL_REVISION, Revision
38
 
from bzrlib.store.versioned import VersionedFileStore, WeaveStore
39
 
from bzrlib.store.text import TextStore
40
 
from bzrlib.symbol_versioning import *
41
 
from bzrlib.trace import mutter, note
42
 
from bzrlib.tree import RevisionTree
43
 
from bzrlib.tsort import topo_sort
44
 
from bzrlib.testament import Testament
45
 
from bzrlib.tree import EmptyTree
46
 
import bzrlib.ui
47
 
from bzrlib.weave import WeaveFile
48
 
import bzrlib.xml5
49
 
 
50
 
 
51
 
class Repository(object):
52
 
    """Repository holding history for one or more branches.
53
 
 
54
 
    The repository holds and retrieves historical information including
55
 
    revisions and file history.  It's normally accessed only by the Branch,
56
 
    which views a particular line of development through that history.
57
 
 
58
 
    The Repository builds on top of Stores and a Transport, which respectively 
59
 
    describe the disk data format and the way of accessing the (possibly 
60
 
    remote) disk.
61
 
    """
62
 
 
63
 
    @needs_write_lock
64
 
    def add_inventory(self, revid, inv, parents):
65
 
        """Add the inventory inv to the repository as revid.
66
 
        
67
 
        :param parents: The revision ids of the parents that revid
68
 
                        is known to have and are in the repository already.
69
 
 
70
 
        returns the sha1 of the serialized inventory.
71
 
        """
72
 
        assert inv.revision_id is None or inv.revision_id == revid, \
73
 
            "Mismatch between inventory revision" \
74
 
            " id and insertion revid (%r, %r)" % (inv.revision_id, revid)
75
 
        inv_text = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
76
 
        inv_sha1 = bzrlib.osutils.sha_string(inv_text)
77
 
        inv_vf = self.control_weaves.get_weave('inventory',
78
 
                                               self.get_transaction())
79
 
        self._inventory_add_lines(inv_vf, revid, parents, bzrlib.osutils.split_lines(inv_text))
80
 
        return inv_sha1
81
 
 
82
 
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
83
 
        final_parents = []
84
 
        for parent in parents:
85
 
            if parent in inv_vf:
86
 
                final_parents.append(parent)
87
 
 
88
 
        inv_vf.add_lines(revid, final_parents, lines)
89
 
 
90
 
    @needs_write_lock
91
 
    def add_revision(self, rev_id, rev, inv=None, config=None):
92
 
        """Add rev to the revision store as rev_id.
93
 
 
94
 
        :param rev_id: the revision id to use.
95
 
        :param rev: The revision object.
96
 
        :param inv: The inventory for the revision. if None, it will be looked
97
 
                    up in the inventory storer
98
 
        :param config: If None no digital signature will be created.
99
 
                       If supplied its signature_needed method will be used
100
 
                       to determine if a signature should be made.
101
 
        """
102
 
        if config is not None and config.signature_needed():
103
 
            if inv is None:
104
 
                inv = self.get_inventory(rev_id)
105
 
            plaintext = Testament(rev, inv).as_short_text()
106
 
            self.store_revision_signature(
107
 
                gpg.GPGStrategy(config), plaintext, rev_id)
108
 
        if not rev_id in self.get_inventory_weave():
109
 
            if inv is None:
110
 
                raise errors.WeaveRevisionNotPresent(rev_id,
111
 
                                                     self.get_inventory_weave())
112
 
            else:
113
 
                # yes, this is not suitable for adding with ghosts.
114
 
                self.add_inventory(rev_id, inv, rev.parent_ids)
115
 
        self._revision_store.add_revision(rev, self.get_transaction())
116
 
 
117
 
    @needs_read_lock
118
 
    def _all_possible_ids(self):
119
 
        """Return all the possible revisions that we could find."""
120
 
        return self.get_inventory_weave().versions()
121
 
 
122
 
    @deprecated_method(zero_nine)
123
 
    def all_revision_ids(self):
124
 
        """Returns a list of all the revision ids in the repository. 
125
 
 
126
 
        This is deprecated because code should generally work on the graph
127
 
        reachable from a particular revision, and ignore any other revisions
128
 
        that might be present.  There is no direct replacement method.
129
 
        """
130
 
        return self._all_revision_ids()
131
 
 
132
 
    @needs_read_lock
133
 
    def _all_revision_ids(self):
134
 
        """Returns a list of all the revision ids in the repository. 
135
 
 
136
 
        These are in as much topological order as the underlying store can 
137
 
        present: for weaves ghosts may lead to a lack of correctness until
138
 
        the reweave updates the parents list.
139
 
        """
140
 
        if self._revision_store.text_store.listable():
141
 
            return self._revision_store.all_revision_ids(self.get_transaction())
142
 
        result = self._all_possible_ids()
143
 
        return self._eliminate_revisions_not_present(result)
144
 
 
145
 
    def break_lock(self):
146
 
        """Break a lock if one is present from another instance.
147
 
 
148
 
        Uses the ui factory to ask for confirmation if the lock may be from
149
 
        an active process.
150
 
        """
151
 
        self.control_files.break_lock()
152
 
 
153
 
    @needs_read_lock
154
 
    def _eliminate_revisions_not_present(self, revision_ids):
155
 
        """Check every revision id in revision_ids to see if we have it.
156
 
 
157
 
        Returns a set of the present revisions.
158
 
        """
159
 
        result = []
160
 
        for id in revision_ids:
161
 
            if self.has_revision(id):
162
 
               result.append(id)
163
 
        return result
164
 
 
165
 
    @staticmethod
166
 
    def create(a_bzrdir):
167
 
        """Construct the current default format repository in a_bzrdir."""
168
 
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
169
 
 
170
 
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
171
 
        """instantiate a Repository.
172
 
 
173
 
        :param _format: The format of the repository on disk.
174
 
        :param a_bzrdir: The BzrDir of the repository.
175
 
 
176
 
        In the future we will have a single api for all stores for
177
 
        getting file texts, inventories and revisions, then
178
 
        this construct will accept instances of those things.
179
 
        """
180
 
        super(Repository, self).__init__()
181
 
        self._format = _format
182
 
        # the following are part of the public API for Repository:
183
 
        self.bzrdir = a_bzrdir
184
 
        self.control_files = control_files
185
 
        self._revision_store = _revision_store
186
 
        self.text_store = text_store
187
 
        # backwards compatibility
188
 
        self.weave_store = text_store
189
 
        # not right yet - should be more semantically clear ? 
190
 
        # 
191
 
        self.control_store = control_store
192
 
        self.control_weaves = control_store
193
 
        # TODO: make sure to construct the right store classes, etc, depending
194
 
        # on whether escaping is required.
195
 
 
196
 
    def __repr__(self):
197
 
        return '%s(%r)' % (self.__class__.__name__, 
198
 
                           self.bzrdir.transport.base)
199
 
 
200
 
    def is_locked(self):
201
 
        return self.control_files.is_locked()
202
 
 
203
 
    def lock_write(self):
204
 
        self.control_files.lock_write()
205
 
 
206
 
    def lock_read(self):
207
 
        self.control_files.lock_read()
208
 
 
209
 
    def get_physical_lock_status(self):
210
 
        return self.control_files.get_physical_lock_status()
211
 
 
212
 
    @needs_read_lock
213
 
    def missing_revision_ids(self, other, revision_id=None):
214
 
        """Return the revision ids that other has that this does not.
215
 
        
216
 
        These are returned in topological order.
217
 
 
218
 
        revision_id: only return revision ids included by revision_id.
219
 
        """
220
 
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
221
 
 
222
 
    @staticmethod
223
 
    def open(base):
224
 
        """Open the repository rooted at base.
225
 
 
226
 
        For instance, if the repository is at URL/.bzr/repository,
227
 
        Repository.open(URL) -> a Repository instance.
228
 
        """
229
 
        control = bzrlib.bzrdir.BzrDir.open(base)
230
 
        return control.open_repository()
231
 
 
232
 
    def copy_content_into(self, destination, revision_id=None, basis=None):
233
 
        """Make a complete copy of the content in self into destination.
234
 
        
235
 
        This is a destructive operation! Do not use it on existing 
236
 
        repositories.
237
 
        """
238
 
        return InterRepository.get(self, destination).copy_content(revision_id, basis)
239
 
 
240
 
    def fetch(self, source, revision_id=None, pb=None):
241
 
        """Fetch the content required to construct revision_id from source.
242
 
 
243
 
        If revision_id is None all content is copied.
244
 
        """
245
 
        return InterRepository.get(source, self).fetch(revision_id=revision_id,
246
 
                                                       pb=pb)
247
 
 
248
 
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
249
 
                           timezone=None, committer=None, revprops=None, 
250
 
                           revision_id=None):
251
 
        """Obtain a CommitBuilder for this repository.
252
 
        
253
 
        :param branch: Branch to commit to.
254
 
        :param parents: Revision ids of the parents of the new revision.
255
 
        :param config: Configuration to use.
256
 
        :param timestamp: Optional timestamp recorded for commit.
257
 
        :param timezone: Optional timezone for timestamp.
258
 
        :param committer: Optional committer to set for commit.
259
 
        :param revprops: Optional dictionary of revision properties.
260
 
        :param revision_id: Optional revision id.
261
 
        """
262
 
        return CommitBuilder(self, parents, config, timestamp, timezone,
263
 
                             committer, revprops, revision_id)
264
 
 
265
 
    def unlock(self):
266
 
        self.control_files.unlock()
267
 
 
268
 
    @needs_read_lock
269
 
    def clone(self, a_bzrdir, revision_id=None, basis=None):
270
 
        """Clone this repository into a_bzrdir using the current format.
271
 
 
272
 
        Currently no check is made that the format of this repository and
273
 
        the bzrdir format are compatible. FIXME RBC 20060201.
274
 
        """
275
 
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
276
 
            # use target default format.
277
 
            result = a_bzrdir.create_repository()
278
 
        # FIXME RBC 20060209 split out the repository type to avoid this check ?
279
 
        elif isinstance(a_bzrdir._format,
280
 
                      (bzrlib.bzrdir.BzrDirFormat4,
281
 
                       bzrlib.bzrdir.BzrDirFormat5,
282
 
                       bzrlib.bzrdir.BzrDirFormat6)):
283
 
            result = a_bzrdir.open_repository()
284
 
        else:
285
 
            result = self._format.initialize(a_bzrdir, shared=self.is_shared())
286
 
        self.copy_content_into(result, revision_id, basis)
287
 
        return result
288
 
 
289
 
    @needs_read_lock
290
 
    def has_revision(self, revision_id):
291
 
        """True if this repository has a copy of the revision."""
292
 
        return self._revision_store.has_revision_id(revision_id,
293
 
                                                    self.get_transaction())
294
 
 
295
 
    @needs_read_lock
296
 
    def get_revision_reconcile(self, revision_id):
297
 
        """'reconcile' helper routine that allows access to a revision always.
298
 
        
299
 
        This variant of get_revision does not cross check the weave graph
300
 
        against the revision one as get_revision does: but it should only
301
 
        be used by reconcile, or reconcile-alike commands that are correcting
302
 
        or testing the revision graph.
303
 
        """
304
 
        if not revision_id or not isinstance(revision_id, basestring):
305
 
            raise InvalidRevisionId(revision_id=revision_id, branch=self)
306
 
        return self._revision_store.get_revision(revision_id,
307
 
                                                 self.get_transaction())
308
 
 
309
 
    @needs_read_lock
310
 
    def get_revision_xml(self, revision_id):
311
 
        rev = self.get_revision(revision_id) 
312
 
        rev_tmp = StringIO()
313
 
        # the current serializer..
314
 
        self._revision_store._serializer.write_revision(rev, rev_tmp)
315
 
        rev_tmp.seek(0)
316
 
        return rev_tmp.getvalue()
317
 
 
318
 
    @needs_read_lock
319
 
    def get_revision(self, revision_id):
320
 
        """Return the Revision object for a named revision"""
321
 
        r = self.get_revision_reconcile(revision_id)
322
 
        # weave corruption can lead to absent revision markers that should be
323
 
        # present.
324
 
        # the following test is reasonably cheap (it needs a single weave read)
325
 
        # and the weave is cached in read transactions. In write transactions
326
 
        # it is not cached but typically we only read a small number of
327
 
        # revisions. For knits when they are introduced we will probably want
328
 
        # to ensure that caching write transactions are in use.
329
 
        inv = self.get_inventory_weave()
330
 
        self._check_revision_parents(r, inv)
331
 
        return r
332
 
 
333
 
    def _check_revision_parents(self, revision, inventory):
334
 
        """Private to Repository and Fetch.
335
 
        
336
 
        This checks the parentage of revision in an inventory weave for 
337
 
        consistency and is only applicable to inventory-weave-for-ancestry
338
 
        using repository formats & fetchers.
339
 
        """
340
 
        weave_parents = inventory.get_parents(revision.revision_id)
341
 
        weave_names = inventory.versions()
342
 
        for parent_id in revision.parent_ids:
343
 
            if parent_id in weave_names:
344
 
                # this parent must not be a ghost.
345
 
                if not parent_id in weave_parents:
346
 
                    # but it is a ghost
347
 
                    raise errors.CorruptRepository(self)
348
 
 
349
 
    @needs_write_lock
350
 
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
351
 
        signature = gpg_strategy.sign(plaintext)
352
 
        self._revision_store.add_revision_signature_text(revision_id,
353
 
                                                         signature,
354
 
                                                         self.get_transaction())
355
 
 
356
 
    def fileids_altered_by_revision_ids(self, revision_ids):
357
 
        """Find the file ids and versions affected by revisions.
358
 
 
359
 
        :param revisions: an iterable containing revision ids.
360
 
        :return: a dictionary mapping altered file-ids to an iterable of
361
 
        revision_ids. Each altered file-ids has the exact revision_ids that
362
 
        altered it listed explicitly.
363
 
        """
364
 
        assert isinstance(self._format, (RepositoryFormat5,
365
 
                                         RepositoryFormat6,
366
 
                                         RepositoryFormat7,
367
 
                                         RepositoryFormatKnit1)), \
368
 
            ("fileids_altered_by_revision_ids only supported for branches " 
369
 
             "which store inventory as unnested xml, not on %r" % self)
370
 
        selected_revision_ids = set(revision_ids)
371
 
        w = self.get_inventory_weave()
372
 
        result = {}
373
 
 
374
 
        # this code needs to read every new line in every inventory for the
375
 
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
376
 
        # not present in one of those inventories is unnecessary but not 
377
 
        # harmful because we are filtering by the revision id marker in the
378
 
        # inventory lines : we only select file ids altered in one of those  
379
 
        # revisions. We don't need to see all lines in the inventory because
380
 
        # only those added in an inventory in rev X can contain a revision=X
381
 
        # line.
382
 
        for line in w.iter_lines_added_or_present_in_versions(selected_revision_ids):
383
 
            start = line.find('file_id="')+9
384
 
            if start < 9: continue
385
 
            end = line.find('"', start)
386
 
            assert end>= 0
387
 
            file_id = _unescape_xml(line[start:end])
388
 
 
389
 
            start = line.find('revision="')+10
390
 
            if start < 10: continue
391
 
            end = line.find('"', start)
392
 
            assert end>= 0
393
 
            revision_id = _unescape_xml(line[start:end])
394
 
            if revision_id in selected_revision_ids:
395
 
                result.setdefault(file_id, set()).add(revision_id)
396
 
        return result
397
 
 
398
 
    @needs_read_lock
399
 
    def get_inventory_weave(self):
400
 
        return self.control_weaves.get_weave('inventory',
401
 
            self.get_transaction())
402
 
 
403
 
    @needs_read_lock
404
 
    def get_inventory(self, revision_id):
405
 
        """Get Inventory object by hash."""
406
 
        return self.deserialise_inventory(
407
 
            revision_id, self.get_inventory_xml(revision_id))
408
 
 
409
 
    def deserialise_inventory(self, revision_id, xml):
410
 
        """Transform the xml into an inventory object. 
411
 
 
412
 
        :param revision_id: The expected revision id of the inventory.
413
 
        :param xml: A serialised inventory.
414
 
        """
415
 
        return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
416
 
 
417
 
    @needs_read_lock
418
 
    def get_inventory_xml(self, revision_id):
419
 
        """Get inventory XML as a file object."""
420
 
        try:
421
 
            assert isinstance(revision_id, basestring), type(revision_id)
422
 
            iw = self.get_inventory_weave()
423
 
            return iw.get_text(revision_id)
424
 
        except IndexError:
425
 
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
426
 
 
427
 
    @needs_read_lock
428
 
    def get_inventory_sha1(self, revision_id):
429
 
        """Return the sha1 hash of the inventory entry
430
 
        """
431
 
        return self.get_revision(revision_id).inventory_sha1
432
 
 
433
 
    @needs_read_lock
434
 
    def get_revision_graph(self, revision_id=None):
435
 
        """Return a dictionary containing the revision graph.
436
 
        
437
 
        :return: a dictionary of revision_id->revision_parents_list.
438
 
        """
439
 
        weave = self.get_inventory_weave()
440
 
        all_revisions = self._eliminate_revisions_not_present(weave.versions())
441
 
        entire_graph = dict([(node, weave.get_parents(node)) for 
442
 
                             node in all_revisions])
443
 
        if revision_id is None:
444
 
            return entire_graph
445
 
        elif revision_id not in entire_graph:
446
 
            raise errors.NoSuchRevision(self, revision_id)
447
 
        else:
448
 
            # add what can be reached from revision_id
449
 
            result = {}
450
 
            pending = set([revision_id])
451
 
            while len(pending) > 0:
452
 
                node = pending.pop()
453
 
                result[node] = entire_graph[node]
454
 
                for revision_id in result[node]:
455
 
                    if revision_id not in result:
456
 
                        pending.add(revision_id)
457
 
            return result
458
 
 
459
 
    @needs_read_lock
460
 
    def get_revision_graph_with_ghosts(self, revision_ids=None):
461
 
        """Return a graph of the revisions with ghosts marked as applicable.
462
 
 
463
 
        :param revision_ids: an iterable of revisions to graph or None for all.
464
 
        :return: a Graph object with the graph reachable from revision_ids.
465
 
        """
466
 
        result = Graph()
467
 
        if not revision_ids:
468
 
            pending = set(self.all_revision_ids())
469
 
            required = set([])
470
 
        else:
471
 
            pending = set(revision_ids)
472
 
            required = set(revision_ids)
473
 
        done = set([])
474
 
        while len(pending):
475
 
            revision_id = pending.pop()
476
 
            try:
477
 
                rev = self.get_revision(revision_id)
478
 
            except errors.NoSuchRevision:
479
 
                if revision_id in required:
480
 
                    raise
481
 
                # a ghost
482
 
                result.add_ghost(revision_id)
483
 
                continue
484
 
            for parent_id in rev.parent_ids:
485
 
                # is this queued or done ?
486
 
                if (parent_id not in pending and
487
 
                    parent_id not in done):
488
 
                    # no, queue it.
489
 
                    pending.add(parent_id)
490
 
            result.add_node(revision_id, rev.parent_ids)
491
 
            done.add(revision_id)
492
 
        return result
493
 
 
494
 
    @needs_read_lock
495
 
    def get_revision_inventory(self, revision_id):
496
 
        """Return inventory of a past revision."""
497
 
        # TODO: Unify this with get_inventory()
498
 
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
499
 
        # must be the same as its revision, so this is trivial.
500
 
        if revision_id is None:
501
 
            # This does not make sense: if there is no revision,
502
 
            # then it is the current tree inventory surely ?!
503
 
            # and thus get_root_id() is something that looks at the last
504
 
            # commit on the branch, and the get_root_id is an inventory check.
505
 
            raise NotImplementedError
506
 
            # return Inventory(self.get_root_id())
507
 
        else:
508
 
            return self.get_inventory(revision_id)
509
 
 
510
 
    @needs_read_lock
511
 
    def is_shared(self):
512
 
        """Return True if this repository is flagged as a shared repository."""
513
 
        raise NotImplementedError(self.is_shared)
514
 
 
515
 
    @needs_write_lock
516
 
    def reconcile(self, other=None, thorough=False):
517
 
        """Reconcile this repository."""
518
 
        from bzrlib.reconcile import RepoReconciler
519
 
        reconciler = RepoReconciler(self, thorough=thorough)
520
 
        reconciler.reconcile()
521
 
        return reconciler
522
 
    
523
 
    @needs_read_lock
524
 
    def revision_tree(self, revision_id):
525
 
        """Return Tree for a revision on this branch.
526
 
 
527
 
        `revision_id` may be None for the null revision, in which case
528
 
        an `EmptyTree` is returned."""
529
 
        # TODO: refactor this to use an existing revision object
530
 
        # so we don't need to read it in twice.
531
 
        if revision_id is None or revision_id == NULL_REVISION:
532
 
            return EmptyTree()
533
 
        else:
534
 
            inv = self.get_revision_inventory(revision_id)
535
 
            return RevisionTree(self, inv, revision_id)
536
 
 
537
 
    @needs_read_lock
538
 
    def get_ancestry(self, revision_id):
539
 
        """Return a list of revision-ids integrated by a revision.
540
 
 
541
 
        The first element of the list is always None, indicating the origin 
542
 
        revision.  This might change when we have history horizons, or 
543
 
        perhaps we should have a new API.
544
 
        
545
 
        This is topologically sorted.
546
 
        """
547
 
        if revision_id is None:
548
 
            return [None]
549
 
        if not self.has_revision(revision_id):
550
 
            raise errors.NoSuchRevision(self, revision_id)
551
 
        w = self.get_inventory_weave()
552
 
        candidates = w.get_ancestry(revision_id)
553
 
        return [None] + candidates # self._eliminate_revisions_not_present(candidates)
554
 
 
555
 
    @needs_read_lock
556
 
    def print_file(self, file, revision_id):
557
 
        """Print `file` to stdout.
558
 
        
559
 
        FIXME RBC 20060125 as John Meinel points out this is a bad api
560
 
        - it writes to stdout, it assumes that that is valid etc. Fix
561
 
        by creating a new more flexible convenience function.
562
 
        """
563
 
        tree = self.revision_tree(revision_id)
564
 
        # use inventory as it was in that revision
565
 
        file_id = tree.inventory.path2id(file)
566
 
        if not file_id:
567
 
            # TODO: jam 20060427 Write a test for this code path
568
 
            #       it had a bug in it, and was raising the wrong
569
 
            #       exception.
570
 
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
571
 
        tree.print_file(file_id)
572
 
 
573
 
    def get_transaction(self):
574
 
        return self.control_files.get_transaction()
575
 
 
576
 
    def revision_parents(self, revid):
577
 
        return self.get_inventory_weave().parent_names(revid)
578
 
 
579
 
    @needs_write_lock
580
 
    def set_make_working_trees(self, new_value):
581
 
        """Set the policy flag for making working trees when creating branches.
582
 
 
583
 
        This only applies to branches that use this repository.
584
 
 
585
 
        The default is 'True'.
586
 
        :param new_value: True to restore the default, False to disable making
587
 
                          working trees.
588
 
        """
589
 
        raise NotImplementedError(self.set_make_working_trees)
590
 
    
591
 
    def make_working_trees(self):
592
 
        """Returns the policy for making working trees on new branches."""
593
 
        raise NotImplementedError(self.make_working_trees)
594
 
 
595
 
    @needs_write_lock
596
 
    def sign_revision(self, revision_id, gpg_strategy):
597
 
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
598
 
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
599
 
 
600
 
    @needs_read_lock
601
 
    def has_signature_for_revision_id(self, revision_id):
602
 
        """Query for a revision signature for revision_id in the repository."""
603
 
        return self._revision_store.has_signature(revision_id,
604
 
                                                  self.get_transaction())
605
 
 
606
 
    @needs_read_lock
607
 
    def get_signature_text(self, revision_id):
608
 
        """Return the text for a signature."""
609
 
        return self._revision_store.get_signature_text(revision_id,
610
 
                                                       self.get_transaction())
611
 
 
612
 
    @needs_read_lock
613
 
    def check(self, revision_ids):
614
 
        """Check consistency of all history of given revision_ids.
615
 
 
616
 
        Different repository implementations should override _check().
617
 
 
618
 
        :param revision_ids: A non-empty list of revision_ids whose ancestry
619
 
             will be checked.  Typically the last revision_id of a branch.
620
 
        """
621
 
        if not revision_ids:
622
 
            raise ValueError("revision_ids must be non-empty in %s.check" 
623
 
                    % (self,))
624
 
        return self._check(revision_ids)
625
 
 
626
 
    def _check(self, revision_ids):
627
 
        result = bzrlib.check.Check(self)
628
 
        result.check()
629
 
        return result
630
 
 
631
 
 
632
 
class AllInOneRepository(Repository):
633
 
    """Legacy support - the repository behaviour for all-in-one branches."""
634
 
 
635
 
    def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
636
 
        # we reuse one control files instance.
637
 
        dir_mode = a_bzrdir._control_files._dir_mode
638
 
        file_mode = a_bzrdir._control_files._file_mode
639
 
 
640
 
        def get_store(name, compressed=True, prefixed=False):
641
 
            # FIXME: This approach of assuming stores are all entirely compressed
642
 
            # or entirely uncompressed is tidy, but breaks upgrade from 
643
 
            # some existing branches where there's a mixture; we probably 
644
 
            # still want the option to look for both.
645
 
            relpath = a_bzrdir._control_files._escape(name)
646
 
            store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
647
 
                              prefixed=prefixed, compressed=compressed,
648
 
                              dir_mode=dir_mode,
649
 
                              file_mode=file_mode)
650
 
            #if self._transport.should_cache():
651
 
            #    cache_path = os.path.join(self.cache_root, name)
652
 
            #    os.mkdir(cache_path)
653
 
            #    store = bzrlib.store.CachedStore(store, cache_path)
654
 
            return store
655
 
 
656
 
        # not broken out yet because the controlweaves|inventory_store
657
 
        # and text_store | weave_store bits are still different.
658
 
        if isinstance(_format, RepositoryFormat4):
659
 
            # cannot remove these - there is still no consistent api 
660
 
            # which allows access to this old info.
661
 
            self.inventory_store = get_store('inventory-store')
662
 
            text_store = get_store('text-store')
663
 
        super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
664
 
 
665
 
    @needs_read_lock
666
 
    def is_shared(self):
667
 
        """AllInOne repositories cannot be shared."""
668
 
        return False
669
 
 
670
 
    @needs_write_lock
671
 
    def set_make_working_trees(self, new_value):
672
 
        """Set the policy flag for making working trees when creating branches.
673
 
 
674
 
        This only applies to branches that use this repository.
675
 
 
676
 
        The default is 'True'.
677
 
        :param new_value: True to restore the default, False to disable making
678
 
                          working trees.
679
 
        """
680
 
        raise NotImplementedError(self.set_make_working_trees)
681
 
    
682
 
    def make_working_trees(self):
683
 
        """Returns the policy for making working trees on new branches."""
684
 
        return True
685
 
 
686
 
 
687
 
def install_revision(repository, rev, revision_tree):
688
 
    """Install all revision data into a repository."""
689
 
    present_parents = []
690
 
    parent_trees = {}
691
 
    for p_id in rev.parent_ids:
692
 
        if repository.has_revision(p_id):
693
 
            present_parents.append(p_id)
694
 
            parent_trees[p_id] = repository.revision_tree(p_id)
695
 
        else:
696
 
            parent_trees[p_id] = EmptyTree()
697
 
 
698
 
    inv = revision_tree.inventory
699
 
    
700
 
    # Add the texts that are not already present
701
 
    for path, ie in inv.iter_entries():
702
 
        w = repository.weave_store.get_weave_or_empty(ie.file_id,
703
 
                repository.get_transaction())
704
 
        if ie.revision not in w:
705
 
            text_parents = []
706
 
            # FIXME: TODO: The following loop *may* be overlapping/duplicate
707
 
            # with InventoryEntry.find_previous_heads(). if it is, then there
708
 
            # is a latent bug here where the parents may have ancestors of each
709
 
            # other. RBC, AB
710
 
            for revision, tree in parent_trees.iteritems():
711
 
                if ie.file_id not in tree:
712
 
                    continue
713
 
                parent_id = tree.inventory[ie.file_id].revision
714
 
                if parent_id in text_parents:
715
 
                    continue
716
 
                text_parents.append(parent_id)
717
 
                    
718
 
            vfile = repository.weave_store.get_weave_or_empty(ie.file_id, 
719
 
                repository.get_transaction())
720
 
            lines = revision_tree.get_file(ie.file_id).readlines()
721
 
            vfile.add_lines(rev.revision_id, text_parents, lines)
722
 
    try:
723
 
        # install the inventory
724
 
        repository.add_inventory(rev.revision_id, inv, present_parents)
725
 
    except errors.RevisionAlreadyPresent:
726
 
        pass
727
 
    repository.add_revision(rev.revision_id, rev, inv)
728
 
 
729
 
 
730
 
class MetaDirRepository(Repository):
731
 
    """Repositories in the new meta-dir layout."""
732
 
 
733
 
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
734
 
        super(MetaDirRepository, self).__init__(_format,
735
 
                                                a_bzrdir,
736
 
                                                control_files,
737
 
                                                _revision_store,
738
 
                                                control_store,
739
 
                                                text_store)
740
 
 
741
 
        dir_mode = self.control_files._dir_mode
742
 
        file_mode = self.control_files._file_mode
743
 
 
744
 
    @needs_read_lock
745
 
    def is_shared(self):
746
 
        """Return True if this repository is flagged as a shared repository."""
747
 
        return self.control_files._transport.has('shared-storage')
748
 
 
749
 
    @needs_write_lock
750
 
    def set_make_working_trees(self, new_value):
751
 
        """Set the policy flag for making working trees when creating branches.
752
 
 
753
 
        This only applies to branches that use this repository.
754
 
 
755
 
        The default is 'True'.
756
 
        :param new_value: True to restore the default, False to disable making
757
 
                          working trees.
758
 
        """
759
 
        if new_value:
760
 
            try:
761
 
                self.control_files._transport.delete('no-working-trees')
762
 
            except errors.NoSuchFile:
763
 
                pass
764
 
        else:
765
 
            self.control_files.put_utf8('no-working-trees', '')
766
 
    
767
 
    def make_working_trees(self):
768
 
        """Returns the policy for making working trees on new branches."""
769
 
        return not self.control_files._transport.has('no-working-trees')
770
 
 
771
 
 
772
 
class KnitRepository(MetaDirRepository):
773
 
    """Knit format repository."""
774
 
 
775
 
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
776
 
        inv_vf.add_lines_with_ghosts(revid, parents, lines)
777
 
 
778
 
    @needs_read_lock
779
 
    def _all_revision_ids(self):
780
 
        """See Repository.all_revision_ids()."""
781
 
        # Knits get the revision graph from the index of the revision knit, so
782
 
        # it's always possible even if they're on an unlistable transport.
783
 
        return self._revision_store.all_revision_ids(self.get_transaction())
784
 
 
785
 
    def fileid_involved_between_revs(self, from_revid, to_revid):
786
 
        """Find file_id(s) which are involved in the changes between revisions.
787
 
 
788
 
        This determines the set of revisions which are involved, and then
789
 
        finds all file ids affected by those revisions.
790
 
        """
791
 
        vf = self._get_revision_vf()
792
 
        from_set = set(vf.get_ancestry(from_revid))
793
 
        to_set = set(vf.get_ancestry(to_revid))
794
 
        changed = to_set.difference(from_set)
795
 
        return self._fileid_involved_by_set(changed)
796
 
 
797
 
    def fileid_involved(self, last_revid=None):
798
 
        """Find all file_ids modified in the ancestry of last_revid.
799
 
 
800
 
        :param last_revid: If None, last_revision() will be used.
801
 
        """
802
 
        if not last_revid:
803
 
            changed = set(self.all_revision_ids())
804
 
        else:
805
 
            changed = set(self.get_ancestry(last_revid))
806
 
        if None in changed:
807
 
            changed.remove(None)
808
 
        return self._fileid_involved_by_set(changed)
809
 
 
810
 
    @needs_read_lock
811
 
    def get_ancestry(self, revision_id):
812
 
        """Return a list of revision-ids integrated by a revision.
813
 
        
814
 
        This is topologically sorted.
815
 
        """
816
 
        if revision_id is None:
817
 
            return [None]
818
 
        vf = self._get_revision_vf()
819
 
        try:
820
 
            return [None] + vf.get_ancestry(revision_id)
821
 
        except errors.RevisionNotPresent:
822
 
            raise errors.NoSuchRevision(self, revision_id)
823
 
 
824
 
    @needs_read_lock
825
 
    def get_revision(self, revision_id):
826
 
        """Return the Revision object for a named revision"""
827
 
        return self.get_revision_reconcile(revision_id)
828
 
 
829
 
    @needs_read_lock
830
 
    def get_revision_graph(self, revision_id=None):
831
 
        """Return a dictionary containing the revision graph.
832
 
        
833
 
        :return: a dictionary of revision_id->revision_parents_list.
834
 
        """
835
 
        weave = self._get_revision_vf()
836
 
        entire_graph = weave.get_graph()
837
 
        if revision_id is None:
838
 
            return weave.get_graph()
839
 
        elif revision_id not in weave:
840
 
            raise errors.NoSuchRevision(self, revision_id)
841
 
        else:
842
 
            # add what can be reached from revision_id
843
 
            result = {}
844
 
            pending = set([revision_id])
845
 
            while len(pending) > 0:
846
 
                node = pending.pop()
847
 
                result[node] = weave.get_parents(node)
848
 
                for revision_id in result[node]:
849
 
                    if revision_id not in result:
850
 
                        pending.add(revision_id)
851
 
            return result
852
 
 
853
 
    @needs_read_lock
854
 
    def get_revision_graph_with_ghosts(self, revision_ids=None):
855
 
        """Return a graph of the revisions with ghosts marked as applicable.
856
 
 
857
 
        :param revision_ids: an iterable of revisions to graph or None for all.
858
 
        :return: a Graph object with the graph reachable from revision_ids.
859
 
        """
860
 
        result = Graph()
861
 
        vf = self._get_revision_vf()
862
 
        versions = set(vf.versions())
863
 
        if not revision_ids:
864
 
            pending = set(self.all_revision_ids())
865
 
            required = set([])
866
 
        else:
867
 
            pending = set(revision_ids)
868
 
            required = set(revision_ids)
869
 
        done = set([])
870
 
        while len(pending):
871
 
            revision_id = pending.pop()
872
 
            if not revision_id in versions:
873
 
                if revision_id in required:
874
 
                    raise errors.NoSuchRevision(self, revision_id)
875
 
                # a ghost
876
 
                result.add_ghost(revision_id)
877
 
                # mark it as done so we don't try for it again.
878
 
                done.add(revision_id)
879
 
                continue
880
 
            parent_ids = vf.get_parents_with_ghosts(revision_id)
881
 
            for parent_id in parent_ids:
882
 
                # is this queued or done ?
883
 
                if (parent_id not in pending and
884
 
                    parent_id not in done):
885
 
                    # no, queue it.
886
 
                    pending.add(parent_id)
887
 
            result.add_node(revision_id, parent_ids)
888
 
            done.add(revision_id)
889
 
        return result
890
 
 
891
 
    def _get_revision_vf(self):
892
 
        """:return: a versioned file containing the revisions."""
893
 
        vf = self._revision_store.get_revision_file(self.get_transaction())
894
 
        return vf
895
 
 
896
 
    @needs_write_lock
897
 
    def reconcile(self, other=None, thorough=False):
898
 
        """Reconcile this repository."""
899
 
        from bzrlib.reconcile import KnitReconciler
900
 
        reconciler = KnitReconciler(self, thorough=thorough)
901
 
        reconciler.reconcile()
902
 
        return reconciler
903
 
    
904
 
    def revision_parents(self, revid):
905
 
        return self._get_revision_vf().get_parents(rev_id)
906
 
 
907
 
class RepositoryFormat(object):
908
 
    """A repository format.
909
 
 
910
 
    Formats provide three things:
911
 
     * An initialization routine to construct repository data on disk.
912
 
     * a format string which is used when the BzrDir supports versioned
913
 
       children.
914
 
     * an open routine which returns a Repository instance.
915
 
 
916
 
    Formats are placed in an dict by their format string for reference 
917
 
    during opening. These should be subclasses of RepositoryFormat
918
 
    for consistency.
919
 
 
920
 
    Once a format is deprecated, just deprecate the initialize and open
921
 
    methods on the format class. Do not deprecate the object, as the 
922
 
    object will be created every system load.
923
 
 
924
 
    Common instance attributes:
925
 
    _matchingbzrdir - the bzrdir format that the repository format was
926
 
    originally written to work with. This can be used if manually
927
 
    constructing a bzrdir and repository, or more commonly for test suite
928
 
    parameterisation.
929
 
    """
930
 
 
931
 
    _default_format = None
932
 
    """The default format used for new repositories."""
933
 
 
934
 
    _formats = {}
935
 
    """The known formats."""
936
 
 
937
 
    @classmethod
938
 
    def find_format(klass, a_bzrdir):
939
 
        """Return the format for the repository object in a_bzrdir."""
940
 
        try:
941
 
            transport = a_bzrdir.get_repository_transport(None)
942
 
            format_string = transport.get("format").read()
943
 
            return klass._formats[format_string]
944
 
        except errors.NoSuchFile:
945
 
            raise errors.NoRepositoryPresent(a_bzrdir)
946
 
        except KeyError:
947
 
            raise errors.UnknownFormatError(format_string)
948
 
 
949
 
    def _get_control_store(self, repo_transport, control_files):
950
 
        """Return the control store for this repository."""
951
 
        raise NotImplementedError(self._get_control_store)
952
 
    
953
 
    @classmethod
954
 
    def get_default_format(klass):
955
 
        """Return the current default format."""
956
 
        return klass._default_format
957
 
 
958
 
    def get_format_string(self):
959
 
        """Return the ASCII format string that identifies this format.
960
 
        
961
 
        Note that in pre format ?? repositories the format string is 
962
 
        not permitted nor written to disk.
963
 
        """
964
 
        raise NotImplementedError(self.get_format_string)
965
 
 
966
 
    def get_format_description(self):
967
 
        """Return the short description for this format."""
968
 
        raise NotImplementedError(self.get_format_description)
969
 
 
970
 
    def _get_revision_store(self, repo_transport, control_files):
971
 
        """Return the revision store object for this a_bzrdir."""
972
 
        raise NotImplementedError(self._get_revision_store)
973
 
 
974
 
    def _get_text_rev_store(self,
975
 
                            transport,
976
 
                            control_files,
977
 
                            name,
978
 
                            compressed=True,
979
 
                            prefixed=False,
980
 
                            serializer=None):
981
 
        """Common logic for getting a revision store for a repository.
982
 
        
983
 
        see self._get_revision_store for the subclass-overridable method to 
984
 
        get the store for a repository.
985
 
        """
986
 
        from bzrlib.store.revision.text import TextRevisionStore
987
 
        dir_mode = control_files._dir_mode
988
 
        file_mode = control_files._file_mode
989
 
        text_store =TextStore(transport.clone(name),
990
 
                              prefixed=prefixed,
991
 
                              compressed=compressed,
992
 
                              dir_mode=dir_mode,
993
 
                              file_mode=file_mode)
994
 
        _revision_store = TextRevisionStore(text_store, serializer)
995
 
        return _revision_store
996
 
 
997
 
    def _get_versioned_file_store(self,
998
 
                                  name,
999
 
                                  transport,
1000
 
                                  control_files,
1001
 
                                  prefixed=True,
1002
 
                                  versionedfile_class=WeaveFile,
1003
 
                                  escaped=False):
1004
 
        weave_transport = control_files._transport.clone(name)
1005
 
        dir_mode = control_files._dir_mode
1006
 
        file_mode = control_files._file_mode
1007
 
        return VersionedFileStore(weave_transport, prefixed=prefixed,
1008
 
                                  dir_mode=dir_mode,
1009
 
                                  file_mode=file_mode,
1010
 
                                  versionedfile_class=versionedfile_class,
1011
 
                                  escaped=escaped)
1012
 
 
1013
 
    def initialize(self, a_bzrdir, shared=False):
1014
 
        """Initialize a repository of this format in a_bzrdir.
1015
 
 
1016
 
        :param a_bzrdir: The bzrdir to put the new repository in it.
1017
 
        :param shared: The repository should be initialized as a sharable one.
1018
 
 
1019
 
        This may raise UninitializableFormat if shared repository are not
1020
 
        compatible the a_bzrdir.
1021
 
        """
1022
 
 
1023
 
    def is_supported(self):
1024
 
        """Is this format supported?
1025
 
 
1026
 
        Supported formats must be initializable and openable.
1027
 
        Unsupported formats may not support initialization or committing or 
1028
 
        some other features depending on the reason for not being supported.
1029
 
        """
1030
 
        return True
1031
 
 
1032
 
    def open(self, a_bzrdir, _found=False):
1033
 
        """Return an instance of this format for the bzrdir a_bzrdir.
1034
 
        
1035
 
        _found is a private parameter, do not use it.
1036
 
        """
1037
 
        raise NotImplementedError(self.open)
1038
 
 
1039
 
    @classmethod
1040
 
    def register_format(klass, format):
1041
 
        klass._formats[format.get_format_string()] = format
1042
 
 
1043
 
    @classmethod
1044
 
    def set_default_format(klass, format):
1045
 
        klass._default_format = format
1046
 
 
1047
 
    @classmethod
1048
 
    def unregister_format(klass, format):
1049
 
        assert klass._formats[format.get_format_string()] is format
1050
 
        del klass._formats[format.get_format_string()]
1051
 
 
1052
 
 
1053
 
class PreSplitOutRepositoryFormat(RepositoryFormat):
1054
 
    """Base class for the pre split out repository formats."""
1055
 
 
1056
 
    def initialize(self, a_bzrdir, shared=False, _internal=False):
1057
 
        """Create a weave repository.
1058
 
        
1059
 
        TODO: when creating split out bzr branch formats, move this to a common
1060
 
        base for Format5, Format6. or something like that.
1061
 
        """
1062
 
        from bzrlib.weavefile import write_weave_v5
1063
 
        from bzrlib.weave import Weave
1064
 
 
1065
 
        if shared:
1066
 
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
1067
 
 
1068
 
        if not _internal:
1069
 
            # always initialized when the bzrdir is.
1070
 
            return self.open(a_bzrdir, _found=True)
1071
 
        
1072
 
        # Create an empty weave
1073
 
        sio = StringIO()
1074
 
        bzrlib.weavefile.write_weave_v5(Weave(), sio)
1075
 
        empty_weave = sio.getvalue()
1076
 
 
1077
 
        mutter('creating repository in %s.', a_bzrdir.transport.base)
1078
 
        dirs = ['revision-store', 'weaves']
1079
 
        files = [('inventory.weave', StringIO(empty_weave)),
1080
 
                 ]
1081
 
        
1082
 
        # FIXME: RBC 20060125 don't peek under the covers
1083
 
        # NB: no need to escape relative paths that are url safe.
1084
 
        control_files = LockableFiles(a_bzrdir.transport, 'branch-lock',
1085
 
                                      TransportLock)
1086
 
        control_files.create_lock()
1087
 
        control_files.lock_write()
1088
 
        control_files._transport.mkdir_multi(dirs,
1089
 
                mode=control_files._dir_mode)
1090
 
        try:
1091
 
            for file, content in files:
1092
 
                control_files.put(file, content)
1093
 
        finally:
1094
 
            control_files.unlock()
1095
 
        return self.open(a_bzrdir, _found=True)
1096
 
 
1097
 
    def _get_control_store(self, repo_transport, control_files):
1098
 
        """Return the control store for this repository."""
1099
 
        return self._get_versioned_file_store('',
1100
 
                                              repo_transport,
1101
 
                                              control_files,
1102
 
                                              prefixed=False)
1103
 
 
1104
 
    def _get_text_store(self, transport, control_files):
1105
 
        """Get a store for file texts for this format."""
1106
 
        raise NotImplementedError(self._get_text_store)
1107
 
 
1108
 
    def open(self, a_bzrdir, _found=False):
1109
 
        """See RepositoryFormat.open()."""
1110
 
        if not _found:
1111
 
            # we are being called directly and must probe.
1112
 
            raise NotImplementedError
1113
 
 
1114
 
        repo_transport = a_bzrdir.get_repository_transport(None)
1115
 
        control_files = a_bzrdir._control_files
1116
 
        text_store = self._get_text_store(repo_transport, control_files)
1117
 
        control_store = self._get_control_store(repo_transport, control_files)
1118
 
        _revision_store = self._get_revision_store(repo_transport, control_files)
1119
 
        return AllInOneRepository(_format=self,
1120
 
                                  a_bzrdir=a_bzrdir,
1121
 
                                  _revision_store=_revision_store,
1122
 
                                  control_store=control_store,
1123
 
                                  text_store=text_store)
1124
 
 
1125
 
 
1126
 
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1127
 
    """Bzr repository format 4.
1128
 
 
1129
 
    This repository format has:
1130
 
     - flat stores
1131
 
     - TextStores for texts, inventories,revisions.
1132
 
 
1133
 
    This format is deprecated: it indexes texts using a text id which is
1134
 
    removed in format 5; initialization and write support for this format
1135
 
    has been removed.
1136
 
    """
1137
 
 
1138
 
    def __init__(self):
1139
 
        super(RepositoryFormat4, self).__init__()
1140
 
        self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
1141
 
 
1142
 
    def get_format_description(self):
1143
 
        """See RepositoryFormat.get_format_description()."""
1144
 
        return "Repository format 4"
1145
 
 
1146
 
    def initialize(self, url, shared=False, _internal=False):
1147
 
        """Format 4 branches cannot be created."""
1148
 
        raise errors.UninitializableFormat(self)
1149
 
 
1150
 
    def is_supported(self):
1151
 
        """Format 4 is not supported.
1152
 
 
1153
 
        It is not supported because the model changed from 4 to 5 and the
1154
 
        conversion logic is expensive - so doing it on the fly was not 
1155
 
        feasible.
1156
 
        """
1157
 
        return False
1158
 
 
1159
 
    def _get_control_store(self, repo_transport, control_files):
1160
 
        """Format 4 repositories have no formal control store at this point.
1161
 
        
1162
 
        This will cause any control-file-needing apis to fail - this is desired.
1163
 
        """
1164
 
        return None
1165
 
    
1166
 
    def _get_revision_store(self, repo_transport, control_files):
1167
 
        """See RepositoryFormat._get_revision_store()."""
1168
 
        from bzrlib.xml4 import serializer_v4
1169
 
        return self._get_text_rev_store(repo_transport,
1170
 
                                        control_files,
1171
 
                                        'revision-store',
1172
 
                                        serializer=serializer_v4)
1173
 
 
1174
 
    def _get_text_store(self, transport, control_files):
1175
 
        """See RepositoryFormat._get_text_store()."""
1176
 
 
1177
 
 
1178
 
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1179
 
    """Bzr control format 5.
1180
 
 
1181
 
    This repository format has:
1182
 
     - weaves for file texts and inventory
1183
 
     - flat stores
1184
 
     - TextStores for revisions and signatures.
1185
 
    """
1186
 
 
1187
 
    def __init__(self):
1188
 
        super(RepositoryFormat5, self).__init__()
1189
 
        self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
1190
 
 
1191
 
    def get_format_description(self):
1192
 
        """See RepositoryFormat.get_format_description()."""
1193
 
        return "Weave repository format 5"
1194
 
 
1195
 
    def _get_revision_store(self, repo_transport, control_files):
1196
 
        """See RepositoryFormat._get_revision_store()."""
1197
 
        """Return the revision store object for this a_bzrdir."""
1198
 
        return self._get_text_rev_store(repo_transport,
1199
 
                                        control_files,
1200
 
                                        'revision-store',
1201
 
                                        compressed=False)
1202
 
 
1203
 
    def _get_text_store(self, transport, control_files):
1204
 
        """See RepositoryFormat._get_text_store()."""
1205
 
        return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1206
 
 
1207
 
 
1208
 
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1209
 
    """Bzr control format 6.
1210
 
 
1211
 
    This repository format has:
1212
 
     - weaves for file texts and inventory
1213
 
     - hash subdirectory based stores.
1214
 
     - TextStores for revisions and signatures.
1215
 
    """
1216
 
 
1217
 
    def __init__(self):
1218
 
        super(RepositoryFormat6, self).__init__()
1219
 
        self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
1220
 
 
1221
 
    def get_format_description(self):
1222
 
        """See RepositoryFormat.get_format_description()."""
1223
 
        return "Weave repository format 6"
1224
 
 
1225
 
    def _get_revision_store(self, repo_transport, control_files):
1226
 
        """See RepositoryFormat._get_revision_store()."""
1227
 
        return self._get_text_rev_store(repo_transport,
1228
 
                                        control_files,
1229
 
                                        'revision-store',
1230
 
                                        compressed=False,
1231
 
                                        prefixed=True)
1232
 
 
1233
 
    def _get_text_store(self, transport, control_files):
1234
 
        """See RepositoryFormat._get_text_store()."""
1235
 
        return self._get_versioned_file_store('weaves', transport, control_files)
1236
 
 
1237
 
 
1238
 
class MetaDirRepositoryFormat(RepositoryFormat):
1239
 
    """Common base class for the new repositories using the metadir layout."""
1240
 
 
1241
 
    def __init__(self):
1242
 
        super(MetaDirRepositoryFormat, self).__init__()
1243
 
        self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
1244
 
 
1245
 
    def _create_control_files(self, a_bzrdir):
1246
 
        """Create the required files and the initial control_files object."""
1247
 
        # FIXME: RBC 20060125 don't peek under the covers
1248
 
        # NB: no need to escape relative paths that are url safe.
1249
 
        repository_transport = a_bzrdir.get_repository_transport(self)
1250
 
        control_files = LockableFiles(repository_transport, 'lock', LockDir)
1251
 
        control_files.create_lock()
1252
 
        return control_files
1253
 
 
1254
 
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1255
 
        """Upload the initial blank content."""
1256
 
        control_files = self._create_control_files(a_bzrdir)
1257
 
        control_files.lock_write()
1258
 
        try:
1259
 
            control_files._transport.mkdir_multi(dirs,
1260
 
                    mode=control_files._dir_mode)
1261
 
            for file, content in files:
1262
 
                control_files.put(file, content)
1263
 
            for file, content in utf8_files:
1264
 
                control_files.put_utf8(file, content)
1265
 
            if shared == True:
1266
 
                control_files.put_utf8('shared-storage', '')
1267
 
        finally:
1268
 
            control_files.unlock()
1269
 
 
1270
 
 
1271
 
class RepositoryFormat7(MetaDirRepositoryFormat):
1272
 
    """Bzr repository 7.
1273
 
 
1274
 
    This repository format has:
1275
 
     - weaves for file texts and inventory
1276
 
     - hash subdirectory based stores.
1277
 
     - TextStores for revisions and signatures.
1278
 
     - a format marker of its own
1279
 
     - an optional 'shared-storage' flag
1280
 
     - an optional 'no-working-trees' flag
1281
 
    """
1282
 
 
1283
 
    def _get_control_store(self, repo_transport, control_files):
1284
 
        """Return the control store for this repository."""
1285
 
        return self._get_versioned_file_store('',
1286
 
                                              repo_transport,
1287
 
                                              control_files,
1288
 
                                              prefixed=False)
1289
 
 
1290
 
    def get_format_string(self):
1291
 
        """See RepositoryFormat.get_format_string()."""
1292
 
        return "Bazaar-NG Repository format 7"
1293
 
 
1294
 
    def get_format_description(self):
1295
 
        """See RepositoryFormat.get_format_description()."""
1296
 
        return "Weave repository format 7"
1297
 
 
1298
 
    def _get_revision_store(self, repo_transport, control_files):
1299
 
        """See RepositoryFormat._get_revision_store()."""
1300
 
        return self._get_text_rev_store(repo_transport,
1301
 
                                        control_files,
1302
 
                                        'revision-store',
1303
 
                                        compressed=False,
1304
 
                                        prefixed=True,
1305
 
                                        )
1306
 
 
1307
 
    def _get_text_store(self, transport, control_files):
1308
 
        """See RepositoryFormat._get_text_store()."""
1309
 
        return self._get_versioned_file_store('weaves',
1310
 
                                              transport,
1311
 
                                              control_files)
1312
 
 
1313
 
    def initialize(self, a_bzrdir, shared=False):
1314
 
        """Create a weave repository.
1315
 
 
1316
 
        :param shared: If true the repository will be initialized as a shared
1317
 
                       repository.
1318
 
        """
1319
 
        from bzrlib.weavefile import write_weave_v5
1320
 
        from bzrlib.weave import Weave
1321
 
 
1322
 
        # Create an empty weave
1323
 
        sio = StringIO()
1324
 
        bzrlib.weavefile.write_weave_v5(Weave(), sio)
1325
 
        empty_weave = sio.getvalue()
1326
 
 
1327
 
        mutter('creating repository in %s.', a_bzrdir.transport.base)
1328
 
        dirs = ['revision-store', 'weaves']
1329
 
        files = [('inventory.weave', StringIO(empty_weave)), 
1330
 
                 ]
1331
 
        utf8_files = [('format', self.get_format_string())]
1332
 
 
1333
 
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1334
 
        return self.open(a_bzrdir=a_bzrdir, _found=True)
1335
 
 
1336
 
    def open(self, a_bzrdir, _found=False, _override_transport=None):
1337
 
        """See RepositoryFormat.open().
1338
 
        
1339
 
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
1340
 
                                    repository at a slightly different url
1341
 
                                    than normal. I.e. during 'upgrade'.
1342
 
        """
1343
 
        if not _found:
1344
 
            format = RepositoryFormat.find_format(a_bzrdir)
1345
 
            assert format.__class__ ==  self.__class__
1346
 
        if _override_transport is not None:
1347
 
            repo_transport = _override_transport
1348
 
        else:
1349
 
            repo_transport = a_bzrdir.get_repository_transport(None)
1350
 
        control_files = LockableFiles(repo_transport, 'lock', LockDir)
1351
 
        text_store = self._get_text_store(repo_transport, control_files)
1352
 
        control_store = self._get_control_store(repo_transport, control_files)
1353
 
        _revision_store = self._get_revision_store(repo_transport, control_files)
1354
 
        return MetaDirRepository(_format=self,
1355
 
                                 a_bzrdir=a_bzrdir,
1356
 
                                 control_files=control_files,
1357
 
                                 _revision_store=_revision_store,
1358
 
                                 control_store=control_store,
1359
 
                                 text_store=text_store)
1360
 
 
1361
 
 
1362
 
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
1363
 
    """Bzr repository knit format 1.
1364
 
 
1365
 
    This repository format has:
1366
 
     - knits for file texts and inventory
1367
 
     - hash subdirectory based stores.
1368
 
     - knits for revisions and signatures
1369
 
     - TextStores for revisions and signatures.
1370
 
     - a format marker of its own
1371
 
     - an optional 'shared-storage' flag
1372
 
     - an optional 'no-working-trees' flag
1373
 
     - a LockDir lock
1374
 
 
1375
 
    This format was introduced in bzr 0.8.
1376
 
    """
1377
 
 
1378
 
    def _get_control_store(self, repo_transport, control_files):
1379
 
        """Return the control store for this repository."""
1380
 
        return VersionedFileStore(
1381
 
            repo_transport,
1382
 
            prefixed=False,
1383
 
            file_mode=control_files._file_mode,
1384
 
            versionedfile_class=KnitVersionedFile,
1385
 
            versionedfile_kwargs={'factory':KnitPlainFactory()},
1386
 
            )
1387
 
 
1388
 
    def get_format_string(self):
1389
 
        """See RepositoryFormat.get_format_string()."""
1390
 
        return "Bazaar-NG Knit Repository Format 1"
1391
 
 
1392
 
    def get_format_description(self):
1393
 
        """See RepositoryFormat.get_format_description()."""
1394
 
        return "Knit repository format 1"
1395
 
 
1396
 
    def _get_revision_store(self, repo_transport, control_files):
1397
 
        """See RepositoryFormat._get_revision_store()."""
1398
 
        from bzrlib.store.revision.knit import KnitRevisionStore
1399
 
        versioned_file_store = VersionedFileStore(
1400
 
            repo_transport,
1401
 
            file_mode=control_files._file_mode,
1402
 
            prefixed=False,
1403
 
            precious=True,
1404
 
            versionedfile_class=KnitVersionedFile,
1405
 
            versionedfile_kwargs={'delta':False, 'factory':KnitPlainFactory()},
1406
 
            escaped=True,
1407
 
            )
1408
 
        return KnitRevisionStore(versioned_file_store)
1409
 
 
1410
 
    def _get_text_store(self, transport, control_files):
1411
 
        """See RepositoryFormat._get_text_store()."""
1412
 
        return self._get_versioned_file_store('knits',
1413
 
                                              transport,
1414
 
                                              control_files,
1415
 
                                              versionedfile_class=KnitVersionedFile,
1416
 
                                              escaped=True)
1417
 
 
1418
 
    def initialize(self, a_bzrdir, shared=False):
1419
 
        """Create a knit format 1 repository.
1420
 
 
1421
 
        :param a_bzrdir: bzrdir to contain the new repository; must already
1422
 
            be initialized.
1423
 
        :param shared: If true the repository will be initialized as a shared
1424
 
                       repository.
1425
 
        """
1426
 
        mutter('creating repository in %s.', a_bzrdir.transport.base)
1427
 
        dirs = ['revision-store', 'knits']
1428
 
        files = []
1429
 
        utf8_files = [('format', self.get_format_string())]
1430
 
        
1431
 
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1432
 
        repo_transport = a_bzrdir.get_repository_transport(None)
1433
 
        control_files = LockableFiles(repo_transport, 'lock', LockDir)
1434
 
        control_store = self._get_control_store(repo_transport, control_files)
1435
 
        transaction = bzrlib.transactions.WriteTransaction()
1436
 
        # trigger a write of the inventory store.
1437
 
        control_store.get_weave_or_empty('inventory', transaction)
1438
 
        _revision_store = self._get_revision_store(repo_transport, control_files)
1439
 
        _revision_store.has_revision_id('A', transaction)
1440
 
        _revision_store.get_signature_file(transaction)
1441
 
        return self.open(a_bzrdir=a_bzrdir, _found=True)
1442
 
 
1443
 
    def open(self, a_bzrdir, _found=False, _override_transport=None):
1444
 
        """See RepositoryFormat.open().
1445
 
        
1446
 
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
1447
 
                                    repository at a slightly different url
1448
 
                                    than normal. I.e. during 'upgrade'.
1449
 
        """
1450
 
        if not _found:
1451
 
            format = RepositoryFormat.find_format(a_bzrdir)
1452
 
            assert format.__class__ ==  self.__class__
1453
 
        if _override_transport is not None:
1454
 
            repo_transport = _override_transport
1455
 
        else:
1456
 
            repo_transport = a_bzrdir.get_repository_transport(None)
1457
 
        control_files = LockableFiles(repo_transport, 'lock', LockDir)
1458
 
        text_store = self._get_text_store(repo_transport, control_files)
1459
 
        control_store = self._get_control_store(repo_transport, control_files)
1460
 
        _revision_store = self._get_revision_store(repo_transport, control_files)
1461
 
        return KnitRepository(_format=self,
1462
 
                              a_bzrdir=a_bzrdir,
1463
 
                              control_files=control_files,
1464
 
                              _revision_store=_revision_store,
1465
 
                              control_store=control_store,
1466
 
                              text_store=text_store)
1467
 
 
1468
 
 
1469
 
# formats which have no format string are not discoverable
1470
 
# and not independently creatable, so are not registered.
1471
 
RepositoryFormat.register_format(RepositoryFormat7())
1472
 
_default_format = RepositoryFormatKnit1()
1473
 
RepositoryFormat.register_format(_default_format)
1474
 
RepositoryFormat.set_default_format(_default_format)
1475
 
_legacy_formats = [RepositoryFormat4(),
1476
 
                   RepositoryFormat5(),
1477
 
                   RepositoryFormat6()]
1478
 
 
1479
 
 
1480
 
class InterRepository(InterObject):
1481
 
    """This class represents operations taking place between two repositories.
1482
 
 
1483
 
    Its instances have methods like copy_content and fetch, and contain
1484
 
    references to the source and target repositories these operations can be 
1485
 
    carried out on.
1486
 
 
1487
 
    Often we will provide convenience methods on 'repository' which carry out
1488
 
    operations with another repository - they will always forward to
1489
 
    InterRepository.get(other).method_name(parameters).
1490
 
    """
1491
 
 
1492
 
    _optimisers = set()
1493
 
    """The available optimised InterRepository types."""
1494
 
 
1495
 
    @needs_write_lock
1496
 
    def copy_content(self, revision_id=None, basis=None):
1497
 
        """Make a complete copy of the content in self into destination.
1498
 
        
1499
 
        This is a destructive operation! Do not use it on existing 
1500
 
        repositories.
1501
 
 
1502
 
        :param revision_id: Only copy the content needed to construct
1503
 
                            revision_id and its parents.
1504
 
        :param basis: Copy the needed data preferentially from basis.
1505
 
        """
1506
 
        try:
1507
 
            self.target.set_make_working_trees(self.source.make_working_trees())
1508
 
        except NotImplementedError:
1509
 
            pass
1510
 
        # grab the basis available data
1511
 
        if basis is not None:
1512
 
            self.target.fetch(basis, revision_id=revision_id)
1513
 
        # but don't bother fetching if we have the needed data now.
1514
 
        if (revision_id not in (None, NULL_REVISION) and 
1515
 
            self.target.has_revision(revision_id)):
1516
 
            return
1517
 
        self.target.fetch(self.source, revision_id=revision_id)
1518
 
 
1519
 
    def _double_lock(self, lock_source, lock_target):
1520
 
        """Take out too locks, rolling back the first if the second throws."""
1521
 
        lock_source()
1522
 
        try:
1523
 
            lock_target()
1524
 
        except Exception:
1525
 
            # we want to ensure that we don't leave source locked by mistake.
1526
 
            # and any error on target should not confuse source.
1527
 
            self.source.unlock()
1528
 
            raise
1529
 
 
1530
 
    @needs_write_lock
1531
 
    def fetch(self, revision_id=None, pb=None):
1532
 
        """Fetch the content required to construct revision_id.
1533
 
 
1534
 
        The content is copied from source to target.
1535
 
 
1536
 
        :param revision_id: if None all content is copied, if NULL_REVISION no
1537
 
                            content is copied.
1538
 
        :param pb: optional progress bar to use for progress reports. If not
1539
 
                   provided a default one will be created.
1540
 
 
1541
 
        Returns the copied revision count and the failed revisions in a tuple:
1542
 
        (copied, failures).
1543
 
        """
1544
 
        from bzrlib.fetch import GenericRepoFetcher
1545
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1546
 
               self.source, self.source._format, self.target, self.target._format)
1547
 
        f = GenericRepoFetcher(to_repository=self.target,
1548
 
                               from_repository=self.source,
1549
 
                               last_revision=revision_id,
1550
 
                               pb=pb)
1551
 
        return f.count_copied, f.failed_revisions
1552
 
 
1553
 
    def lock_read(self):
1554
 
        """Take out a logical read lock.
1555
 
 
1556
 
        This will lock the source branch and the target branch. The source gets
1557
 
        a read lock and the target a read lock.
1558
 
        """
1559
 
        self._double_lock(self.source.lock_read, self.target.lock_read)
1560
 
 
1561
 
    def lock_write(self):
1562
 
        """Take out a logical write lock.
1563
 
 
1564
 
        This will lock the source branch and the target branch. The source gets
1565
 
        a read lock and the target a write lock.
1566
 
        """
1567
 
        self._double_lock(self.source.lock_read, self.target.lock_write)
1568
 
 
1569
 
    @needs_read_lock
1570
 
    def missing_revision_ids(self, revision_id=None):
1571
 
        """Return the revision ids that source has that target does not.
1572
 
        
1573
 
        These are returned in topological order.
1574
 
 
1575
 
        :param revision_id: only return revision ids included by this
1576
 
                            revision_id.
1577
 
        """
1578
 
        # generic, possibly worst case, slow code path.
1579
 
        target_ids = set(self.target.all_revision_ids())
1580
 
        if revision_id is not None:
1581
 
            source_ids = self.source.get_ancestry(revision_id)
1582
 
            assert source_ids[0] == None
1583
 
            source_ids.pop(0)
1584
 
        else:
1585
 
            source_ids = self.source.all_revision_ids()
1586
 
        result_set = set(source_ids).difference(target_ids)
1587
 
        # this may look like a no-op: its not. It preserves the ordering
1588
 
        # other_ids had while only returning the members from other_ids
1589
 
        # that we've decided we need.
1590
 
        return [rev_id for rev_id in source_ids if rev_id in result_set]
1591
 
 
1592
 
    def unlock(self):
1593
 
        """Release the locks on source and target."""
1594
 
        try:
1595
 
            self.target.unlock()
1596
 
        finally:
1597
 
            self.source.unlock()
1598
 
 
1599
 
 
1600
 
class InterWeaveRepo(InterRepository):
1601
 
    """Optimised code paths between Weave based repositories."""
1602
 
 
1603
 
    _matching_repo_format = RepositoryFormat7()
1604
 
    """Repository format for testing with."""
1605
 
 
1606
 
    @staticmethod
1607
 
    def is_compatible(source, target):
1608
 
        """Be compatible with known Weave formats.
1609
 
        
1610
 
        We don't test for the stores being of specific types because that
1611
 
        could lead to confusing results, and there is no need to be 
1612
 
        overly general.
1613
 
        """
1614
 
        try:
1615
 
            return (isinstance(source._format, (RepositoryFormat5,
1616
 
                                                RepositoryFormat6,
1617
 
                                                RepositoryFormat7)) and
1618
 
                    isinstance(target._format, (RepositoryFormat5,
1619
 
                                                RepositoryFormat6,
1620
 
                                                RepositoryFormat7)))
1621
 
        except AttributeError:
1622
 
            return False
1623
 
    
1624
 
    @needs_write_lock
1625
 
    def copy_content(self, revision_id=None, basis=None):
1626
 
        """See InterRepository.copy_content()."""
1627
 
        # weave specific optimised path:
1628
 
        if basis is not None:
1629
 
            # copy the basis in, then fetch remaining data.
1630
 
            basis.copy_content_into(self.target, revision_id)
1631
 
            # the basis copy_content_into could miss-set this.
1632
 
            try:
1633
 
                self.target.set_make_working_trees(self.source.make_working_trees())
1634
 
            except NotImplementedError:
1635
 
                pass
1636
 
            self.target.fetch(self.source, revision_id=revision_id)
1637
 
        else:
1638
 
            try:
1639
 
                self.target.set_make_working_trees(self.source.make_working_trees())
1640
 
            except NotImplementedError:
1641
 
                pass
1642
 
            # FIXME do not peek!
1643
 
            if self.source.control_files._transport.listable():
1644
 
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
1645
 
                try:
1646
 
                    self.target.weave_store.copy_all_ids(
1647
 
                        self.source.weave_store,
1648
 
                        pb=pb,
1649
 
                        from_transaction=self.source.get_transaction(),
1650
 
                        to_transaction=self.target.get_transaction())
1651
 
                    pb.update('copying inventory', 0, 1)
1652
 
                    self.target.control_weaves.copy_multi(
1653
 
                        self.source.control_weaves, ['inventory'],
1654
 
                        from_transaction=self.source.get_transaction(),
1655
 
                        to_transaction=self.target.get_transaction())
1656
 
                    self.target._revision_store.text_store.copy_all_ids(
1657
 
                        self.source._revision_store.text_store,
1658
 
                        pb=pb)
1659
 
                finally:
1660
 
                    pb.finished()
1661
 
            else:
1662
 
                self.target.fetch(self.source, revision_id=revision_id)
1663
 
 
1664
 
    @needs_write_lock
1665
 
    def fetch(self, revision_id=None, pb=None):
1666
 
        """See InterRepository.fetch()."""
1667
 
        from bzrlib.fetch import GenericRepoFetcher
1668
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1669
 
               self.source, self.source._format, self.target, self.target._format)
1670
 
        f = GenericRepoFetcher(to_repository=self.target,
1671
 
                               from_repository=self.source,
1672
 
                               last_revision=revision_id,
1673
 
                               pb=pb)
1674
 
        return f.count_copied, f.failed_revisions
1675
 
 
1676
 
    @needs_read_lock
1677
 
    def missing_revision_ids(self, revision_id=None):
1678
 
        """See InterRepository.missing_revision_ids()."""
1679
 
        # we want all revisions to satisfy revision_id in source.
1680
 
        # but we don't want to stat every file here and there.
1681
 
        # we want then, all revisions other needs to satisfy revision_id 
1682
 
        # checked, but not those that we have locally.
1683
 
        # so the first thing is to get a subset of the revisions to 
1684
 
        # satisfy revision_id in source, and then eliminate those that
1685
 
        # we do already have. 
1686
 
        # this is slow on high latency connection to self, but as as this
1687
 
        # disk format scales terribly for push anyway due to rewriting 
1688
 
        # inventory.weave, this is considered acceptable.
1689
 
        # - RBC 20060209
1690
 
        if revision_id is not None:
1691
 
            source_ids = self.source.get_ancestry(revision_id)
1692
 
            assert source_ids[0] == None
1693
 
            source_ids.pop(0)
1694
 
        else:
1695
 
            source_ids = self.source._all_possible_ids()
1696
 
        source_ids_set = set(source_ids)
1697
 
        # source_ids is the worst possible case we may need to pull.
1698
 
        # now we want to filter source_ids against what we actually
1699
 
        # have in target, but don't try to check for existence where we know
1700
 
        # we do not have a revision as that would be pointless.
1701
 
        target_ids = set(self.target._all_possible_ids())
1702
 
        possibly_present_revisions = target_ids.intersection(source_ids_set)
1703
 
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1704
 
        required_revisions = source_ids_set.difference(actually_present_revisions)
1705
 
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1706
 
        if revision_id is not None:
1707
 
            # we used get_ancestry to determine source_ids then we are assured all
1708
 
            # revisions referenced are present as they are installed in topological order.
1709
 
            # and the tip revision was validated by get_ancestry.
1710
 
            return required_topo_revisions
1711
 
        else:
1712
 
            # if we just grabbed the possibly available ids, then 
1713
 
            # we only have an estimate of whats available and need to validate
1714
 
            # that against the revision records.
1715
 
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
1716
 
 
1717
 
 
1718
 
class InterKnitRepo(InterRepository):
1719
 
    """Optimised code paths between Knit based repositories."""
1720
 
 
1721
 
    _matching_repo_format = RepositoryFormatKnit1()
1722
 
    """Repository format for testing with."""
1723
 
 
1724
 
    @staticmethod
1725
 
    def is_compatible(source, target):
1726
 
        """Be compatible with known Knit formats.
1727
 
        
1728
 
        We don't test for the stores being of specific types because that
1729
 
        could lead to confusing results, and there is no need to be 
1730
 
        overly general.
1731
 
        """
1732
 
        try:
1733
 
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
1734
 
                    isinstance(target._format, (RepositoryFormatKnit1)))
1735
 
        except AttributeError:
1736
 
            return False
1737
 
 
1738
 
    @needs_write_lock
1739
 
    def fetch(self, revision_id=None, pb=None):
1740
 
        """See InterRepository.fetch()."""
1741
 
        from bzrlib.fetch import KnitRepoFetcher
1742
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1743
 
               self.source, self.source._format, self.target, self.target._format)
1744
 
        f = KnitRepoFetcher(to_repository=self.target,
1745
 
                            from_repository=self.source,
1746
 
                            last_revision=revision_id,
1747
 
                            pb=pb)
1748
 
        return f.count_copied, f.failed_revisions
1749
 
 
1750
 
    @needs_read_lock
1751
 
    def missing_revision_ids(self, revision_id=None):
1752
 
        """See InterRepository.missing_revision_ids()."""
1753
 
        if revision_id is not None:
1754
 
            source_ids = self.source.get_ancestry(revision_id)
1755
 
            assert source_ids[0] == None
1756
 
            source_ids.pop(0)
1757
 
        else:
1758
 
            source_ids = self.source._all_possible_ids()
1759
 
        source_ids_set = set(source_ids)
1760
 
        # source_ids is the worst possible case we may need to pull.
1761
 
        # now we want to filter source_ids against what we actually
1762
 
        # have in target, but don't try to check for existence where we know
1763
 
        # we do not have a revision as that would be pointless.
1764
 
        target_ids = set(self.target._all_possible_ids())
1765
 
        possibly_present_revisions = target_ids.intersection(source_ids_set)
1766
 
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1767
 
        required_revisions = source_ids_set.difference(actually_present_revisions)
1768
 
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1769
 
        if revision_id is not None:
1770
 
            # we used get_ancestry to determine source_ids then we are assured all
1771
 
            # revisions referenced are present as they are installed in topological order.
1772
 
            # and the tip revision was validated by get_ancestry.
1773
 
            return required_topo_revisions
1774
 
        else:
1775
 
            # if we just grabbed the possibly available ids, then 
1776
 
            # we only have an estimate of whats available and need to validate
1777
 
            # that against the revision records.
1778
 
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
1779
 
 
1780
 
InterRepository.register_optimiser(InterWeaveRepo)
1781
 
InterRepository.register_optimiser(InterKnitRepo)
1782
 
 
1783
 
 
1784
 
class RepositoryTestProviderAdapter(object):
1785
 
    """A tool to generate a suite testing multiple repository formats at once.
1786
 
 
1787
 
    This is done by copying the test once for each transport and injecting
1788
 
    the transport_server, transport_readonly_server, and bzrdir_format and
1789
 
    repository_format classes into each copy. Each copy is also given a new id()
1790
 
    to make it easy to identify.
1791
 
    """
1792
 
 
1793
 
    def __init__(self, transport_server, transport_readonly_server, formats):
1794
 
        self._transport_server = transport_server
1795
 
        self._transport_readonly_server = transport_readonly_server
1796
 
        self._formats = formats
1797
 
    
1798
 
    def adapt(self, test):
1799
 
        result = TestSuite()
1800
 
        for repository_format, bzrdir_format in self._formats:
1801
 
            new_test = deepcopy(test)
1802
 
            new_test.transport_server = self._transport_server
1803
 
            new_test.transport_readonly_server = self._transport_readonly_server
1804
 
            new_test.bzrdir_format = bzrdir_format
1805
 
            new_test.repository_format = repository_format
1806
 
            def make_new_test_id():
1807
 
                new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1808
 
                return lambda: new_id
1809
 
            new_test.id = make_new_test_id()
1810
 
            result.addTest(new_test)
1811
 
        return result
1812
 
 
1813
 
 
1814
 
class InterRepositoryTestProviderAdapter(object):
1815
 
    """A tool to generate a suite testing multiple inter repository formats.
1816
 
 
1817
 
    This is done by copying the test once for each interrepo provider and injecting
1818
 
    the transport_server, transport_readonly_server, repository_format and 
1819
 
    repository_to_format classes into each copy.
1820
 
    Each copy is also given a new id() to make it easy to identify.
1821
 
    """
1822
 
 
1823
 
    def __init__(self, transport_server, transport_readonly_server, formats):
1824
 
        self._transport_server = transport_server
1825
 
        self._transport_readonly_server = transport_readonly_server
1826
 
        self._formats = formats
1827
 
    
1828
 
    def adapt(self, test):
1829
 
        result = TestSuite()
1830
 
        for interrepo_class, repository_format, repository_format_to in self._formats:
1831
 
            new_test = deepcopy(test)
1832
 
            new_test.transport_server = self._transport_server
1833
 
            new_test.transport_readonly_server = self._transport_readonly_server
1834
 
            new_test.interrepo_class = interrepo_class
1835
 
            new_test.repository_format = repository_format
1836
 
            new_test.repository_format_to = repository_format_to
1837
 
            def make_new_test_id():
1838
 
                new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1839
 
                return lambda: new_id
1840
 
            new_test.id = make_new_test_id()
1841
 
            result.addTest(new_test)
1842
 
        return result
1843
 
 
1844
 
    @staticmethod
1845
 
    def default_test_list():
1846
 
        """Generate the default list of interrepo permutations to test."""
1847
 
        result = []
1848
 
        # test the default InterRepository between format 6 and the current 
1849
 
        # default format.
1850
 
        # XXX: robertc 20060220 reinstate this when there are two supported
1851
 
        # formats which do not have an optimal code path between them.
1852
 
        result.append((InterRepository,
1853
 
                       RepositoryFormat6(),
1854
 
                       RepositoryFormatKnit1()))
1855
 
        for optimiser in InterRepository._optimisers:
1856
 
            result.append((optimiser,
1857
 
                           optimiser._matching_repo_format,
1858
 
                           optimiser._matching_repo_format
1859
 
                           ))
1860
 
        # if there are specific combinations we want to use, we can add them 
1861
 
        # here.
1862
 
        return result
1863
 
 
1864
 
 
1865
 
class CopyConverter(object):
1866
 
    """A repository conversion tool which just performs a copy of the content.
1867
 
    
1868
 
    This is slow but quite reliable.
1869
 
    """
1870
 
 
1871
 
    def __init__(self, target_format):
1872
 
        """Create a CopyConverter.
1873
 
 
1874
 
        :param target_format: The format the resulting repository should be.
1875
 
        """
1876
 
        self.target_format = target_format
1877
 
        
1878
 
    def convert(self, repo, pb):
1879
 
        """Perform the conversion of to_convert, giving feedback via pb.
1880
 
 
1881
 
        :param to_convert: The disk object to convert.
1882
 
        :param pb: a progress bar to use for progress information.
1883
 
        """
1884
 
        self.pb = pb
1885
 
        self.count = 0
1886
 
        self.total = 4
1887
 
        # this is only useful with metadir layouts - separated repo content.
1888
 
        # trigger an assertion if not such
1889
 
        repo._format.get_format_string()
1890
 
        self.repo_dir = repo.bzrdir
1891
 
        self.step('Moving repository to repository.backup')
1892
 
        self.repo_dir.transport.move('repository', 'repository.backup')
1893
 
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
1894
 
        self.source_repo = repo._format.open(self.repo_dir,
1895
 
            _found=True,
1896
 
            _override_transport=backup_transport)
1897
 
        self.step('Creating new repository')
1898
 
        converted = self.target_format.initialize(self.repo_dir,
1899
 
                                                  self.source_repo.is_shared())
1900
 
        converted.lock_write()
1901
 
        try:
1902
 
            self.step('Copying content into repository.')
1903
 
            self.source_repo.copy_content_into(converted)
1904
 
        finally:
1905
 
            converted.unlock()
1906
 
        self.step('Deleting old repository content.')
1907
 
        self.repo_dir.transport.delete_tree('repository.backup')
1908
 
        self.pb.note('repository converted')
1909
 
 
1910
 
    def step(self, message):
1911
 
        """Update the pb by a step."""
1912
 
        self.count +=1
1913
 
        self.pb.update(message, self.count, self.total)
1914
 
 
1915
 
 
1916
 
class CommitBuilder(object):
1917
 
    """Provides an interface to build up a commit.
1918
 
 
1919
 
    This allows describing a tree to be committed without needing to 
1920
 
    know the internals of the format of the repository.
1921
 
    """
1922
 
    def __init__(self, repository, parents, config, timestamp=None, 
1923
 
                 timezone=None, committer=None, revprops=None, 
1924
 
                 revision_id=None):
1925
 
        """Initiate a CommitBuilder.
1926
 
 
1927
 
        :param repository: Repository to commit to.
1928
 
        :param parents: Revision ids of the parents of the new revision.
1929
 
        :param config: Configuration to use.
1930
 
        :param timestamp: Optional timestamp recorded for commit.
1931
 
        :param timezone: Optional timezone for timestamp.
1932
 
        :param committer: Optional committer to set for commit.
1933
 
        :param revprops: Optional dictionary of revision properties.
1934
 
        :param revision_id: Optional revision id.
1935
 
        """
1936
 
        self._config = config
1937
 
 
1938
 
        if committer is None:
1939
 
            self._committer = self._config.username()
1940
 
        else:
1941
 
            assert isinstance(committer, basestring), type(committer)
1942
 
            self._committer = committer
1943
 
 
1944
 
        self.new_inventory = Inventory()
1945
 
        self._new_revision_id = revision_id
1946
 
        self.parents = parents
1947
 
        self.repository = repository
1948
 
 
1949
 
        self._revprops = {}
1950
 
        if revprops is not None:
1951
 
            self._revprops.update(revprops)
1952
 
 
1953
 
        if timestamp is None:
1954
 
            self._timestamp = time.time()
1955
 
        else:
1956
 
            self._timestamp = long(timestamp)
1957
 
 
1958
 
        if timezone is None:
1959
 
            self._timezone = local_time_offset()
1960
 
        else:
1961
 
            self._timezone = int(timezone)
1962
 
 
1963
 
        self._generate_revision_if_needed()
1964
 
 
1965
 
    def commit(self, message):
1966
 
        """Make the actual commit.
1967
 
 
1968
 
        :return: The revision id of the recorded revision.
1969
 
        """
1970
 
        rev = Revision(timestamp=self._timestamp,
1971
 
                       timezone=self._timezone,
1972
 
                       committer=self._committer,
1973
 
                       message=message,
1974
 
                       inventory_sha1=self.inv_sha1,
1975
 
                       revision_id=self._new_revision_id,
1976
 
                       properties=self._revprops)
1977
 
        rev.parent_ids = self.parents
1978
 
        self.repository.add_revision(self._new_revision_id, rev, 
1979
 
            self.new_inventory, self._config)
1980
 
        return self._new_revision_id
1981
 
 
1982
 
    def finish_inventory(self):
1983
 
        """Tell the builder that the inventory is finished."""
1984
 
        self.new_inventory.revision_id = self._new_revision_id
1985
 
        self.inv_sha1 = self.repository.add_inventory(
1986
 
            self._new_revision_id,
1987
 
            self.new_inventory,
1988
 
            self.parents
1989
 
            )
1990
 
 
1991
 
    def _gen_revision_id(self):
1992
 
        """Return new revision-id."""
1993
 
        s = '%s-%s-' % (self._config.user_email(), 
1994
 
                        compact_date(self._timestamp))
1995
 
        s += hexlify(rand_bytes(8))
1996
 
        return s
1997
 
 
1998
 
    def _generate_revision_if_needed(self):
1999
 
        """Create a revision id if None was supplied.
2000
 
        
2001
 
        If the repository can not support user-specified revision ids
2002
 
        they should override this function and raise UnsupportedOperation
2003
 
        if _new_revision_id is not None.
2004
 
 
2005
 
        :raises: UnsupportedOperation
2006
 
        """
2007
 
        if self._new_revision_id is None:
2008
 
            self._new_revision_id = self._gen_revision_id()
2009
 
 
2010
 
    def record_entry_contents(self, ie, parent_invs, path, tree):
2011
 
        """Record the content of ie from tree into the commit if needed.
2012
 
 
2013
 
        :param ie: An inventory entry present in the commit.
2014
 
        :param parent_invs: The inventories of the parent revisions of the
2015
 
            commit.
2016
 
        :param path: The path the entry is at in the tree.
2017
 
        :param tree: The tree which contains this entry and should be used to 
2018
 
        obtain content.
2019
 
        """
2020
 
        self.new_inventory.add(ie)
2021
 
 
2022
 
        # ie.revision is always None if the InventoryEntry is considered
2023
 
        # for committing. ie.snapshot will record the correct revision 
2024
 
        # which may be the sole parent if it is untouched.
2025
 
        if ie.revision is not None:
2026
 
            return
2027
 
        previous_entries = ie.find_previous_heads(
2028
 
            parent_invs,
2029
 
            self.repository.weave_store,
2030
 
            self.repository.get_transaction())
2031
 
        # we are creating a new revision for ie in the history store
2032
 
        # and inventory.
2033
 
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2034
 
 
2035
 
    def modified_directory(self, file_id, file_parents):
2036
 
        """Record the presence of a symbolic link.
2037
 
 
2038
 
        :param file_id: The file_id of the link to record.
2039
 
        :param file_parents: The per-file parent revision ids.
2040
 
        """
2041
 
        self._add_text_to_weave(file_id, [], file_parents.keys())
2042
 
    
2043
 
    def modified_file_text(self, file_id, file_parents,
2044
 
                           get_content_byte_lines, text_sha1=None,
2045
 
                           text_size=None):
2046
 
        """Record the text of file file_id
2047
 
 
2048
 
        :param file_id: The file_id of the file to record the text of.
2049
 
        :param file_parents: The per-file parent revision ids.
2050
 
        :param get_content_byte_lines: A callable which will return the byte
2051
 
            lines for the file.
2052
 
        :param text_sha1: Optional SHA1 of the file contents.
2053
 
        :param text_size: Optional size of the file contents.
2054
 
        """
2055
 
        mutter('storing text of file {%s} in revision {%s} into %r',
2056
 
               file_id, self._new_revision_id, self.repository.weave_store)
2057
 
        # special case to avoid diffing on renames or 
2058
 
        # reparenting
2059
 
        if (len(file_parents) == 1
2060
 
            and text_sha1 == file_parents.values()[0].text_sha1
2061
 
            and text_size == file_parents.values()[0].text_size):
2062
 
            previous_ie = file_parents.values()[0]
2063
 
            versionedfile = self.repository.weave_store.get_weave(file_id, 
2064
 
                self.repository.get_transaction())
2065
 
            versionedfile.clone_text(self._new_revision_id, 
2066
 
                previous_ie.revision, file_parents.keys())
2067
 
            return text_sha1, text_size
2068
 
        else:
2069
 
            new_lines = get_content_byte_lines()
2070
 
            # TODO: Rather than invoking sha_strings here, _add_text_to_weave
2071
 
            # should return the SHA1 and size
2072
 
            self._add_text_to_weave(file_id, new_lines, file_parents.keys())
2073
 
            return bzrlib.osutils.sha_strings(new_lines), \
2074
 
                sum(map(len, new_lines))
2075
 
 
2076
 
    def modified_link(self, file_id, file_parents, link_target):
2077
 
        """Record the presence of a symbolic link.
2078
 
 
2079
 
        :param file_id: The file_id of the link to record.
2080
 
        :param file_parents: The per-file parent revision ids.
2081
 
        :param link_target: Target location of this link.
2082
 
        """
2083
 
        self._add_text_to_weave(file_id, [], file_parents.keys())
2084
 
 
2085
 
    def _add_text_to_weave(self, file_id, new_lines, parents):
2086
 
        versionedfile = self.repository.weave_store.get_weave_or_empty(
2087
 
            file_id, self.repository.get_transaction())
2088
 
        versionedfile.add_lines(self._new_revision_id, parents, new_lines)
2089
 
        versionedfile.clear_cache()
2090
 
 
2091
 
 
2092
 
# Copied from xml.sax.saxutils
2093
 
def _unescape_xml(data):
2094
 
    """Unescape &amp;, &lt;, and &gt; in a string of data.
2095
 
    """
2096
 
    data = data.replace("&lt;", "<")
2097
 
    data = data.replace("&gt;", ">")
2098
 
    # must do ampersand last
2099
 
    return data.replace("&amp;", "&")