/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Martin Pool
  • Date: 2006-06-20 04:45:30 UTC
  • mto: This revision was merged to the branch mainline in revision 1798.
  • Revision ID: mbp@sourcefrog.net-20060620044530-6e8a6f4b6f3bc525
Cleanup of imports; undeprecate all_revision_ids()

Thanks to John for review comments.

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