~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2006-10-02 00:43:10 UTC
  • mfrom: (2057.1.1 bzr.dev)
  • Revision ID: pqm@pqm.ubuntu.com-20061002004310-6e09ddd7fd28f71c
Merge in 0.11 NEWS entry.

Show diffs side-by-side

added added

removed removed

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