/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: Robert Collins
  • Date: 2006-07-24 04:40:06 UTC
  • mto: (1852.7.2 split-tree-source)
  • mto: This revision was merged to the branch mainline in revision 1890.
  • Revision ID: robertc@robertcollins.net-20060724044006-faa99aee0dff9ae9
Finish updating iter_entries change to make all tests pass.

Show diffs side-by-side

added added

removed removed

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