~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Alexander Belchenko
  • Date: 2006-07-30 16:43:12 UTC
  • mto: (1711.2.111 jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1906.
  • Revision ID: bialix@ukr.net-20060730164312-b025fd3ff0cee59e
rename  gpl.txt => COPYING.txt

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
 
17
from binascii import hexlify
 
18
from copy import deepcopy
17
19
from cStringIO import StringIO
18
 
 
19
 
from bzrlib.lazy_import import lazy_import
20
 
lazy_import(globals(), """
21
20
import re
22
21
import time
23
 
import unittest
 
22
from unittest import TestSuite
24
23
 
25
 
from bzrlib import (
26
 
    bzrdir,
27
 
    check,
28
 
    errors,
29
 
    generate_ids,
30
 
    gpg,
31
 
    graph,
32
 
    lazy_regex,
33
 
    lockable_files,
34
 
    lockdir,
35
 
    osutils,
36
 
    registry,
37
 
    remote,
38
 
    revision as _mod_revision,
39
 
    symbol_versioning,
40
 
    transactions,
41
 
    ui,
42
 
    )
 
24
from bzrlib import bzrdir, check, delta, gpg, errors, xml5, ui, transactions, osutils
 
25
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
26
from bzrlib.errors import InvalidRevisionId
 
27
from bzrlib.graph import Graph
 
28
from bzrlib.inter import InterObject
 
29
from bzrlib.inventory import Inventory
 
30
from bzrlib.knit import KnitVersionedFile, KnitPlainFactory
 
31
from bzrlib.lockable_files import LockableFiles, TransportLock
 
32
from bzrlib.lockdir import LockDir
 
33
from bzrlib.osutils import (safe_unicode, rand_bytes, compact_date, 
 
34
                            local_time_offset)
 
35
from bzrlib.revision import NULL_REVISION, Revision
43
36
from bzrlib.revisiontree import RevisionTree
44
 
from bzrlib.store.versioned import VersionedFileStore
 
37
from bzrlib.store.versioned import VersionedFileStore, WeaveStore
45
38
from bzrlib.store.text import TextStore
 
39
from bzrlib.symbol_versioning import (deprecated_method,
 
40
        zero_nine, 
 
41
        )
46
42
from bzrlib.testament import Testament
47
 
 
48
 
""")
49
 
 
50
 
from bzrlib.decorators import needs_read_lock, needs_write_lock
51
 
from bzrlib.inter import InterObject
52
 
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
53
 
from bzrlib.symbol_versioning import (
54
 
        deprecated_method,
55
 
        zero_nine,
56
 
        )
57
 
from bzrlib.trace import mutter, note, warning
58
 
 
59
 
 
60
 
# Old formats display a warning, but only once
61
 
_deprecation_warning_done = False
62
 
 
63
 
 
64
 
######################################################################
65
 
# Repositories
 
43
from bzrlib.trace import mutter, note
 
44
from bzrlib.tsort import topo_sort
 
45
from bzrlib.weave import WeaveFile
 
46
 
66
47
 
67
48
class Repository(object):
68
49
    """Repository holding history for one or more branches.
76
57
    remote) disk.
77
58
    """
78
59
 
79
 
    _file_ids_altered_regex = lazy_regex.lazy_compile(
80
 
        r'file_id="(?P<file_id>[^"]+)"'
81
 
        r'.*revision="(?P<revision_id>[^"]+)"'
82
 
        )
83
 
 
84
60
    @needs_write_lock
85
 
    def add_inventory(self, revision_id, inv, parents):
86
 
        """Add the inventory inv to the repository as revision_id.
 
61
    def add_inventory(self, revid, inv, parents):
 
62
        """Add the inventory inv to the repository as revid.
87
63
        
88
 
        :param parents: The revision ids of the parents that revision_id
 
64
        :param parents: The revision ids of the parents that revid
89
65
                        is known to have and are in the repository already.
90
66
 
91
67
        returns the sha1 of the serialized inventory.
92
68
        """
93
 
        revision_id = osutils.safe_revision_id(revision_id)
94
 
        _mod_revision.check_not_reserved_id(revision_id)
95
 
        assert inv.revision_id is None or inv.revision_id == revision_id, \
 
69
        assert inv.revision_id is None or inv.revision_id == revid, \
96
70
            "Mismatch between inventory revision" \
97
 
            " id and insertion revid (%r, %r)" % (inv.revision_id, revision_id)
98
 
        assert inv.root is not None
99
 
        inv_text = self.serialise_inventory(inv)
 
71
            " id and insertion revid (%r, %r)" % (inv.revision_id, revid)
 
72
        inv_text = xml5.serializer_v5.write_inventory_to_string(inv)
100
73
        inv_sha1 = osutils.sha_string(inv_text)
101
74
        inv_vf = self.control_weaves.get_weave('inventory',
102
75
                                               self.get_transaction())
103
 
        self._inventory_add_lines(inv_vf, revision_id, parents,
104
 
                                  osutils.split_lines(inv_text))
 
76
        self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
105
77
        return inv_sha1
106
78
 
107
 
    def _inventory_add_lines(self, inv_vf, revision_id, parents, lines):
 
79
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
108
80
        final_parents = []
109
81
        for parent in parents:
110
82
            if parent in inv_vf:
111
83
                final_parents.append(parent)
112
84
 
113
 
        inv_vf.add_lines(revision_id, final_parents, lines)
 
85
        inv_vf.add_lines(revid, final_parents, lines)
114
86
 
115
87
    @needs_write_lock
116
 
    def add_revision(self, revision_id, rev, inv=None, config=None):
117
 
        """Add rev to the revision store as revision_id.
 
88
    def add_revision(self, rev_id, rev, inv=None, config=None):
 
89
        """Add rev to the revision store as rev_id.
118
90
 
119
 
        :param revision_id: the revision id to use.
 
91
        :param rev_id: the revision id to use.
120
92
        :param rev: The revision object.
121
93
        :param inv: The inventory for the revision. if None, it will be looked
122
94
                    up in the inventory storer
124
96
                       If supplied its signature_needed method will be used
125
97
                       to determine if a signature should be made.
126
98
        """
127
 
        revision_id = osutils.safe_revision_id(revision_id)
128
 
        # TODO: jam 20070210 Shouldn't we check rev.revision_id and
129
 
        #       rev.parent_ids?
130
 
        _mod_revision.check_not_reserved_id(revision_id)
131
99
        if config is not None and config.signature_needed():
132
100
            if inv is None:
133
 
                inv = self.get_inventory(revision_id)
 
101
                inv = self.get_inventory(rev_id)
134
102
            plaintext = Testament(rev, inv).as_short_text()
135
103
            self.store_revision_signature(
136
 
                gpg.GPGStrategy(config), plaintext, revision_id)
137
 
        if not revision_id in self.get_inventory_weave():
 
104
                gpg.GPGStrategy(config), plaintext, rev_id)
 
105
        if not rev_id in self.get_inventory_weave():
138
106
            if inv is None:
