/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Aaron Bentley
  • Date: 2006-06-11 21:46:37 UTC
  • mto: This revision was merged to the branch mainline in revision 1776.
  • Revision ID: aaron.bentley@utoronto.ca-20060611214637-3a88d0f47f40f77e
Add log benchmark

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