/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

Merge from bzr.dev.

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