139
 
                raise errors.WeaveRevisionNotPresent(revision_id,
 
107
                raise errors.WeaveRevisionNotPresent(rev_id,
140
108
                                                     self.get_inventory_weave())
141
109
            else:
142
110
                # yes, this is not suitable for adding with ghosts.
143
 
                self.add_inventory(revision_id, inv, rev.parent_ids)
 
111
                self.add_inventory(rev_id, inv, rev.parent_ids)
144
112
        self._revision_store.add_revision(rev, self.get_transaction())
145
113
 
146
114
    @needs_read_lock
168
136
        if self._revision_store.text_store.listable():
169
137
            return self._revision_store.all_revision_ids(self.get_transaction())
170
138
        result = self._all_possible_ids()
171
 
        # TODO: jam 20070210 Ensure that _all_possible_ids returns non-unicode
172
 
        #       ids. (It should, since _revision_store's API should change to
173
 
        #       return utf8 revision_ids)
174
139
        return self._eliminate_revisions_not_present(result)
175
140
 
176
141
    def break_lock(self):
223
188
        self.control_weaves = control_store
224
189
        # TODO: make sure to construct the right store classes, etc, depending
225
190
        # on whether escaping is required.
226
 
        self._warn_if_deprecated()
227
191
 
228
192
    def __repr__(self):
229
193
        return '%s(%r)' % (self.__class__.__name__, 
232
196
    def is_locked(self):
233
197
        return self.control_files.is_locked()
234
198
 
235
 
    def lock_write(self, token=None):
236
 
        """Lock this repository for writing.
237
 
        
238
 
        :param token: if this is already locked, then lock_write will fail
239
 
            unless the token matches the existing lock.
240
 
        :returns: a token if this instance supports tokens, otherwise None.
241
 
        :raises TokenLockingNotSupported: when a token is given but this
242
 
            instance doesn't support using token locks.
243
 
        :raises MismatchedToken: if the specified token doesn't match the token
244
 
            of the existing lock.
245
 
 
246
 
        A token should be passed in if you know that you have locked the object
247
 
        some other way, and need to synchronise this object's state with that
248
 
        fact.
249
 
 
250
 
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
251
 
        """
252
 
        return self.control_files.lock_write(token=token)
 
199
    def lock_write(self):
 
200
        self.control_files.lock_write()
253
201
 
254
202
    def lock_read(self):
255
203
        self.control_files.lock_read()
257
205
    def get_physical_lock_status(self):
258
206
        return self.control_files.get_physical_lock_status()
259
207
 
260
 
    def leave_lock_in_place(self):
261
 
        """Tell this repository not to release the physical lock when this
262
 
        object is unlocked.
263
 
        
264
 
        If lock_write doesn't return a token, then this method is not supported.
265
 
        """
266
 
        self.control_files.leave_in_place()
267
 
 
268
 
    def dont_leave_lock_in_place(self):
269
 
        """Tell this repository to release the physical lock when this
270
 
        object is unlocked, even if it didn't originally acquire it.
271
 
 
272
 
        If lock_write doesn't return a token, then this method is not supported.
273
 
        """
274
 
        self.control_files.dont_leave_in_place()
275
 
 
276
 
    @needs_read_lock
277
 
    def gather_stats(self, revid=None, committers=None):
278
 
        """Gather statistics from a revision id.
279
 
 
280
 
        :param revid: The revision id to gather statistics from, if None, then
281
 
            no revision specific statistics are gathered.
282
 
        :param committers: Optional parameter controlling whether to grab
283
 
            a count of committers from the revision specific statistics.
284
 
        :return: A dictionary of statistics. Currently this contains:
285
 
            committers: The number of committers if requested.
286
 
            firstrev: A tuple with timestamp, timezone for the penultimate left
287
 
                most ancestor of revid, if revid is not the NULL_REVISION.
288
 
            latestrev: A tuple with timestamp, timezone for revid, if revid is
289
 
                not the NULL_REVISION.
290
 
            revisions: The total revision count in the repository.
291
 
            size: An estimate disk size of the repository in bytes.
292
 
        """
293
 
        result = {}
294
 
        if revid and committers:
295
 
            result['committers'] = 0
296
 
        if revid and revid != _mod_revision.NULL_REVISION:
297
 
            if committers:
298
 
                all_committers = set()
299
 
            revisions = self.get_ancestry(revid)
300
 
            # pop the leading None
301
 
            revisions.pop(0)
302
 
            first_revision = None
303
 
            if not committers:
304
 
                # ignore the revisions in the middle - just grab first and last
305
 
                revisions = revisions[0], revisions[-1]
306
 
            for revision in self.get_revisions(revisions):
307
 
                if not first_revision:
308
 
                    first_revision = revision
309
 
                if committers:
310
 
                    all_committers.add(revision.committer)
311
 
            last_revision = revision
312
 
            if committers:
313
 
                result['committers'] = len(all_committers)
314
 
            result['firstrev'] = (first_revision.timestamp,
315
 
                first_revision.timezone)
316
 
            result['latestrev'] = (last_revision.timestamp,
317
 
                last_revision.timezone)
318
 
 
319
 
        # now gather global repository information
320
 
        if self.bzrdir.root_transport.listable():
321
 
            c, t = self._revision_store.total_size(self.get_transaction())
322
 
            result['revisions'] = c
323
 
            result['size'] = t
324
 
        return result
325
 
 
326
208
    @needs_read_lock
327
209
    def missing_revision_ids(self, other, revision_id=None):
328
210
        """Return the revision ids that other has that this does not.
331
213
 
332
214
        revision_id: only return revision ids included by revision_id.
333
215
        """
334
 
        revision_id = osutils.safe_revision_id(revision_id)
335
216
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
336
217
 
337
218
    @staticmethod
344
225
        control = bzrdir.BzrDir.open(base)
345
226
        return control.open_repository()
346
227
 
347
 
    def copy_content_into(self, destination, revision_id=None):
 
228
    def copy_content_into(self, destination, revision_id=None, basis=None):
348
229
        """Make a complete copy of the content in self into destination.
349
230
        
350
231
        This is a destructive operation! Do not use it on existing 
351
232
        repositories.
352
233
        """
353
 
        revision_id = osutils.safe_revision_id(revision_id)
354
 
        return InterRepository.get(self, destination).copy_content(revision_id)
 
234
        return InterRepository.get(self, destination).copy_content(revision_id, basis)
355
235
 
356
236
    def fetch(self, source, revision_id=None, pb=None):
357
237
        """Fetch the content required to construct revision_id from source.
358
238
 
359
239
        If revision_id is None all content is copied.
360
240
        """
361
 
        revision_id = osutils.safe_revision_id(revision_id)
362
 
        inter = InterRepository.get(source, self)
363
 
        try:
364
 
            return inter.fetch(revision_id=revision_id, pb=pb)
365
 
        except NotImplementedError:
366
 
            raise errors.IncompatibleRepositories(source, self)
 
241
        return InterRepository.get(source, self).fetch(revision_id=revision_id,
 
242
                                                       pb=pb)
367
243
 
368
244
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
369
245
                           timezone=None, committer=None, revprops=None, 
379
255
        :param revprops: Optional dictionary of revision properties.
380
256
        :param revision_id: Optional revision id.
381
257
        """
382
 
        revision_id = osutils.safe_revision_id(revision_id)
383
 
        return _CommitBuilder(self, parents, config, timestamp, timezone,
384
 
                              committer, revprops, revision_id)
 
258
        return CommitBuilder(self, parents, config, timestamp, timezone,
 
259
                             committer, revprops, revision_id)
385
260
 
386
261
    def unlock(self):
387
262
        self.control_files.unlock()
388
263
 
389
264
    @needs_read_lock
390
 
    def clone(self, a_bzrdir, revision_id=None):
 
265
    def clone(self, a_bzrdir, revision_id=None, basis=None):
391
266
        """Clone this repository into a_bzrdir using the current format.
392
267
 
393
268
        Currently no check is made that the format of this repository and
394
269
        the bzrdir format are compatible. FIXME RBC 20060201.
395
 
 
396
 
        :return: The newly created destination repository.
397
 
        """
398
 
        # TODO: deprecate after 0.16; cloning this with all its settings is
399
 
        # probably not very useful -- mbp 20070423
400
 
        dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
401
 
        self.copy_content_into(dest_repo, revision_id)
402
 
        return dest_repo
403
 
 
404
 
    @needs_read_lock
405
 
    def sprout(self, to_bzrdir, revision_id=None):
406
 
        """Create a descendent repository for new development.
407
 
 
408
 
        Unlike clone, this does not copy the settings of the repository.
409
 
        """
410
 
        dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
411
 
        dest_repo.fetch(self, revision_id=revision_id)
412
 
        return dest_repo
413
 
 
414
 
    def _create_sprouting_repo(self, a_bzrdir, shared):
 
270
        """
415
271
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
416
272
            # use target default format.
417
 
            dest_repo = a_bzrdir.create_repository()
 
273
            result = a_bzrdir.create_repository()
 
274
        # FIXME RBC 20060209 split out the repository type to avoid this check ?
 
275
        elif isinstance(a_bzrdir._format,
 
276
                      (bzrdir.BzrDirFormat4,
 
277
                       bzrdir.BzrDirFormat5,
 
278
                       bzrdir.BzrDirFormat6)):
 
279
            result = a_bzrdir.open_repository()
418
280
        else:
419
 
            # Most control formats need the repository to be specifically
420
 
            # created, but on some old all-in-one formats it's not needed
421
 
            try:
422
 
                dest_repo = self._format.initialize(a_bzrdir, shared=shared)
423
 
            except errors.UninitializableFormat:
424
 
                dest_repo = a_bzrdir.open_repository()
425
 
        return dest_repo
 
281
            result = self._format.initialize(a_bzrdir, shared=self.is_shared())
 
282
        self.copy_content_into(result, revision_id, basis)
 
283
        return result
426
284
 
427
285
    @needs_read_lock
428
286
    def has_revision(self, revision_id):
429
287
        """True if this repository has a copy of the revision."""
430
 
        revision_id = osutils.safe_revision_id(revision_id)
431
288
        return self._revision_store.has_revision_id(revision_id,
432
289
                                                    self.get_transaction())
433
290
 
441
298
        or testing the revision graph.
442
299
        """
443
300
        if not revision_id or not isinstance(revision_id, basestring):
444
 
            raise errors.InvalidRevisionId(revision_id=revision_id,
445
 
                                           branch=self)
446
 
        return self.get_revisions([revision_id])[0]
447
 
 
 
301
            raise InvalidRevisionId(revision_id=revision_id, branch=self)
 
302
        return self._revision_store.get_revisions([revision_id],
 
303
                                                  self.get_transaction())[0]
448
304
    @needs_read_lock
449
305
    def get_revisions(self, revision_ids):
450
 
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
451
 
        revs = self._revision_store.get_revisions(revision_ids,
 
306
        return self._revision_store.get_revisions(revision_ids,
452
307
                                                  self.get_transaction())
453
 
        for rev in revs:
454
 
            assert not isinstance(rev.revision_id, unicode)
455
 
            for parent_id in rev.parent_ids:
456
 
                assert not isinstance(parent_id, unicode)
457
 
        return revs
458
308
 
459
309
    @needs_read_lock
460
310
    def get_revision_xml(self, revision_id):
461
 
        # TODO: jam 20070210 This shouldn't be necessary since get_revision
462
 
        #       would have already do it.
463
 
        # TODO: jam 20070210 Just use _serializer.write_revision_to_string()
464
 
        revision_id = osutils.safe_revision_id(revision_id)
465
 
        rev = self.get_revision(revision_id)
 
311
        rev = self.get_revision(revision_id) 
466
312
        rev_tmp = StringIO()
467
313
        # the current serializer..
468
314
        self._revision_store._serializer.write_revision(rev, rev_tmp)
472
318
    @needs_read_lock
473
319
    def get_revision(self, revision_id):
474
320
        """Return the Revision object for a named revision"""
475
 
        # TODO: jam 20070210 get_revision_reconcile should do this for us
476
 
        revision_id = osutils.safe_revision_id(revision_id)
477
321
        r = self.get_revision_reconcile(revision_id)
478
322
        # weave corruption can lead to absent revision markers that should be
479
323
        # present.
535
379
 
536
380
    @needs_write_lock
537
381
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
538
 
        revision_id = osutils.safe_revision_id(revision_id)
539
382
        signature = gpg_strategy.sign(plaintext)
540
383
        self._revision_store.add_revision_signature_text(revision_id,
541
384
                                                         signature,
549
392
        revision_ids. Each altered file-ids has the exact revision_ids that
550
393
        altered it listed explicitly.
551
394
        """
552
 
        assert self._serializer.support_altered_by_hack, \
 
395
        assert isinstance(self._format, (RepositoryFormat5,
 
396
                                         RepositoryFormat6,
 
397
                                         RepositoryFormat7,
 
398
                                         RepositoryFormatKnit1)), \
553
399
            ("fileids_altered_by_revision_ids only supported for branches " 
554
400
             "which store inventory as unnested xml, not on %r" % self)
555
 
        selected_revision_ids = set(osutils.safe_revision_id(r)
556
 
                                    for r in revision_ids)
 
401
        selected_revision_ids = set(revision_ids)
557
402
        w = self.get_inventory_weave()
558
403
        result = {}
559
404
 
565
410
        # revisions. We don't need to see all lines in the inventory because
566
411
        # only those added in an inventory in rev X can contain a revision=X
567
412
        # line.
568
 
        unescape_revid_cache = {}
569
 
        unescape_fileid_cache = {}
570
 
 
571
 
        # jam 20061218 In a big fetch, this handles hundreds of thousands
572
 
        # of lines, so it has had a lot of inlining and optimizing done.
573
 
        # Sorry that it is a little bit messy.
574
 
        # Move several functions to be local variables, since this is a long
575
 
        # running loop.
576
 
        search = self._file_ids_altered_regex.search
577
 
        unescape = _unescape_xml
578
 
        setdefault = result.setdefault
579
 
        pb = ui.ui_factory.nested_progress_bar()
580
 
        try:
581
 
            for line in w.iter_lines_added_or_present_in_versions(
582
 
                                        selected_revision_ids, pb=pb):
583
 
                match = search(line)
584
 
                if match is None:
585
 
                    continue
586
 
                # One call to match.group() returning multiple items is quite a
587
 
                # bit faster than 2 calls to match.group() each returning 1
588
 
                file_id, revision_id = match.group('file_id', 'revision_id')
589
 
 
590
 
                # Inlining the cache lookups helps a lot when you make 170,000
591
 
                # lines and 350k ids, versus 8.4 unique ids.
592
 
                # Using a cache helps in 2 ways:
593
 
                #   1) Avoids unnecessary decoding calls
594
 
                #   2) Re-uses cached strings, which helps in future set and
595
 
                #      equality checks.
596
 
                # (2) is enough that removing encoding entirely along with
597
 
                # the cache (so we are using plain strings) results in no
598
 
                # performance improvement.
599
 
                try:
600
 
                    revision_id = unescape_revid_cache[revision_id]
601
 
                except KeyError:
602
 
                    unescaped = unescape(revision_id)
603
 
                    unescape_revid_cache[revision_id] = unescaped
604
 
                    revision_id = unescaped
605
 
 
606
 
                if revision_id in selected_revision_ids:
607
 
                    try:
608
 
                        file_id = unescape_fileid_cache[file_id]
609
 
                    except KeyError:
610
 
                        unescaped = unescape(file_id)
611
 
                        unescape_fileid_cache[file_id] = unescaped
612
 
                        file_id = unescaped
613
 
                    setdefault(file_id, set()).add(revision_id)
614
 
        finally:
615
 
            pb.finished()
 
413
        for line in w.iter_lines_added_or_present_in_versions(selected_revision_ids):
 
414
            start = line.find('file_id="')+9
 
415
            if start < 9: continue
 
416
            end = line.find('"', start)
 
417
            assert end>= 0
 
418
            file_id = _unescape_xml(line[start:end])
 
419
 
 
420
            start = line.find('revision="')+10
 
421
            if start < 10: continue
 
422
            end = line.find('"', start)
 
423
            assert end>= 0
 
424
            revision_id = _unescape_xml(line[start:end])
 
425
            if revision_id in selected_revision_ids:
 
426
                result.setdefault(file_id, set()).add(revision_id)
616
427
        return result
617
428
 
618
429
    @needs_read_lock
623
434
    @needs_read_lock
624
435
    def get_inventory(self, revision_id):
625
436
        """Get Inventory object by hash."""
626
 
        # TODO: jam 20070210 Technically we don't need to sanitize, since all
627
 
        #       called functions must sanitize.
628
 
        revision_id = osutils.safe_revision_id(revision_id)
629
437
        return self.deserialise_inventory(
630
438
            revision_id, self.get_inventory_xml(revision_id))
631
439
 
635
443
        :param revision_id: The expected revision id of the inventory.
636
444
        :param xml: A serialised inventory.
637
445
        """
638
 
        revision_id = osutils.safe_revision_id(revision_id)
639
 
        result = self._serializer.read_inventory_from_string(xml)
640
 
        result.root.revision = revision_id
641
 
        return result
642
 
 
643
 
    def serialise_inventory(self, inv):
644
 
        return self._serializer.write_inventory_to_string(inv)
 
446
        return xml5.serializer_v5.read_inventory_from_string(xml)
645
447
 
646
448
    @needs_read_lock
647
449
    def get_inventory_xml(self, revision_id):
648
450
        """Get inventory XML as a file object."""
649
 
        revision_id = osutils.safe_revision_id(revision_id)
650
451
        try:
651
 
            assert isinstance(revision_id, str), type(revision_id)
 
452
            assert isinstance(revision_id, basestring), type(revision_id)
652
453
            iw = self.get_inventory_weave()
653
454
            return iw.get_text(revision_id)
654
455
        except IndexError:
658
459
    def get_inventory_sha1(self, revision_id):
659
460
        """Return the sha1 hash of the inventory entry
660
461
        """
661
 
        # TODO: jam 20070210 Shouldn't this be deprecated / removed?
662
 
        revision_id = osutils.safe_revision_id(revision_id)
663
462
        return self.get_revision(revision_id).inventory_sha1
664
463
 
665
464
    @needs_read_lock
672
471
        :return: a dictionary of revision_id->revision_parents_list.
673
472
        """
674
473
        # special case NULL_REVISION
675
 
        if revision_id == _mod_revision.NULL_REVISION:
 
474
        if revision_id == NULL_REVISION:
676
475
            return {}
677
 
        revision_id = osutils.safe_revision_id(revision_id)
678
 
        a_weave = self.get_inventory_weave()
679
 
        all_revisions = self._eliminate_revisions_not_present(
680
 
                                a_weave.versions())
681
 
        entire_graph = dict([(node, a_weave.get_parents(node)) for 
 
476
        weave = self.get_inventory_weave()
 
477
        all_revisions = self._eliminate_revisions_not_present(weave.versions())
 
478
        entire_graph = dict([(node, weave.get_parents(node)) for 
682
479
                             node in all_revisions])
683
480
        if revision_id is None:
684
481
            return entire_graph
703
500
        :param revision_ids: an iterable of revisions to graph or None for all.
704
501
        :return: a Graph object with the graph reachable from revision_ids.
705
502
        """
706
 
        result = graph.Graph()
 
503
        result = Graph()
707
504
        if not revision_ids:
708
505
            pending = set(self.all_revision_ids())
709
506
            required = set([])
710
507
        else:
711
 
            pending = set(osutils.safe_revision_id(r) for r in revision_ids)
 
508
            pending = set(revision_ids)
712
509
            # special case NULL_REVISION
713
 
            if _mod_revision.NULL_REVISION in pending:
714
 
                pending.remove(_mod_revision.NULL_REVISION)
 
510
            if NULL_REVISION in pending:
 
511
                pending.remove(NULL_REVISION)
715
512
            required = set(pending)
716
513
        done = set([])
717
514
        while len(pending):
734
531
            done.add(revision_id)
735
532
        return result
736
533
 
737
 
    def _get_history_vf(self):
738
 
        """Get a versionedfile whose history graph reflects all revisions.
739
 
 
740
 
        For weave repositories, this is the inventory weave.
741
 
        """
742
 
        return self.get_inventory_weave()
743
 
 
744
 
    def iter_reverse_revision_history(self, revision_id):
745
 
        """Iterate backwards through revision ids in the lefthand history
746
 
 
747
 
        :param revision_id: The revision id to start with.  All its lefthand
748
 
            ancestors will be traversed.
749
 
        """
750
 
        revision_id = osutils.safe_revision_id(revision_id)
751
 
        if revision_id in (None, _mod_revision.NULL_REVISION):
752
 
            return
753
 
        next_id = revision_id
754
 
        versionedfile = self._get_history_vf()
755
 
        while True:
756
 
            yield next_id
757
 
            parents = versionedfile.get_parents(next_id)
758
 
            if len(parents) == 0:
759
 
                return
760
 
            else:
761
 
                next_id = parents[0]
762
 
 
763
534
    @needs_read_lock
764
535
    def get_revision_inventory(self, revision_id):
765
536
        """Return inventory of a past revision."""
788
559
        reconciler = RepoReconciler(self, thorough=thorough)
789
560
        reconciler.reconcile()
790
561
        return reconciler
791
 
 
 
562
    
792
563
    @needs_read_lock
793
564
    def revision_tree(self, revision_id):
794
565
        """Return Tree for a revision on this branch.
797
568
        """
798
569
        # TODO: refactor this to use an existing revision object
799
570
        # so we don't need to read it in twice.
800
 
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
801
 
            return RevisionTree(self, Inventory(root_id=None), 
802
 
                                _mod_revision.NULL_REVISION)
 
571
        if revision_id is None or revision_id == NULL_REVISION:
 
572
            return RevisionTree(self, Inventory(), NULL_REVISION)
803
573
        else:
804
 
            revision_id = osutils.safe_revision_id(revision_id)
805
574
            inv = self.get_revision_inventory(revision_id)
806
575
            return RevisionTree(self, inv, revision_id)
807
576
 
811
580
 
812
581
        `revision_id` may not be None or 'null:'"""
813
582
        assert None not in revision_ids
814
 
        assert _mod_revision.NULL_REVISION not in revision_ids
 
583
        assert NULL_REVISION not in revision_ids
815
584
        texts = self.get_inventory_weave().get_texts(revision_ids)
816
585
        for text, revision_id in zip(texts, revision_ids):
817
586
            inv = self.deserialise_inventory(revision_id, text)
829
598
        """
830
599
        if revision_id is None:
831
600
            return [None]
832
 
        revision_id = osutils.safe_revision_id(revision_id)
833
601
        if not self.has_revision(revision_id):
834
602
            raise errors.NoSuchRevision(self, revision_id)
835
603
        w = self.get_inventory_weave()
844
612
        - it writes to stdout, it assumes that that is valid etc. Fix
845
613
        by creating a new more flexible convenience function.
846
614
        """
847
 
        revision_id = osutils.safe_revision_id(revision_id)
848
615
        tree = self.revision_tree(revision_id)
849
616
        # use inventory as it was in that revision
850
617
        file_id = tree.inventory.path2id(file)
858
625
    def get_transaction(self):
859
626
        return self.control_files.get_transaction()
860
627
 
861
 
    def revision_parents(self, revision_id):
862
 
        revision_id = osutils.safe_revision_id(revision_id)
863
 
        return self.get_inventory_weave().parent_names(revision_id)
 
628
    def revision_parents(self, revid):
 
629
        return self.get_inventory_weave().parent_names(revid)
864
630
 
865
631
    @needs_write_lock
866
632
    def set_make_working_trees(self, new_value):
880
646
 
881
647
    @needs_write_lock
882
648
    def sign_revision(self, revision_id, gpg_strategy):
883
 
        revision_id = osutils.safe_revision_id(revision_id)
884
649
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
885
650
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
886
651
 
887
652
    @needs_read_lock
888
653
    def has_signature_for_revision_id(self, revision_id):
889
654
        """Query for a revision signature for revision_id in the repository."""
890
 
        revision_id = osutils.safe_revision_id(revision_id)
891
655
        return self._revision_store.has_signature(revision_id,
892
656
                                                  self.get_transaction())
893
657
 
894
658
    @needs_read_lock
895
659
    def get_signature_text(self, revision_id):
896
660
        """Return the text for a signature."""
897
 
        revision_id = osutils.safe_revision_id(revision_id)
898
661
        return self._revision_store.get_signature_text(revision_id,
899
662
                                                       self.get_transaction())
900
663
 
910
673
        if not revision_ids:
911
674
            raise ValueError("revision_ids must be non-empty in %s.check" 
912
675
                    % (self,))
913
 
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
914
676
        return self._check(revision_ids)
915
677
 
916
678
    def _check(self, revision_ids):
918
680
        result.check()
919
681
        return result
920
682
 
921
 
    def _warn_if_deprecated(self):
922
 
        global _deprecation_warning_done
923
 
        if _deprecation_warning_done:
924
 
            return
925
 
        _deprecation_warning_done = True
926
 
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
927
 
                % (self._format, self.bzrdir.transport.base))
928
 
 
929
 
    def supports_rich_root(self):
930
 
        return self._format.rich_root_data
931
 
 
932
 
    def _check_ascii_revisionid(self, revision_id, method):
933
 
        """Private helper for ascii-only repositories."""
934
 
        # weave repositories refuse to store revisionids that are non-ascii.
935
 
        if revision_id is not None:
936
 
            # weaves require ascii revision ids.
937
 
            if isinstance(revision_id, unicode):
938
 
                try:
939
 
                    revision_id.encode('ascii')
940
 
                except UnicodeEncodeError:
941
 
                    raise errors.NonAsciiRevisionId(method, self)
942
 
            else:
943
 
                try:
944
 
                    revision_id.decode('ascii')
945
 
                except UnicodeDecodeError:
946
 
                    raise errors.NonAsciiRevisionId(method, self)
947
 
 
948
 
 
949
 
 
950
 
# remove these delegates a while after bzr 0.15
951
 
def __make_delegated(name, from_module):
952
 
    def _deprecated_repository_forwarder():
953
 
        symbol_versioning.warn('%s moved to %s in bzr 0.15'
954
 
            % (name, from_module),
955
 
            DeprecationWarning,
956
 
            stacklevel=2)
957
 
        m = __import__(from_module, globals(), locals(), [name])
958
 
        try:
959
 
            return getattr(m, name)
960
 
        except AttributeError:
961
 
            raise AttributeError('module %s has no name %s'
962
 
                    % (m, name))
963
 
    globals()[name] = _deprecated_repository_forwarder
964
 
 
965
 
for _name in [
966
 
        'AllInOneRepository',
967
 
        'WeaveMetaDirRepository',
968
 
        'PreSplitOutRepositoryFormat',
969
 
        'RepositoryFormat4',
970
 
        'RepositoryFormat5',
971
 
        'RepositoryFormat6',
972
 
        'RepositoryFormat7',
973
 
        ]:
974
 
    __make_delegated(_name, 'bzrlib.repofmt.weaverepo')
975
 
 
976
 
for _name in [
977
 
        'KnitRepository',
978
 
        'RepositoryFormatKnit',
979
 
        'RepositoryFormatKnit1',
980
 
        ]:
981
 
    __make_delegated(_name, 'bzrlib.repofmt.knitrepo')
 
683
 
 
684
class AllInOneRepository(Repository):
 
685
    """Legacy support - the repository behaviour for all-in-one branches."""
 
686
 
 
687
    def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
 
688
        # we reuse one control files instance.
 
689
        dir_mode = a_bzrdir._control_files._dir_mode
 
690
        file_mode = a_bzrdir._control_files._file_mode
 
691
 
 
692
        def get_store(name, compressed=True, prefixed=False):
 
693
            # FIXME: This approach of assuming stores are all entirely compressed
 
694
            # or entirely uncompressed is tidy, but breaks upgrade from 
 
695
            # some existing branches where there's a mixture; we probably 
 
696
            # still want the option to look for both.
 
697
            relpath = a_bzrdir._control_files._escape(name)
 
698
            store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
 
699
                              prefixed=prefixed, compressed=compressed,
 
700
                              dir_mode=dir_mode,
 
701
                              file_mode=file_mode)
 
702
            #if self._transport.should_cache():
 
703
            #    cache_path = os.path.join(self.cache_root, name)
 
704
            #    os.mkdir(cache_path)
 
705
            #    store = bzrlib.store.CachedStore(store, cache_path)
 
706
            return store
 
707
 
 
708
        # not broken out yet because the controlweaves|inventory_store
 
709
        # and text_store | weave_store bits are still different.
 
710
        if isinstance(_format, RepositoryFormat4):
 
711
            # cannot remove these - there is still no consistent api 
 
712
            # which allows access to this old info.
 
713
            self.inventory_store = get_store('inventory-store')
 
714
            text_store = get_store('text-store')
 
715
        super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
 
716
 
 
717
    @needs_read_lock
 
718
    def is_shared(self):
 
719
        """AllInOne repositories cannot be shared."""
 
720
        return False
 
721
 
 
722
    @needs_write_lock
 
723
    def set_make_working_trees(self, new_value):
 
724
        """Set the policy flag for making working trees when creating branches.
 
725
 
 
726
        This only applies to branches that use this repository.
 
727
 
 
728
        The default is 'True'.
 
729
        :param new_value: True to restore the default, False to disable making
 
730
                          working trees.
 
731
        """
 
732
        raise NotImplementedError(self.set_make_working_trees)
 
733
    
 
734
    def make_working_trees(self):
 
735
        """Returns the policy for making working trees on new branches."""
 
736
        return True
982
737
 
983
738
 
984
739
def install_revision(repository, rev, revision_tree):
993
748
            parent_trees[p_id] = repository.revision_tree(None)
994
749
 
995
750
    inv = revision_tree.inventory
 
751
    
 
752
    # backwards compatability hack: skip the root id.
996
753
    entries = inv.iter_entries()
997
 
    # backwards compatability hack: skip the root id.
998
 
    if not repository.supports_rich_root():
999
 
        path, root = entries.next()
1000
 
        if root.revision != rev.revision_id:
1001
 
            raise errors.IncompatibleRevision(repr(repository))
 
754
    entries.next()
1002
755
    # Add the texts that are not already present
1003
756
    for path, ie in entries:
1004
757
        w = repository.weave_store.get_weave_or_empty(ie.file_id,
1039
792
                                                _revision_store,
1040
793
                                                control_store,
1041
794
                                                text_store)
 
795
 
1042
796
        dir_mode = self.control_files._dir_mode
1043
797
        file_mode = self.control_files._file_mode
1044
798
 
1070
824
        return not self.control_files._transport.has('no-working-trees')
1071
825
 
1072
826
 
1073
 
class RepositoryFormatRegistry(registry.Registry):
1074
 
    """Registry of RepositoryFormats.
1075
 
    """
1076
 
 
1077
 
    def get(self, format_string):
1078
 
        r = registry.Registry.get(self, format_string)
1079
 
        if callable(r):
1080
 
            r = r()
1081
 
        return r
 
827
class KnitRepository(MetaDirRepository):
 
828
    """Knit format repository."""
 
829
 
 
830
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
 
831
        inv_vf.add_lines_with_ghosts(revid, parents, lines)
 
832
 
 
833
    @needs_read_lock
 
834
    def _all_revision_ids(self):
 
835
        """See Repository.all_revision_ids()."""
 
836
        # Knits get the revision graph from the index of the revision knit, so
 
837
        # it's always possible even if they're on an unlistable transport.
 
838
        return self._revision_store.all_revision_ids(self.get_transaction())
 
839
 
 
840
    def fileid_involved_between_revs(self, from_revid, to_revid):
 
841
        """Find file_id(s) which are involved in the changes between revisions.
 
842
 
 
843
        This determines the set of revisions which are involved, and then
 
844
        finds all file ids affected by those revisions.
 
845
        """
 
846
        vf = self._get_revision_vf()
 
847
        from_set = set(vf.get_ancestry(from_revid))
 
848
        to_set = set(vf.get_ancestry(to_revid))
 
849
        changed = to_set.difference(from_set)
 
850
        return self._fileid_involved_by_set(changed)
 
851
 
 
852
    def fileid_involved(self, last_revid=None):
 
853
        """Find all file_ids modified in the ancestry of last_revid.
 
854
 
 
855
        :param last_revid: If None, last_revision() will be used.
 
856
        """
 
857
        if not last_revid:
 
858
            changed = set(self.all_revision_ids())
 
859
        else:
 
860
            changed = set(self.get_ancestry(last_revid))
 
861
        if None in changed:
 
862
            changed.remove(None)
 
863
        return self._fileid_involved_by_set(changed)
 
864
 
 
865
    @needs_read_lock
 
866
    def get_ancestry(self, revision_id):
 
867
        """Return a list of revision-ids integrated by a revision.
 
868
        
 
869
        This is topologically sorted.
 
870
        """
 
871
        if revision_id is None:
 
872
            return [None]
 
873
        vf = self._get_revision_vf()
 
874
        try:
 
875
            return [None] + vf.get_ancestry(revision_id)
 
876
        except errors.RevisionNotPresent:
 
877
            raise errors.NoSuchRevision(self, revision_id)
 
878
 
 
879
    @needs_read_lock
 
880
    def get_revision(self, revision_id):
 
881
        """Return the Revision object for a named revision"""
 
882
        return self.get_revision_reconcile(revision_id)
 
883
 
 
884
    @needs_read_lock
 
885
    def get_revision_graph(self, revision_id=None):
 
886
        """Return a dictionary containing the revision graph.
 
887
 
 
888
        :param revision_id: The revision_id to get a graph from. If None, then
 
889
        the entire revision graph is returned. This is a deprecated mode of
 
890
        operation and will be removed in the future.
 
891
        :return: a dictionary of revision_id->revision_parents_list.
 
892
        """
 
893
        # special case NULL_REVISION
 
894
        if revision_id == NULL_REVISION:
 
895
            return {}
 
896
        weave = self._get_revision_vf()
 
897
        entire_graph = weave.get_graph()
 
898
        if revision_id is None:
 
899
            return weave.get_graph()
 
900
        elif revision_id not in weave:
 
901
            raise errors.NoSuchRevision(self, revision_id)
 
902
        else:
 
903
            # add what can be reached from revision_id
 
904
            result = {}
 
905
            pending = set([revision_id])
 
906
            while len(pending) > 0:
 
907
                node = pending.pop()
 
908
                result[node] = weave.get_parents(node)
 
909
                for revision_id in result[node]:
 
910
                    if revision_id not in result:
 
911
                        pending.add(revision_id)
 
912
            return result
 
913
 
 
914
    @needs_read_lock
 
915
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
916
        """Return a graph of the revisions with ghosts marked as applicable.
 
917
 
 
918
        :param revision_ids: an iterable of revisions to graph or None for all.
 
919
        :return: a Graph object with the graph reachable from revision_ids.
 
920
        """
 
921
        result = Graph()
 
922
        vf = self._get_revision_vf()
 
923
        versions = set(vf.versions())
 
924
        if not revision_ids:
 
925
            pending = set(self.all_revision_ids())
 
926
            required = set([])
 
927
        else:
 
928
            pending = set(revision_ids)
 
929
            # special case NULL_REVISION
 
930
            if NULL_REVISION in pending:
 
931
                pending.remove(NULL_REVISION)
 
932
            required = set(pending)
 
933
        done = set([])
 
934
        while len(pending):
 
935
            revision_id = pending.pop()
 
936
            if not revision_id in versions:
 
937
                if revision_id in required:
 
938
                    raise errors.NoSuchRevision(self, revision_id)
 
939
                # a ghost
 
940
                result.add_ghost(revision_id)
 
941
                # mark it as done so we don't try for it again.
 
942
                done.add(revision_id)
 
943
                continue
 
944
            parent_ids = vf.get_parents_with_ghosts(revision_id)
 
945
            for parent_id in parent_ids:
 
946
                # is this queued or done ?
 
947
                if (parent_id not in pending and
 
948
                    parent_id not in done):
 
949
                    # no, queue it.
 
950
                    pending.add(parent_id)
 
951
            result.add_node(revision_id, parent_ids)
 
952
            done.add(revision_id)
 
953
        return result
 
954
 
 
955
    def _get_revision_vf(self):
 
956
        """:return: a versioned file containing the revisions."""
 
957
        vf = self._revision_store.get_revision_file(self.get_transaction())
 
958
        return vf
 
959
 
 
960
    @needs_write_lock
 
961
    def reconcile(self, other=None, thorough=False):
 
962
        """Reconcile this repository."""
 
963
        from bzrlib.reconcile import KnitReconciler
 
964
        reconciler = KnitReconciler(self, thorough=thorough)
 
965
        reconciler.reconcile()
 
966
        return reconciler
1082
967
    
1083
 
 
1084
 
format_registry = RepositoryFormatRegistry()
1085
 
"""Registry of formats, indexed by their identifying format string.
1086
 
 
1087
 
This can contain either format instances themselves, or classes/factories that
1088
 
can be called to obtain one.
1089
 
"""
1090
 
 
1091
 
 
1092
 
#####################################################################
1093
 
# Repository Formats
 
968
    def revision_parents(self, revision_id):
 
969
        return self._get_revision_vf().get_parents(revision_id)
 
970
 
1094
971
 
1095
972
class RepositoryFormat(object):
1096
973
    """A repository format.
1116
993
    parameterisation.
1117
994
    """
1118
995
 
1119
 
    def __str__(self):
1120
 
        return "<%s>" % self.__class__.__name__
1121
 
 
1122
 
    def __eq__(self, other):
1123
 
        # format objects are generally stateless
1124
 
        return isinstance(other, self.__class__)
1125
 
 
1126
 
    def __ne__(self, other):
1127
 
        return not self == other
 
996
    _default_format = None
 
997
    """The default format used for new repositories."""
 
998
 
 
999
    _formats = {}
 
1000
    """The known formats."""
1128
1001
 
1129
1002
    @classmethod
1130
1003
    def find_format(klass, a_bzrdir):
1131
 
        """Return the format for the repository object in a_bzrdir.
1132
 
        
1133
 
        This is used by bzr native formats that have a "format" file in
1134
 
        the repository.  Other methods may be used by different types of 
1135
 
        control directory.
1136
 
        """
 
1004
        """Return the format for the repository object in a_bzrdir."""
1137
1005
        try:
1138
1006
            transport = a_bzrdir.get_repository_transport(None)
1139
1007
            format_string = transport.get("format").read()
1140
 
            return format_registry.get(format_string)
 
1008
            return klass._formats[format_string]
1141
1009
        except errors.NoSuchFile:
1142
1010
            raise errors.NoRepositoryPresent(a_bzrdir)
1143
1011
        except KeyError:
1144
1012
            raise errors.UnknownFormatError(format=format_string)
1145
1013
 
1146
 
    @classmethod
1147
 
    def register_format(klass, format):
1148
 
        format_registry.register(format.get_format_string(), format)
1149
 
 
1150
 
    @classmethod
1151
 
    def unregister_format(klass, format):
1152
 
        format_registry.remove(format.get_format_string())
 
1014
    def _get_control_store(self, repo_transport, control_files):
 
1015
        """Return the control store for this repository."""
 
1016
        raise NotImplementedError(self._get_control_store)
1153
1017
    
1154
1018
    @classmethod
1155
1019
    def get_default_format(klass):
1156
1020
        """Return the current default format."""
1157
 
        from bzrlib import bzrdir
1158
 
        return bzrdir.format_registry.make_bzrdir('default').repository_format
1159
 
 
1160
 
    def _get_control_store(self, repo_transport, control_files):
1161
 
        """Return the control store for this repository."""
1162
 
        raise NotImplementedError(self._get_control_store)
 
1021
        return klass._default_format
1163
1022
 
1164
1023
    def get_format_string(self):
1165
1024
        """Return the ASCII format string that identifies this format.
1192
1051
        from bzrlib.store.revision.text import TextRevisionStore
1193
1052
        dir_mode = control_files._dir_mode
1194
1053
        file_mode = control_files._file_mode
1195
 
        text_store = TextStore(transport.clone(name),
 
1054
        text_store =TextStore(transport.clone(name),
1196
1055
                              prefixed=prefixed,
1197
1056
                              compressed=compressed,
1198
1057
                              dir_mode=dir_mode,
1200
1059
        _revision_store = TextRevisionStore(text_store, serializer)
1201
1060
        return _revision_store
1202
1061
 
1203
 
    # TODO: this shouldn't be in the base class, it's specific to things that
1204
 
    # use weaves or knits -- mbp 20070207
1205
1062
    def _get_versioned_file_store(self,
1206
1063
                                  name,
1207
1064
                                  transport,
1208
1065
                                  control_files,
1209
1066
                                  prefixed=True,
1210
 
                                  versionedfile_class=None,
1211
 
                                  versionedfile_kwargs={},
 
1067
                                  versionedfile_class=WeaveFile,
1212
1068
                                  escaped=False):
1213
 
        if versionedfile_class is None:
1214
 
            versionedfile_class = self._versionedfile_class
1215
1069
        weave_transport = control_files._transport.clone(name)
1216
1070
        dir_mode = control_files._dir_mode
1217
1071
        file_mode = control_files._file_mode
1219
1073
                                  dir_mode=dir_mode,
1220
1074
                                  file_mode=file_mode,
1221
1075
                                  versionedfile_class=versionedfile_class,
1222
 
                                  versionedfile_kwargs=versionedfile_kwargs,
1223
1076
                                  escaped=escaped)
1224
1077
 
1225
1078
    def initialize(self, a_bzrdir, shared=False):
1227
1080
 
1228
1081
        :param a_bzrdir: The bzrdir to put the new repository in it.
1229
1082
        :param shared: The repository should be initialized as a sharable one.
1230
 
        :returns: The new repository object.
1231
 
        
 
1083
 
1232
1084
        This may raise UninitializableFormat if shared repository are not
1233
1085
        compatible the a_bzrdir.
1234
1086
        """
1235
 
        raise NotImplementedError(self.initialize)
1236
1087
 
1237
1088
    def is_supported(self):
1238
1089
        """Is this format supported?
1243
1094
        """
1244
1095
        return True
1245
1096
 
1246
 
    def check_conversion_target(self, target_format):
1247
 
        raise NotImplementedError(self.check_conversion_target)
1248
 
 
1249
1097
    def open(self, a_bzrdir, _found=False):
1250
1098
        """Return an instance of this format for the bzrdir a_bzrdir.
1251
1099
        
1253
1101
        """
1254
1102
        raise NotImplementedError(self.open)
1255
1103
 
 
1104
    @classmethod
 
1105
    def register_format(klass, format):
 
1106
        klass._formats[format.get_format_string()] = format
 
1107
 
 
1108
    @classmethod
 
1109
    def set_default_format(klass, format):
 
1110
        klass._default_format = format
 
1111
 
 
1112
    @classmethod
 
1113
    def unregister_format(klass, format):
 
1114
        assert klass._formats[format.get_format_string()] is format
 
1115
        del klass._formats[format.get_format_string()]
 
1116
 
 
1117
 
 
1118
class PreSplitOutRepositoryFormat(RepositoryFormat):
 
1119
    """Base class for the pre split out repository formats."""
 
1120
 
 
1121
    def initialize(self, a_bzrdir, shared=False, _internal=False):
 
1122
        """Create a weave repository.
 
1123
        
 
1124
        TODO: when creating split out bzr branch formats, move this to a common
 
1125
        base for Format5, Format6. or something like that.
 
1126
        """
 
1127
        from bzrlib.weavefile import write_weave_v5
 
1128
        from bzrlib.weave import Weave
 
1129
 
 
1130
        if shared:
 
1131
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
 
1132
 
 
1133
        if not _internal:
 
1134
            # always initialized when the bzrdir is.
 
1135
            return self.open(a_bzrdir, _found=True)
 
1136
        
 
1137
        # Create an empty weave
 
1138
        sio = StringIO()
 
1139
        write_weave_v5(Weave(), sio)
 
1140
        empty_weave = sio.getvalue()
 
1141
 
 
1142
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
1143
        dirs = ['revision-store', 'weaves']
 
1144
        files = [('inventory.weave', StringIO(empty_weave)),
 
1145
                 ]
 
1146
        
 
1147
        # FIXME: RBC 20060125 don't peek under the covers
 
1148
        # NB: no need to escape relative paths that are url safe.
 
1149
        control_files = LockableFiles(a_bzrdir.transport, 'branch-lock',
 
1150
                                      TransportLock)
 
1151
        control_files.create_lock()
 
1152
        control_files.lock_write()
 
1153
        control_files._transport.mkdir_multi(dirs,
 
1154
                mode=control_files._dir_mode)
 
1155
        try:
 
1156
            for file, content in files:
 
1157
                control_files.put(file, content)
 
1158
        finally:
 
1159
            control_files.unlock()
 
1160
        return self.open(a_bzrdir, _found=True)
 
1161
 
 
1162
    def _get_control_store(self, repo_transport, control_files):
 
1163
        """Return the control store for this repository."""
 
1164
        return self._get_versioned_file_store('',
 
1165
                                              repo_transport,
 
1166
                                              control_files,
 
1167
                                              prefixed=False)
 
1168
 
 
1169
    def _get_text_store(self, transport, control_files):
 
1170
        """Get a store for file texts for this format."""
 
1171
        raise NotImplementedError(self._get_text_store)
 
1172
 
 
1173
    def open(self, a_bzrdir, _found=False):
 
1174
        """See RepositoryFormat.open()."""
 
1175
        if not _found:
 
1176
            # we are being called directly and must probe.
 
1177
            raise NotImplementedError
 
1178
 
 
1179
        repo_transport = a_bzrdir.get_repository_transport(None)
 
1180
        control_files = a_bzrdir._control_files
 
1181
        text_store = self._get_text_store(repo_transport, control_files)
 
1182
        control_store = self._get_control_store(repo_transport, control_files)
 
1183
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
1184
        return AllInOneRepository(_format=self,
 
1185
                                  a_bzrdir=a_bzrdir,
 
1186
                                  _revision_store=_revision_store,
 
1187
                                  control_store=control_store,
 
1188
                                  text_store=text_store)
 
1189
 
 
1190
 
 
1191
class RepositoryFormat4(PreSplitOutRepositoryFormat):
 
1192
    """Bzr repository format 4.
 
1193
 
 
1194
    This repository format has:
 
1195
     - flat stores
 
1196
     - TextStores for texts, inventories,revisions.
 
1197
 
 
1198
    This format is deprecated: it indexes texts using a text id which is
 
1199
    removed in format 5; initialization and write support for this format
 
1200
    has been removed.
 
1201
    """
 
1202
 
 
1203
    def __init__(self):
 
1204
        super(RepositoryFormat4, self).__init__()
 
1205
        self._matchingbzrdir = bzrdir.BzrDirFormat4()
 
1206
 
 
1207
    def get_format_description(self):
 
1208
        """See RepositoryFormat.get_format_description()."""
 
1209
        return "Repository format 4"
 
1210
 
 
1211
    def initialize(self, url, shared=False, _internal=False):
 
1212
        """Format 4 branches cannot be created."""
 
1213
        raise errors.UninitializableFormat(self)
 
1214
 
 
1215
    def is_supported(self):
 
1216
        """Format 4 is not supported.
 
1217
 
 
1218
        It is not supported because the model changed from 4 to 5 and the
 
1219
        conversion logic is expensive - so doing it on the fly was not 
 
1220
        feasible.
 
1221
        """
 
1222
        return False
 
1223
 
 
1224
    def _get_control_store(self, repo_transport, control_files):
 
1225
        """Format 4 repositories have no formal control store at this point.
 
1226
        
 
1227
        This will cause any control-file-needing apis to fail - this is desired.
 
1228
        """
 
1229
        return None
 
1230
    
 
1231
    def _get_revision_store(self, repo_transport, control_files):
 
1232
        """See RepositoryFormat._get_revision_store()."""
 
1233
        from bzrlib.xml4 import serializer_v4
 
1234
        return self._get_text_rev_store(repo_transport,
 
1235
                                        control_files,
 
1236
                                        'revision-store',
 
1237
                                        serializer=serializer_v4)
 
1238
 
 
1239
    def _get_text_store(self, transport, control_files):
 
1240
        """See RepositoryFormat._get_text_store()."""
 
1241
 
 
1242
 
 
1243
class RepositoryFormat5(PreSplitOutRepositoryFormat):
 
1244
    """Bzr control format 5.
 
1245
 
 
1246
    This repository format has:
 
1247
     - weaves for file texts and inventory
 
1248
     - flat stores
 
1249
     - TextStores for revisions and signatures.
 
1250
    """
 
1251
 
 
1252
    def __init__(self):
 
1253
        super(RepositoryFormat5, self).__init__()
 
1254
        self._matchingbzrdir = bzrdir.BzrDirFormat5()
 
1255
 
 
1256
    def get_format_description(self):
 
1257
        """See RepositoryFormat.get_format_description()."""
 
1258
        return "Weave repository format 5"
 
1259
 
 
1260
    def _get_revision_store(self, repo_transport, control_files):
 
1261
        """See RepositoryFormat._get_revision_store()."""
 
1262
        """Return the revision store object for this a_bzrdir."""
 
1263
        return self._get_text_rev_store(repo_transport,
 
1264
                                        control_files,
 
1265
                                        'revision-store',
 
1266
                                        compressed=False)
 
1267
 
 
1268
    def _get_text_store(self, transport, control_files):
 
1269
        """See RepositoryFormat._get_text_store()."""
 
1270
        return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
 
1271
 
 
1272
 
 
1273
class RepositoryFormat6(PreSplitOutRepositoryFormat):
 
1274
    """Bzr control format 6.
 
1275
 
 
1276
    This repository format has:
 
1277
     - weaves for file texts and inventory
 
1278
     - hash subdirectory based stores.
 
1279
     - TextStores for revisions and signatures.
 
1280
    """
 
1281
 
 
1282
    def __init__(self):
 
1283
        super(RepositoryFormat6, self).__init__()
 
1284
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1285
 
 
1286
    def get_format_description(self):
 
1287
        """See RepositoryFormat.get_format_description()."""
 
1288
        return "Weave repository format 6"
 
1289
 
 
1290
    def _get_revision_store(self, repo_transport, control_files):
 
1291
        """See RepositoryFormat._get_revision_store()."""
 
1292
        return self._get_text_rev_store(repo_transport,
 
1293
                                        control_files,
 
1294
                                        'revision-store',
 
1295
                                        compressed=False,
 
1296
                                        prefixed=True)
 
1297
 
 
1298
    def _get_text_store(self, transport, control_files):
 
1299
        """See RepositoryFormat._get_text_store()."""
 
1300
        return self._get_versioned_file_store('weaves', transport, control_files)
 
1301
 
1256
1302
 
1257
1303
class MetaDirRepositoryFormat(RepositoryFormat):
1258
1304
    """Common base class for the new repositories using the metadir layout."""
1259
1305
 
1260
 
    rich_root_data = False
1261
 
    supports_tree_reference = False
1262
 
    _matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1263
 
 
1264
1306
    def __init__(self):
1265
1307
        super(MetaDirRepositoryFormat, self).__init__()
 
1308
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1266
1309
 
1267
1310
    def _create_control_files(self, a_bzrdir):
1268
1311
        """Create the required files and the initial control_files object."""
1269
1312
        # FIXME: RBC 20060125 don't peek under the covers
1270
1313
        # NB: no need to escape relative paths that are url safe.
1271
1314
        repository_transport = a_bzrdir.get_repository_transport(self)
1272
 
        control_files = lockable_files.LockableFiles(repository_transport,
1273
 
                                'lock', lockdir.LockDir)
 
1315
        control_files = LockableFiles(repository_transport, 'lock', LockDir)
1274
1316
        control_files.create_lock()
1275
1317
        return control_files
1276
1318
 
1291
1333
            control_files.unlock()
1292
1334
 
1293
1335
 
 
1336
class RepositoryFormat7(MetaDirRepositoryFormat):
 
1337
    """Bzr repository 7.
 
1338
 
 
1339
    This repository format has:
 
1340
     - weaves for file texts and inventory
 
1341
     - hash subdirectory based stores.
 
1342
     - TextStores for revisions and signatures.
 
1343
     - a format marker of its own
 
1344
     - an optional 'shared-storage' flag
 
1345
     - an optional 'no-working-trees' flag
 
1346
    """
 
1347
 
 
1348
    def _get_control_store(self, repo_transport, control_files):
 
1349
        """Return the control store for this repository."""
 
1350
        return self._get_versioned_file_store('',
 
1351
                                              repo_transport,
 
1352
                                              control_files,
 
1353
                                              prefixed=False)
 
1354
 
 
1355
    def get_format_string(self):
 
1356
        """See RepositoryFormat.get_format_string()."""
 
1357
        return "Bazaar-NG Repository format 7"
 
1358
 
 
1359
    def get_format_description(self):
 
1360
        """See RepositoryFormat.get_format_description()."""
 
1361
        return "Weave repository format 7"
 
1362
 
 
1363
    def _get_revision_store(self, repo_transport, control_files):
 
1364
        """See RepositoryFormat._get_revision_store()."""
 
1365
        return self._get_text_rev_store(repo_transport,
 
1366
                                        control_files,
 
1367
                                        'revision-store',
 
1368
                                        compressed=False,
 
1369
                                        prefixed=True,
 
1370
                                        )
 
1371
 
 
1372
    def _get_text_store(self, transport, control_files):
 
1373
        """See RepositoryFormat._get_text_store()."""
 
1374
        return self._get_versioned_file_store('weaves',
 
1375
                                              transport,
 
1376
                                              control_files)
 
1377
 
 
1378
    def initialize(self, a_bzrdir, shared=False):
 
1379
        """Create a weave repository.
 
1380
 
 
1381
        :param shared: If true the repository will be initialized as a shared
 
1382
                       repository.
 
1383
        """
 
1384
        from bzrlib.weavefile import write_weave_v5
 
1385
        from bzrlib.weave import Weave
 
1386
 
 
1387
        # Create an empty weave
 
1388
        sio = StringIO()
 
1389
        write_weave_v5(Weave(), sio)
 
1390
        empty_weave = sio.getvalue()
 
1391
 
 
1392
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
1393
        dirs = ['revision-store', 'weaves']
 
1394
        files = [('inventory.weave', StringIO(empty_weave)), 
 
1395
                 ]
 
1396
        utf8_files = [('format', self.get_format_string())]
 
1397
 
 
1398
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
1399
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
1400
 
 
1401
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
1402
        """See RepositoryFormat.open().
 
1403
        
 
1404
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
1405
                                    repository at a slightly different url
 
1406
                                    than normal. I.e. during 'upgrade'.
 
1407
        """
 
1408
        if not _found:
 
1409
            format = RepositoryFormat.find_format(a_bzrdir)
 
1410
            assert format.__class__ ==  self.__class__
 
1411
        if _override_transport is not None:
 
1412
            repo_transport = _override_transport
 
1413
        else:
 
1414
            repo_transport = a_bzrdir.get_repository_transport(None)
 
1415
        control_files = LockableFiles(repo_transport, 'lock', LockDir)
 
1416
        text_store = self._get_text_store(repo_transport, control_files)
 
1417
        control_store = self._get_control_store(repo_transport, control_files)
 
1418
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
1419
        return MetaDirRepository(_format=self,
 
1420
                                 a_bzrdir=a_bzrdir,
 
1421
                                 control_files=control_files,
 
1422
                                 _revision_store=_revision_store,
 
1423
                                 control_store=control_store,
 
1424
                                 text_store=text_store)
 
1425
 
 
1426
 
 
1427
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
 
1428
    """Bzr repository knit format 1.
 
1429
 
 
1430
    This repository format has:
 
1431
     - knits for file texts and inventory
 
1432
     - hash subdirectory based stores.
 
1433
     - knits for revisions and signatures
 
1434
     - TextStores for revisions and signatures.
 
1435
     - a format marker of its own
 
1436
     - an optional 'shared-storage' flag
 
1437
     - an optional 'no-working-trees' flag
 
1438
     - a LockDir lock
 
1439
 
 
1440
    This format was introduced in bzr 0.8.
 
1441
    """
 
1442
 
 
1443
    def _get_control_store(self, repo_transport, control_files):
 
1444
        """Return the control store for this repository."""
 
1445
        return VersionedFileStore(
 
1446
            repo_transport,
 
1447
            prefixed=False,
 
1448
            file_mode=control_files._file_mode,
 
1449
            versionedfile_class=KnitVersionedFile,
 
1450
            versionedfile_kwargs={'factory':KnitPlainFactory()},
 
1451
            )
 
1452
 
 
1453
    def get_format_string(self):
 
1454
        """See RepositoryFormat.get_format_string()."""
 
1455
        return "Bazaar-NG Knit Repository Format 1"
 
1456
 
 
1457
    def get_format_description(self):
 
1458
        """See RepositoryFormat.get_format_description()."""
 
1459
        return "Knit repository format 1"
 
1460
 
 
1461
    def _get_revision_store(self, repo_transport, control_files):
 
1462
        """See RepositoryFormat._get_revision_store()."""
 
1463
        from bzrlib.store.revision.knit import KnitRevisionStore
 
1464
        versioned_file_store = VersionedFileStore(
 
1465
            repo_transport,
 
1466
            file_mode=control_files._file_mode,
 
1467
            prefixed=False,
 
1468
            precious=True,
 
1469
            versionedfile_class=KnitVersionedFile,
 
1470
            versionedfile_kwargs={'delta':False, 'factory':KnitPlainFactory()},
 
1471
            escaped=True,
 
1472
            )
 
1473
        return KnitRevisionStore(versioned_file_store)
 
1474
 
 
1475
    def _get_text_store(self, transport, control_files):
 
1476
        """See RepositoryFormat._get_text_store()."""
 
1477
        return self._get_versioned_file_store('knits',
 
1478
                                              transport,
 
1479
                                              control_files,
 
1480
                                              versionedfile_class=KnitVersionedFile,
 
1481
                                              escaped=True)
 
1482
 
 
1483
    def initialize(self, a_bzrdir, shared=False):
 
1484
        """Create a knit format 1 repository.
 
1485
 
 
1486
        :param a_bzrdir: bzrdir to contain the new repository; must already
 
1487
            be initialized.
 
1488
        :param shared: If true the repository will be initialized as a shared
 
1489
                       repository.
 
1490
        """
 
1491
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
1492
        dirs = ['revision-store', 'knits']
 
1493
        files = []
 
1494
        utf8_files = [('format', self.get_format_string())]
 
1495
        
 
1496
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
1497
        repo_transport = a_bzrdir.get_repository_transport(None)
 
1498
        control_files = LockableFiles(repo_transport, 'lock', LockDir)
 
1499
        control_store = self._get_control_store(repo_transport, control_files)
 
1500
        transaction = transactions.WriteTransaction()
 
1501
        # trigger a write of the inventory store.
 
1502
        control_store.get_weave_or_empty('inventory', transaction)
 
1503
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
1504
        _revision_store.has_revision_id('A', transaction)
 
1505
        _revision_store.get_signature_file(transaction)
 
1506
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
1507
 
 
1508
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
1509
        """See RepositoryFormat.open().
 
1510
        
 
1511
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
1512
                                    repository at a slightly different url
 
1513
                                    than normal. I.e. during 'upgrade'.
 
1514
        """
 
1515
        if not _found:
 
1516
            format = RepositoryFormat.find_format(a_bzrdir)
 
1517
            assert format.__class__ ==  self.__class__
 
1518
        if _override_transport is not None:
 
1519
            repo_transport = _override_transport
 
1520
        else:
 
1521
            repo_transport = a_bzrdir.get_repository_transport(None)
 
1522
        control_files = LockableFiles(repo_transport, 'lock', LockDir)
 
1523
        text_store = self._get_text_store(repo_transport, control_files)
 
1524
        control_store = self._get_control_store(repo_transport, control_files)
 
1525
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
1526
        return KnitRepository(_format=self,
 
1527
                              a_bzrdir=a_bzrdir,
 
1528
                              control_files=control_files,
 
1529
                              _revision_store=_revision_store,
 
1530
                              control_store=control_store,
 
1531
                              text_store=text_store)
 
1532
 
 
1533
 
1294
1534
# formats which have no format string are not discoverable
1295
 
# and not independently creatable, so are not registered.  They're 
1296
 
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
1297
 
# needed, it's constructed directly by the BzrDir.  Non-native formats where
1298
 
# the repository is not separately opened are similar.
1299
 
 
1300
 
format_registry.register_lazy(
1301
 
    'Bazaar-NG Repository format 7',
1302
 
    'bzrlib.repofmt.weaverepo',
1303
 
    'RepositoryFormat7'
1304
 
    )
1305
 
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1306
 
# default control directory format
1307
 
 
1308
 
format_registry.register_lazy(
1309
 
    'Bazaar-NG Knit Repository Format 1',
1310
 
    'bzrlib.repofmt.knitrepo',
1311
 
    'RepositoryFormatKnit1',
1312
 
    )
1313
 
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
1314
 
 
1315
 
format_registry.register_lazy(
1316
 
    'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
1317
 
    'bzrlib.repofmt.knitrepo',
1318
 
    'RepositoryFormatKnit3',
1319
 
    )
 
1535
# and not independently creatable, so are not registered.
 
1536
RepositoryFormat.register_format(RepositoryFormat7())
 
1537
_default_format = RepositoryFormatKnit1()
 
1538
RepositoryFormat.register_format(_default_format)
 
1539
RepositoryFormat.set_default_format(_default_format)
 
1540
_legacy_formats = [RepositoryFormat4(),
 
1541
                   RepositoryFormat5(),
 
1542
                   RepositoryFormat6()]
1320
1543
 
1321
1544
 
1322
1545
class InterRepository(InterObject):
1331
1554
    InterRepository.get(other).method_name(parameters).
1332
1555
    """
1333
1556
 
1334
 
    _optimisers = []
 
1557
    _optimisers = set()
1335
1558
    """The available optimised InterRepository types."""
1336
1559
 
1337
 
    def copy_content(self, revision_id=None):
1338
 
        raise NotImplementedError(self.copy_content)
1339
 
 
 
1560
    @needs_write_lock
 
1561
    def copy_content(self, revision_id=None, basis=None):
 
1562
        """Make a complete copy of the content in self into destination.
 
1563
        
 
1564
        This is a destructive operation! Do not use it on existing 
 
1565
        repositories.
 
1566
 
 
1567
        :param revision_id: Only copy the content needed to construct
 
1568
                            revision_id and its parents.
 
1569
        :param basis: Copy the needed data preferentially from basis.
 
1570
        """
 
1571
        try:
 
1572
            self.target.set_make_working_trees(self.source.make_working_trees())
 
1573
        except NotImplementedError:
 
1574
            pass
 
1575
        # grab the basis available data
 
1576
        if basis is not None:
 
1577
            self.target.fetch(basis, revision_id=revision_id)
 
1578
        # but don't bother fetching if we have the needed data now.
 
1579
        if (revision_id not in (None, NULL_REVISION) and 
 
1580
            self.target.has_revision(revision_id)):
 
1581
            return
 
1582
        self.target.fetch(self.source, revision_id=revision_id)
 
1583
 
 
1584
    @needs_write_lock
1340
1585
    def fetch(self, revision_id=None, pb=None):
1341
1586
        """Fetch the content required to construct revision_id.
1342
1587
 
1343
 
        The content is copied from self.source to self.target.
 
1588
        The content is copied from source to target.
1344
1589
 
1345
1590
        :param revision_id: if None all content is copied, if NULL_REVISION no
1346
1591
                            content is copied.
1350
1595
        Returns the copied revision count and the failed revisions in a tuple:
1351
1596
        (copied, failures).
1352
1597
        """
1353
 
        raise NotImplementedError(self.fetch)
1354
 
   
 
1598
        from bzrlib.fetch import GenericRepoFetcher
 
1599
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
1600
               self.source, self.source._format, self.target, self.target._format)
 
1601
        f = GenericRepoFetcher(to_repository=self.target,
 
1602
                               from_repository=self.source,
 
1603
                               last_revision=revision_id,
 
1604
                               pb=pb)
 
1605
        return f.count_copied, f.failed_revisions
 
1606
 
1355
1607
    @needs_read_lock
1356
1608
    def missing_revision_ids(self, revision_id=None):
1357
1609
        """Return the revision ids that source has that target does not.
1364
1616
        # generic, possibly worst case, slow code path.
1365
1617
        target_ids = set(self.target.all_revision_ids())
1366
1618
        if revision_id is not None:
1367
 
            # TODO: jam 20070210 InterRepository is internal enough that it
1368
 
            #       should assume revision_ids are already utf-8
1369
 
            revision_id = osutils.safe_revision_id(revision_id)
1370
1619
            source_ids = self.source.get_ancestry(revision_id)
1371
 
            assert source_ids[0] is None
 
1620
            assert source_ids[0] == None
1372
1621
            source_ids.pop(0)
1373
1622
        else:
1374
1623
            source_ids = self.source.all_revision_ids()
1379
1628
        return [rev_id for rev_id in source_ids if rev_id in result_set]
1380
1629
 
1381
1630
 
1382
 
class InterSameDataRepository(InterRepository):
1383
 
    """Code for converting between repositories that represent the same data.
1384
 
    
1385
 
    Data format and model must match for this to work.
1386
 
    """
1387
 
 
1388
 
    @classmethod
1389
 
    def _get_repo_format_to_test(self):
1390
 
        """Repository format for testing with."""
1391
 
        return RepositoryFormat.get_default_format()
1392
 
 
1393
 
    @staticmethod
1394
 
    def is_compatible(source, target):
1395
 
        if source.supports_rich_root() != target.supports_rich_root():
1396
 
            return False
1397
 
        if source._serializer != target._serializer:
1398
 
            return False
1399
 
        return True
1400
 
 
1401
 
    @needs_write_lock
1402
 
    def copy_content(self, revision_id=None):
1403
 
        """Make a complete copy of the content in self into destination.
1404
 
 
1405
 
        This copies both the repository's revision data, and configuration information
1406
 
        such as the make_working_trees setting.
1407
 
        
1408
 
        This is a destructive operation! Do not use it on existing 
1409
 
        repositories.
1410
 
 
1411
 
        :param revision_id: Only copy the content needed to construct
1412
 
                            revision_id and its parents.
1413
 
        """
1414
 
        try:
1415
 
            self.target.set_make_working_trees(self.source.make_working_trees())
1416
 
        except NotImplementedError:
1417
 
            pass
1418
 
        # TODO: jam 20070210 This is fairly internal, so we should probably
1419
 
        #       just assert that revision_id is not unicode.
1420
 
        revision_id = osutils.safe_revision_id(revision_id)
1421
 
        # but don't bother fetching if we have the needed data now.
1422
 
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
1423
 
            self.target.has_revision(revision_id)):
1424
 
            return
1425
 
        self.target.fetch(self.source, revision_id=revision_id)
1426
 
 
1427
 
    @needs_write_lock
1428
 
    def fetch(self, revision_id=None, pb=None):
1429
 
        """See InterRepository.fetch()."""
1430
 
        from bzrlib.fetch import GenericRepoFetcher
1431
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1432
 
               self.source, self.source._format, self.target, 
1433
 
               self.target._format)
