/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: John Arbash Meinel
  • Date: 2006-09-12 22:12:30 UTC
  • mto: This revision was merged to the branch mainline in revision 2071.
  • Revision ID: john@arbash-meinel.com-20060912221230-d3980a26890a32e3
lazy_import bundle and bundle.commands

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