/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: John Arbash Meinel
  • Date: 2007-02-10 17:02:18 UTC
  • mto: This revision was merged to the branch mainline in revision 2294.
  • Revision ID: john@arbash-meinel.com-20070210170218-6qxxiywltp0uawzw
Add some tests that generate_ids.get_revision_id() generates ascii revision ids

Show diffs side-by-side

added added

removed removed

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