1434
 
        # TODO: jam 20070210 This should be an assert, not a translate
1435
 
        revision_id = osutils.safe_revision_id(revision_id)
1436
 
        f = GenericRepoFetcher(to_repository=self.target,
1437
 
                               from_repository=self.source,
1438
 
                               last_revision=revision_id,
1439
 
                               pb=pb)
1440
 
        return f.count_copied, f.failed_revisions
1441
 
 
1442
 
 
1443
 
class InterWeaveRepo(InterSameDataRepository):
 
1631
class InterWeaveRepo(InterRepository):
1444
1632
    """Optimised code paths between Weave based repositories."""
1445
1633
 
1446
 
    @classmethod
1447
 
    def _get_repo_format_to_test(self):
1448
 
        from bzrlib.repofmt import weaverepo
1449
 
        return weaverepo.RepositoryFormat7()
 
1634
    _matching_repo_format = RepositoryFormat7()
 
1635
    """Repository format for testing with."""
1450
1636
 
1451
1637
    @staticmethod
1452
1638
    def is_compatible(source, target):
1456
1642
        could lead to confusing results, and there is no need to be 
1457
1643
        overly general.
1458
1644
        """
1459
 
        from bzrlib.repofmt.weaverepo import (
1460
 
                RepositoryFormat5,
1461
 
                RepositoryFormat6,
1462
 
                RepositoryFormat7,
1463
 
                )
1464
1645
        try:
1465
1646
            return (isinstance(source._format, (RepositoryFormat5,
1466
1647
                                                RepositoryFormat6,
1472
1653
            return False
1473
1654
    
1474
1655
    @needs_write_lock
1475
 
    def copy_content(self, revision_id=None):
 
1656
    def copy_content(self, revision_id=None, basis=None):
1476
1657
        """See InterRepository.copy_content()."""
1477
1658
        # weave specific optimised path:
1478
 
        # TODO: jam 20070210 Internal, should be an assert, not translate
1479
 
        revision_id = osutils.safe_revision_id(revision_id)
1480
 
        try:
1481
 
            self.target.set_make_working_trees(self.source.make_working_trees())
1482
 
        except NotImplementedError:
1483
 
            pass
1484
 
        # FIXME do not peek!
1485
 
        if self.source.control_files._transport.listable():
1486
 
            pb = ui.ui_factory.nested_progress_bar()
 
1659
        if basis is not None:
 
1660
            # copy the basis in, then fetch remaining data.
 
1661
            basis.copy_content_into(self.target, revision_id)
 
1662
            # the basis copy_content_into could miss-set this.
1487
1663
            try:
1488
 
                self.target.weave_store.copy_all_ids(
1489
 
                    self.source.weave_store,
1490
 
                    pb=pb,
1491
 
                    from_transaction=self.source.get_transaction(),
1492
 
                    to_transaction=self.target.get_transaction())
1493
 
                pb.update('copying inventory', 0, 1)
1494
 
                self.target.control_weaves.copy_multi(
1495
 
                    self.source.control_weaves, ['inventory'],
1496
 
                    from_transaction=self.source.get_transaction(),
1497
 
                    to_transaction=self.target.get_transaction())
1498
 
                self.target._revision_store.text_store.copy_all_ids(
1499
 
                    self.source._revision_store.text_store,
1500
 
                    pb=pb)
1501
 
            finally:
1502
 
                pb.finished()
1503
 
        else:
 
1664
                self.target.set_make_working_trees(self.source.make_working_trees())
 
1665
            except NotImplementedError:
 
1666
                pass
1504
1667
            self.target.fetch(self.source, revision_id=revision_id)
 
1668
        else:
 
1669
            try:
 
1670
                self.target.set_make_working_trees(self.source.make_working_trees())
 
1671
            except NotImplementedError:
 
1672
                pass
 
1673
            # FIXME do not peek!
 
1674
            if self.source.control_files._transport.listable():
 
1675
                pb = ui.ui_factory.nested_progress_bar()
 
1676
                try:
 
1677
                    self.target.weave_store.copy_all_ids(
 
1678
                        self.source.weave_store,
 
1679
                        pb=pb,
 
1680
                        from_transaction=self.source.get_transaction(),
 
1681
                        to_transaction=self.target.get_transaction())
 
1682
                    pb.update('copying inventory', 0, 1)
 
1683
                    self.target.control_weaves.copy_multi(
 
1684
                        self.source.control_weaves, ['inventory'],
 
1685
                        from_transaction=self.source.get_transaction(),
 
1686
                        to_transaction=self.target.get_transaction())
 
1687
                    self.target._revision_store.text_store.copy_all_ids(
 
1688
                        self.source._revision_store.text_store,
 
1689
                        pb=pb)
 
1690
                finally:
 
1691
                    pb.finished()
 
1692
            else:
 
1693
                self.target.fetch(self.source, revision_id=revision_id)
1505
1694
 
1506
1695
    @needs_write_lock
1507
1696
    def fetch(self, revision_id=None, pb=None):
1509
1698
        from bzrlib.fetch import GenericRepoFetcher
1510
1699
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1511
1700
               self.source, self.source._format, self.target, self.target._format)
1512
 
        # TODO: jam 20070210 This should be an assert, not a translate
1513
 
        revision_id = osutils.safe_revision_id(revision_id)
1514
1701
        f = GenericRepoFetcher(to_repository=self.target,
1515
1702
                               from_repository=self.source,
1516
1703
                               last_revision=revision_id,
1533
1720
        # - RBC 20060209
1534
1721
        if revision_id is not None:
1535
1722
            source_ids = self.source.get_ancestry(revision_id)
1536
 
            assert source_ids[0] is None
 
1723
            assert source_ids[0] == None
1537
1724
            source_ids.pop(0)
1538
1725
        else:
1539
1726
            source_ids = self.source._all_possible_ids()
1559
1746
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
1560
1747
 
1561
1748
 
1562
 
class InterKnitRepo(InterSameDataRepository):
 
1749
class InterKnitRepo(InterRepository):
1563
1750
    """Optimised code paths between Knit based repositories."""
1564
1751
 
1565
 
    @classmethod
1566
 
    def _get_repo_format_to_test(self):
1567
 
        from bzrlib.repofmt import knitrepo
1568
 
        return knitrepo.RepositoryFormatKnit1()
 
1752
    _matching_repo_format = RepositoryFormatKnit1()
 
1753
    """Repository format for testing with."""
1569
1754
 
1570
1755
    @staticmethod
1571
1756
    def is_compatible(source, target):
1575
1760
        could lead to confusing results, and there is no need to be 
1576
1761
        overly general.
1577
1762
        """
