/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: Aaron Bentley
  • Date: 2006-08-08 16:35:47 UTC
  • mto: (1910.2.43 format-bumps)
  • mto: This revision was merged to the branch mainline in revision 1922.
  • Revision ID: abentley@panoramicfeedback.com-20060808163547-aef6d866d4b94da7
All tests pass

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