1578
 
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1
1579
1763
        try:
1580
1764
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
1581
1765
                    isinstance(target._format, (RepositoryFormatKnit1)))
1588
1772
        from bzrlib.fetch import KnitRepoFetcher
1589
1773
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1590
1774
               self.source, self.source._format, self.target, self.target._format)
1591
 
        # TODO: jam 20070210 This should be an assert, not a translate
1592
 
        revision_id = osutils.safe_revision_id(revision_id)
1593
1775
        f = KnitRepoFetcher(to_repository=self.target,
1594
1776
                            from_repository=self.source,
1595
1777
                            last_revision=revision_id,
1601
1783
        """See InterRepository.missing_revision_ids()."""
1602
1784
        if revision_id is not None:
1603
1785
            source_ids = self.source.get_ancestry(revision_id)
1604
 
            assert source_ids[0] is None
 
1786
            assert source_ids[0] == None
1605
1787
            source_ids.pop(0)
1606
1788
        else:
1607
1789
            source_ids = self.source._all_possible_ids()
1626
1808
            # that against the revision records.
1627
1809
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
1628
1810
 
1629
 
 
1630
 
class InterModel1and2(InterRepository):
1631
 
 
1632
 
    @classmethod
1633
 
    def _get_repo_format_to_test(self):
1634
 
        return None
1635
 
 
1636
 
    @staticmethod
1637
 
    def is_compatible(source, target):
1638
 
        if not source.supports_rich_root() and target.supports_rich_root():
1639
 
            return True
1640
 
        else:
1641
 
            return False
1642
 
 
1643
 
    @needs_write_lock
1644
 
    def fetch(self, revision_id=None, pb=None):
1645
 
        """See InterRepository.fetch()."""
1646
 
        from bzrlib.fetch import Model1toKnit2Fetcher
1647
 
        # TODO: jam 20070210 This should be an assert, not a translate
1648
 
        revision_id = osutils.safe_revision_id(revision_id)
1649
 
        f = Model1toKnit2Fetcher(to_repository=self.target,
1650
 
                                 from_repository=self.source,
1651
 
                                 last_revision=revision_id,
1652
 
                                 pb=pb)
1653
 
        return f.count_copied, f.failed_revisions
1654
 
 
1655
 
    @needs_write_lock
1656
 
    def copy_content(self, revision_id=None):
1657
 
        """Make a complete copy of the content in self into destination.
1658
 
        
1659
 
        This is a destructive operation! Do not use it on existing 
1660
 
        repositories.
1661
 
 
1662
 
        :param revision_id: Only copy the content needed to construct
1663
 
                            revision_id and its parents.
1664
 
        """
1665
 
        try:
1666
 
            self.target.set_make_working_trees(self.source.make_working_trees())
1667
 
        except NotImplementedError:
1668
 
            pass
1669
 
        # TODO: jam 20070210 Internal, assert, don't translate
1670
 
        revision_id = osutils.safe_revision_id(revision_id)
1671
 
        # but don't bother fetching if we have the needed data now.
1672
 
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
1673
 
            self.target.has_revision(revision_id)):
1674
 
            return
1675
 
        self.target.fetch(self.source, revision_id=revision_id)
1676
 
 
1677
 
 
1678
 
class InterKnit1and2(InterKnitRepo):
1679
 
 
1680
 
    @classmethod
1681
 
    def _get_repo_format_to_test(self):
1682
 
        return None
1683
 
 
1684
 
    @staticmethod
1685
 
    def is_compatible(source, target):
1686
 
        """Be compatible with Knit1 source and Knit3 target"""
1687
 
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
1688
 
        try:
1689
 
            from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
1690
 
                    RepositoryFormatKnit3
1691
 
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
1692
 
                    isinstance(target._format, (RepositoryFormatKnit3)))
1693
 
        except AttributeError:
1694
 
            return False
1695
 
 
1696
 
    @needs_write_lock
1697
 
    def fetch(self, revision_id=None, pb=None):
1698
 
        """See InterRepository.fetch()."""
1699
 
        from bzrlib.fetch import Knit1to2Fetcher
1700
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1701
 
               self.source, self.source._format, self.target, 
1702
 
               self.target._format)
1703
 
        # TODO: jam 20070210 This should be an assert, not a translate
1704
 
        revision_id = osutils.safe_revision_id(revision_id)
1705
 
        f = Knit1to2Fetcher(to_repository=self.target,
1706
 
                            from_repository=self.source,
1707
 
                            last_revision=revision_id,
1708
 
                            pb=pb)
1709
 
        return f.count_copied, f.failed_revisions
1710
 
 
1711
 
 
1712
 
class InterRemoteRepository(InterRepository):
1713
 
    """Code for converting between RemoteRepository objects.
1714
 
 
1715
 
    This just gets an non-remote repository from the RemoteRepository, and calls
1716
 
    InterRepository.get again.
1717
 
    """
1718
 
 
1719
 
    def __init__(self, source, target):
1720
 
        if isinstance(source, remote.RemoteRepository):
1721
 
            source._ensure_real()
1722
 
            real_source = source._real_repository
1723
 
        else:
1724
 
            real_source = source
1725
 
        if isinstance(target, remote.RemoteRepository):
1726
 
            target._ensure_real()
1727
 
            real_target = target._real_repository
1728
 
        else:
1729
 
            real_target = target
1730
 
        self.real_inter = InterRepository.get(real_source, real_target)
1731
 
 
1732
 
    @staticmethod
1733
 
    def is_compatible(source, target):
1734
 
        if isinstance(source, remote.RemoteRepository):
1735
 
            return True
1736
 
        if isinstance(target, remote.RemoteRepository):
1737
 
            return True
1738
 
        return False
1739
 
 
1740
 
    def copy_content(self, revision_id=None):
1741
 
        self.real_inter.copy_content(revision_id=revision_id)
1742
 
 
1743
 
    def fetch(self, revision_id=None, pb=None):
1744
 
        self.real_inter.fetch(revision_id=revision_id, pb=pb)
1745
 
 
1746
 
    @classmethod
1747
 
    def _get_repo_format_to_test(self):
1748
 
        return None
1749
 
 
1750
 
 
1751
 
InterRepository.register_optimiser(InterSameDataRepository)
1752
1811
InterRepository.register_optimiser(InterWeaveRepo)
1753
1812
InterRepository.register_optimiser(InterKnitRepo)
1754
 
InterRepository.register_optimiser(InterModel1and2)
1755
 
InterRepository.register_optimiser(InterKnit1and2)
1756
 
InterRepository.register_optimiser(InterRemoteRepository)
1757
1813
 
1758
1814
 
1759
1815
class RepositoryTestProviderAdapter(object):
1765
1821
    to make it easy to identify.
1766
1822
    """
1767
1823
 
1768
 
    def __init__(self, transport_server, transport_readonly_server, formats,
1769
 
                 vfs_transport_factory=None):
 
1824
    def __init__(self, transport_server, transport_readonly_server, formats):
1770
1825
        self._transport_server = transport_server
1771
1826
        self._transport_readonly_server = transport_readonly_server
1772
 
        self._vfs_transport_factory = vfs_transport_factory
1773
1827
        self._formats = formats
1774
1828
    
1775
1829
    def adapt(self, test):
1776
 
        result = unittest.TestSuite()
 
1830
        result = TestSuite()
1777
1831
        for repository_format, bzrdir_format in self._formats:
1778
 
            from copy import deepcopy
1779
1832
            new_test = deepcopy(test)
1780
1833
            new_test.transport_server = self._transport_server
1781
1834
            new_test.transport_readonly_server = self._transport_readonly_server
1782
 
            # Only override the test's vfs_transport_factory if one was
1783
 
            # specified, otherwise just leave the default in place.
1784
 
            if self._vfs_transport_factory:
1785
 
                new_test.vfs_transport_factory = self._vfs_transport_factory
1786
1835
            new_test.bzrdir_format = bzrdir_format
1787
1836
            new_test.repository_format = repository_format
1788
1837
            def make_new_test_id():
1808
1857
        self._formats = formats
1809
1858
    
1810
1859
    def adapt(self, test):
1811
 
        result = unittest.TestSuite()
 
1860
        result = TestSuite()
1812
1861
        for interrepo_class, repository_format, repository_format_to in self._formats:
1813
 
            from copy import deepcopy
1814
1862
            new_test = deepcopy(test)
1815
1863
            new_test.transport_server = self._transport_server
1816
1864
            new_test.transport_readonly_server = self._transport_readonly_server
1827
1875
    @staticmethod
1828
1876
    def default_test_list():
1829
1877
        """Generate the default list of interrepo permutations to test."""
1830
 
        from bzrlib.repofmt import knitrepo, weaverepo
1831
1878
        result = []
1832
1879
        # test the default InterRepository between format 6 and the current 
1833
1880
        # default format.
1834
1881
        # XXX: robertc 20060220 reinstate this when there are two supported
1835
1882
        # formats which do not have an optimal code path between them.
1836
 
        #result.append((InterRepository,
1837
 
        #               RepositoryFormat6(),
1838
 
        #               RepositoryFormatKnit1()))
1839
 
        for optimiser_class in InterRepository._optimisers:
1840
 
            format_to_test = optimiser_class._get_repo_format_to_test()
1841
 
            if format_to_test is not None:
1842
 
                result.append((optimiser_class,
1843
 
                               format_to_test, format_to_test))
 
1883
        result.append((InterRepository,
 
1884
                       RepositoryFormat6(),
 
1885
                       RepositoryFormatKnit1()))
 
1886
        for optimiser in InterRepository._optimisers:
 
1887
            result.append((optimiser,
 
1888
                           optimiser._matching_repo_format,
 
1889
                           optimiser._matching_repo_format
 
1890
                           ))
1844
1891
        # if there are specific combinations we want to use, we can add them 
1845
1892
        # here.
1846
 
        result.append((InterModel1and2,
1847
 
                       weaverepo.RepositoryFormat5(),
1848
 
                       knitrepo.RepositoryFormatKnit3()))
1849
 
        result.append((InterKnit1and2,
1850
 
                       knitrepo.RepositoryFormatKnit1(),
1851
 
                       knitrepo.RepositoryFormatKnit3()))
1852
1893
        return result
1853
1894
 
1854
1895
 
1881
1922
        self.step('Moving repository to repository.backup')
1882
1923
        self.repo_dir.transport.move('repository', 'repository.backup')
1883
1924
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
1884
 
        repo._format.check_conversion_target(self.target_format)
1885
1925
        self.source_repo = repo._format.open(self.repo_dir,
1886
1926
            _found=True,
1887
1927
            _override_transport=backup_transport)
1910
1950
    This allows describing a tree to be committed without needing to 
1911
1951
    know the internals of the format of the repository.
1912
1952
    """
1913
 
    
1914
 
    record_root_entry = False
1915
1953
    def __init__(self, repository, parents, config, timestamp=None, 
1916
1954
                 timezone=None, committer=None, revprops=None, 
1917
1955
                 revision_id=None):
1934
1972
            assert isinstance(committer, basestring), type(committer)
1935
1973
            self._committer = committer
1936
1974
 
1937
 
        self.new_inventory = Inventory(None)
1938
 
        self._new_revision_id = osutils.safe_revision_id(revision_id)
 
1975
        self.new_inventory = Inventory()
 
1976
        self._new_revision_id = revision_id
1939
1977
        self.parents = parents
1940
1978
        self.repository = repository
1941
1979
 
1949
1987
        self._timestamp = round(timestamp, 3)
1950
1988
 
1951
1989
        if timezone is None:
1952
 
            self._timezone = osutils.local_time_offset()
 
1990
            self._timezone = local_time_offset()
1953
1991
        else:
1954
1992
            self._timezone = int(timezone)
1955
1993
 
1960
1998
 
1961
1999
        :return: The revision id of the recorded revision.
1962
2000
        """
1963
 
        rev = _mod_revision.Revision(
1964
 
                       timestamp=self._timestamp,
 
2001
        rev = Revision(timestamp=self._timestamp,
1965
2002
                       timezone=self._timezone,
1966
2003
                       committer=self._committer,
1967
2004
                       message=message,
1973
2010
            self.new_inventory, self._config)
1974
2011
        return self._new_revision_id
1975
2012
 
1976
 
    def revision_tree(self):
1977
 
        """Return the tree that was just committed.
1978
 
 
1979
 
        After calling commit() this can be called to get a RevisionTree
1980
 
        representing the newly committed tree. This is preferred to
1981
 
        calling Repository.revision_tree() because that may require
1982
 
        deserializing the inventory, while we already have a copy in
1983
 
        memory.
1984
 
        """
1985
 
        return RevisionTree(self.repository, self.new_inventory,
1986
 
                            self._new_revision_id)
1987
 
 
1988
2013
    def finish_inventory(self):
1989
2014
        """Tell the builder that the inventory is finished."""
1990
 
        if self.new_inventory.root is None:
1991
 
            symbol_versioning.warn('Root entry should be supplied to'
1992
 
                ' record_entry_contents, as of bzr 0.10.',
1993
 
                 DeprecationWarning, stacklevel=2)
1994
 
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
1995
2015
        self.new_inventory.revision_id = self._new_revision_id
1996
2016
        self.inv_sha1 = self.repository.add_inventory(
1997
2017
            self._new_revision_id,
2001
2021
 
2002
2022
    def _gen_revision_id(self):
2003
2023
        """Return new revision-id."""
2004
 
        return generate_ids.gen_revision_id(self._config.username(),
2005
 
                                            self._timestamp)
 
2024
        s = '%s-%s-' % (self._config.user_email(), 
 
2025
                        compact_date(self._timestamp))
 
2026
        s += hexlify(rand_bytes(8))
 
2027
        return s
2006
2028
 
2007
2029
    def _generate_revision_if_needed(self):
2008
2030
        """Create a revision id if None was supplied.
2009
2031
        
2010
2032
        If the repository can not support user-specified revision ids
2011
 
        they should override this function and raise CannotSetRevisionId
 
2033
        they should override this function and raise UnsupportedOperation
2012
2034
        if _new_revision_id is not None.
2013
2035
 
2014
 
        :raises: CannotSetRevisionId
 
2036
        :raises: UnsupportedOperation
2015
2037
        """
2016
2038
        if self._new_revision_id is None:
2017
2039
            self._new_revision_id = self._gen_revision_id()
2019
2041
    def record_entry_contents(self, ie, parent_invs, path, tree):
2020
2042
        """Record the content of ie from tree into the commit if needed.
2021
2043
 
2022
 
        Side effect: sets ie.revision when unchanged
2023
 
 
2024
2044
        :param ie: An inventory entry present in the commit.
2025
2045
        :param parent_invs: The inventories of the parent revisions of the
2026
2046
            commit.
2028
2048
        :param tree: The tree which contains this entry and should be used to 
2029
2049
        obtain content.
2030
2050
        """
2031
 
        if self.new_inventory.root is None and ie.parent_id is not None:
2032
 
            symbol_versioning.warn('Root entry should be supplied to'
2033
 
                ' record_entry_contents, as of bzr 0.10.',
2034
 
                 DeprecationWarning, stacklevel=2)
2035
 
            self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
2036
 
                                       '', tree)
2037
2051
        self.new_inventory.add(ie)
2038
2052
 
2039
2053
        # ie.revision is always None if the InventoryEntry is considered
2041
2055
        # which may be the sole parent if it is untouched.
2042
2056
        if ie.revision is not None:
2043
2057
            return
2044
 
 
2045
 
        # In this revision format, root entries have no knit or weave
2046
 
        if ie is self.new_inventory.root:
2047
 
            # When serializing out to disk and back in
2048
 
            # root.revision is always _new_revision_id
2049
 
            ie.revision = self._new_revision_id
2050
 
            return
2051
2058
        previous_entries = ie.find_previous_heads(
2052
2059
            parent_invs,
2053
2060
            self.repository.weave_store,
2063
2070
        :param file_parents: The per-file parent revision ids.
2064
2071
        """
2065
2072
        self._add_text_to_weave(file_id, [], file_parents.keys())
2066
 
 
2067
 
    def modified_reference(self, file_id, file_parents):
2068
 
        """Record the modification of a reference.
2069
 
 
2070
 
        :param file_id: The file_id of the link to record.
2071
 
        :param file_parents: The per-file parent revision ids.
2072
 
        """
2073
 
        self._add_text_to_weave(file_id, [], file_parents.keys())
2074
2073
    
2075
2074
    def modified_file_text(self, file_id, file_parents,
2076
2075
                           get_content_byte_lines, text_sha1=None,
2121
2120
        versionedfile.clear_cache()
2122
2121
 
2123
2122
 
2124
 
class _CommitBuilder(CommitBuilder):
2125
 
    """Temporary class so old CommitBuilders are detected properly
2126
 
    
2127
 
    Note: CommitBuilder works whether or not root entry is recorded.
2128
 
    """
2129
 
 
2130
 
    record_root_entry = True
2131
 
 
2132
 
 
2133
 
class RootCommitBuilder(CommitBuilder):
2134
 
    """This commitbuilder actually records the root id"""
2135
 
    
2136
 
    record_root_entry = True
2137
 
 
2138
 
    def record_entry_contents(self, ie, parent_invs, path, tree):
2139
 
        """Record the content of ie from tree into the commit if needed.
2140
 
 
2141
 
        Side effect: sets ie.revision when unchanged
2142
 
 
2143
 
        :param ie: An inventory entry present in the commit.
2144
 
        :param parent_invs: The inventories of the parent revisions of the
2145
 
            commit.
2146
 
        :param path: The path the entry is at in the tree.
2147
 
        :param tree: The tree which contains this entry and should be used to 
2148
 
        obtain content.
2149
 
        """
2150
 
        assert self.new_inventory.root is not None or ie.parent_id is None
2151
 
        self.new_inventory.add(ie)
2152
 
 
2153
 
        # ie.revision is always None if the InventoryEntry is considered
2154
 
        # for committing. ie.snapshot will record the correct revision 
2155
 
        # which may be the sole parent if it is untouched.
2156
 
        if ie.revision is not None:
2157
 
            return
2158
 
 
2159
 
        previous_entries = ie.find_previous_heads(
2160
 
            parent_invs,
2161
 
            self.repository.weave_store,
2162
 
            self.repository.get_transaction())
2163
 
        # we are creating a new revision for ie in the history store
2164
 
        # and inventory.
2165
 
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2166
 
 
2167
 
 
2168
2123
_unescape_map = {
2169
2124
    'apos':"'",
2170
2125
    'quot':'"',
2175
2130
 
2176
2131
 
2177
2132
def _unescaper(match, _map=_unescape_map):
2178
 
    code = match.group(1)
2179
 
    try:
2180
 
        return _map[code]
2181
 
    except KeyError:
2182
 
        if not code.startswith('#'):
2183
 
            raise
2184
 
        return unichr(int(code[1:])).encode('utf8')
 
2133
    return _map[match.group(1)]
2185
2134
 
2186
2135
 
2187
2136
_unescape_re = None
2191
2140
    """Unescape predefined XML entities in a string of data."""
2192
2141
    global _unescape_re
2193
2142
    if _unescape_re is None:
2194
 
        _unescape_re = re.compile('\&([^;]*);')
 
2143
        _unescape_re = re.compile('\&([^;]*);')
2195
2144
    return _unescape_re.sub(_unescaper, data)