/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/repository.py

  • Committer: Jelmer Vernooij
  • Date: 2019-03-13 23:24:13 UTC
  • mto: (7290.1.23 work)
  • mto: This revision was merged to the branch mainline in revision 7311.
  • Revision ID: jelmer@jelmer.uk-20190313232413-y1c951be4surcc9g
Fix formatting.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2011 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
from __future__ import absolute_import
 
18
 
 
19
from .lazy_import import lazy_import
 
20
lazy_import(globals(), """
 
21
import time
 
22
 
 
23
from breezy import (
 
24
    config,
 
25
    controldir,
 
26
    debug,
 
27
    graph,
 
28
    osutils,
 
29
    revision as _mod_revision,
 
30
    gpg,
 
31
    )
 
32
from breezy.bundle import serializer
 
33
from breezy.i18n import gettext
 
34
""")
 
35
 
 
36
from . import (
 
37
    errors,
 
38
    registry,
 
39
    ui,
 
40
    )
 
41
from .decorators import only_raises
 
42
from .inter import InterObject
 
43
from .lock import _RelockDebugMixin, LogicalLockResult
 
44
from .sixish import (
 
45
    text_type,
 
46
    viewitems,
 
47
    )
 
48
from .trace import (
 
49
    log_exception_quietly, note, mutter, mutter_callsite, warning)
 
50
 
 
51
 
 
52
# Old formats display a warning, but only once
 
53
_deprecation_warning_done = False
 
54
 
 
55
 
 
56
class IsInWriteGroupError(errors.InternalBzrError):
 
57
 
 
58
    _fmt = "May not refresh_data of repo %(repo)s while in a write group."
 
59
 
 
60
    def __init__(self, repo):
 
61
        errors.InternalBzrError.__init__(self, repo=repo)
 
62
 
 
63
 
 
64
class CannotSetRevisionId(errors.BzrError):
 
65
 
 
66
    _fmt = "Repository format does not support setting revision ids."
 
67
 
 
68
 
 
69
class CommitBuilder(object):
 
70
    """Provides an interface to build up a commit.
 
71
 
 
72
    This allows describing a tree to be committed without needing to
 
73
    know the internals of the format of the repository.
 
74
    """
 
75
 
 
76
    # all clients should supply tree roots.
 
77
    record_root_entry = True
 
78
    # whether this commit builder will automatically update the branch that is
 
79
    # being committed to
 
80
    updates_branch = False
 
81
 
 
82
    def __init__(self, repository, parents, config_stack, timestamp=None,
 
83
                 timezone=None, committer=None, revprops=None,
 
84
                 revision_id=None, lossy=False):
 
85
        """Initiate a CommitBuilder.
 
86
 
 
87
        :param repository: Repository to commit to.
 
88
        :param parents: Revision ids of the parents of the new revision.
 
89
        :param timestamp: Optional timestamp recorded for commit.
 
90
        :param timezone: Optional timezone for timestamp.
 
91
        :param committer: Optional committer to set for commit.
 
92
        :param revprops: Optional dictionary of revision properties.
 
93
        :param revision_id: Optional revision id.
 
94
        :param lossy: Whether to discard data that can not be natively
 
95
            represented, when pushing to a foreign VCS
 
96
        """
 
97
        self._config_stack = config_stack
 
98
        self._lossy = lossy
 
99
 
 
100
        if committer is None:
 
101
            self._committer = self._config_stack.get('email')
 
102
        elif not isinstance(committer, text_type):
 
103
            self._committer = committer.decode()  # throw if non-ascii
 
104
        else:
 
105
            self._committer = committer
 
106
 
 
107
        self.parents = parents
 
108
        self.repository = repository
 
109
 
 
110
        self._revprops = {}
 
111
        if revprops is not None:
 
112
            self._validate_revprops(revprops)
 
113
            self._revprops.update(revprops)
 
114
 
 
115
        if timestamp is None:
 
116
            timestamp = time.time()
 
117
        # Restrict resolution to 1ms
 
118
        self._timestamp = round(timestamp, 3)
 
119
 
 
120
        if timezone is None:
 
121
            self._timezone = osutils.local_time_offset()
 
122
        else:
 
123
            self._timezone = int(timezone)
 
124
 
 
125
        self._generate_revision_if_needed(revision_id)
 
126
 
 
127
    def any_changes(self):
 
128
        """Return True if any entries were changed.
 
129
 
 
130
        This includes merge-only changes. It is the core for the --unchanged
 
131
        detection in commit.
 
132
 
 
133
        :return: True if any changes have occured.
 
134
        """
 
135
        raise NotImplementedError(self.any_changes)
 
136
 
 
137
    def _validate_unicode_text(self, text, context):
 
138
        """Verify things like commit messages don't have bogus characters."""
 
139
        # TODO(jelmer): Make this repository-format specific
 
140
        if u'\r' in text:
 
141
            raise ValueError('Invalid value for %s: %r' % (context, text))
 
142
 
 
143
    def _validate_revprops(self, revprops):
 
144
        for key, value in viewitems(revprops):
 
145
            # We know that the XML serializers do not round trip '\r'
 
146
            # correctly, so refuse to accept them
 
147
            if not isinstance(value, (text_type, str)):
 
148
                raise ValueError('revision property (%s) is not a valid'
 
149
                                 ' (unicode) string: %r' % (key, value))
 
150
            # TODO(jelmer): Make this repository-format specific
 
151
            self._validate_unicode_text(value,
 
152
                                        'revision property (%s)' % (key,))
 
153
 
 
154
    def commit(self, message):
 
155
        """Make the actual commit.
 
156
 
 
157
        :return: The revision id of the recorded revision.
 
158
        """
 
159
        raise NotImplementedError(self.commit)
 
160
 
 
161
    def abort(self):
 
162
        """Abort the commit that is being built.
 
163
        """
 
164
        raise NotImplementedError(self.abort)
 
165
 
 
166
    def revision_tree(self):
 
167
        """Return the tree that was just committed.
 
168
 
 
169
        After calling commit() this can be called to get a
 
170
        RevisionTree representing the newly committed tree. This is
 
171
        preferred to calling Repository.revision_tree() because that may
 
172
        require deserializing the inventory, while we already have a copy in
 
173
        memory.
 
174
        """
 
175
        raise NotImplementedError(self.revision_tree)
 
176
 
 
177
    def finish_inventory(self):
 
178
        """Tell the builder that the inventory is finished.
 
179
 
 
180
        :return: The inventory id in the repository, which can be used with
 
181
            repository.get_inventory.
 
182
        """
 
183
        raise NotImplementedError(self.finish_inventory)
 
184
 
 
185
    def _generate_revision_if_needed(self, revision_id):
 
186
        """Create a revision id if None was supplied.
 
187
 
 
188
        If the repository can not support user-specified revision ids
 
189
        they should override this function and raise CannotSetRevisionId
 
190
        if _new_revision_id is not None.
 
191
 
 
192
        :raises: CannotSetRevisionId
 
193
        """
 
194
        if not self.repository._format.supports_setting_revision_ids:
 
195
            if revision_id is not None:
 
196
                raise CannotSetRevisionId()
 
197
            return
 
198
        if revision_id is None:
 
199
            self._new_revision_id = self._gen_revision_id()
 
200
            self.random_revid = True
 
201
        else:
 
202
            self._new_revision_id = revision_id
 
203
            self.random_revid = False
 
204
 
 
205
    def record_iter_changes(self, tree, basis_revision_id, iter_changes):
 
206
        """Record a new tree via iter_changes.
 
207
 
 
208
        :param tree: The tree to obtain text contents from for changed objects.
 
209
        :param basis_revision_id: The revision id of the tree the iter_changes
 
210
            has been generated against. Currently assumed to be the same
 
211
            as self.parents[0] - if it is not, errors may occur.
 
212
        :param iter_changes: An iter_changes iterator with the changes to apply
 
213
            to basis_revision_id. The iterator must not include any items with
 
214
            a current kind of None - missing items must be either filtered out
 
215
            or errored-on beefore record_iter_changes sees the item.
 
216
        :return: A generator of (relpath, fs_hash) tuples for use with
 
217
            tree._observed_sha1.
 
218
        """
 
219
        raise NotImplementedError(self.record_iter_changes)
 
220
 
 
221
 
 
222
class RepositoryWriteLockResult(LogicalLockResult):
 
223
    """The result of write locking a repository.
 
224
 
 
225
    :ivar repository_token: The token obtained from the underlying lock, or
 
226
        None.
 
227
    :ivar unlock: A callable which will unlock the lock.
 
228
    """
 
229
 
 
230
    def __init__(self, unlock, repository_token):
 
231
        LogicalLockResult.__init__(self, unlock)
 
232
        self.repository_token = repository_token
 
233
 
 
234
    def __repr__(self):
 
235
        return "RepositoryWriteLockResult(%s, %s)" % (self.repository_token,
 
236
                                                      self.unlock)
 
237
 
 
238
 
 
239
######################################################################
 
240
# Repositories
 
241
 
 
242
 
 
243
class Repository(controldir.ControlComponent, _RelockDebugMixin):
 
244
    """Repository holding history for one or more branches.
 
245
 
 
246
    The repository holds and retrieves historical information including
 
247
    revisions and file history.  It's normally accessed only by the Branch,
 
248
    which views a particular line of development through that history.
 
249
 
 
250
    See VersionedFileRepository in breezy.vf_repository for the
 
251
    base class for most Bazaar repositories.
 
252
    """
 
253
 
 
254
    # Does this repository implementation support random access to
 
255
    # items in the tree, or just bulk fetching/pushing of data?
 
256
    supports_random_access = True
 
257
 
 
258
    def abort_write_group(self, suppress_errors=False):
 
259
        """Commit the contents accrued within the current write group.
 
260
 
 
261
        :param suppress_errors: if true, abort_write_group will catch and log
 
262
            unexpected errors that happen during the abort, rather than
 
263
            allowing them to propagate.  Defaults to False.
 
264
 
 
265
        :seealso: start_write_group.
 
266
        """
 
267
        if self._write_group is not self.get_transaction():
 
268
            # has an unlock or relock occured ?
 
269
            if suppress_errors:
 
270
                mutter(
 
271
                    '(suppressed) mismatched lock context and write group. %r, %r',
 
272
                    self._write_group, self.get_transaction())
 
273
                return
 
274
            raise errors.BzrError(
 
275
                'mismatched lock context and write group. %r, %r' %
 
276
                (self._write_group, self.get_transaction()))
 
277
        try:
 
278
            self._abort_write_group()
 
279
        except Exception as exc:
 
280
            self._write_group = None
 
281
            if not suppress_errors:
 
282
                raise
 
283
            mutter('abort_write_group failed')
 
284
            log_exception_quietly()
 
285
            note(gettext('brz: ERROR (ignored): %s'), exc)
 
286
        self._write_group = None
 
287
 
 
288
    def _abort_write_group(self):
 
289
        """Template method for per-repository write group cleanup.
 
290
 
 
291
        This is called during abort before the write group is considered to be
 
292
        finished and should cleanup any internal state accrued during the write
 
293
        group. There is no requirement that data handed to the repository be
 
294
        *not* made available - this is not a rollback - but neither should any
 
295
        attempt be made to ensure that data added is fully commited. Abort is
 
296
        invoked when an error has occured so futher disk or network operations
 
297
        may not be possible or may error and if possible should not be
 
298
        attempted.
 
299
        """
 
300
 
 
301
    def add_fallback_repository(self, repository):
 
302
        """Add a repository to use for looking up data not held locally.
 
303
 
 
304
        :param repository: A repository.
 
305
        """
 
306
        raise NotImplementedError(self.add_fallback_repository)
 
307
 
 
308
    def _check_fallback_repository(self, repository):
 
309
        """Check that this repository can fallback to repository safely.
 
310
 
 
311
        Raise an error if not.
 
312
 
 
313
        :param repository: A repository to fallback to.
 
314
        """
 
315
        return InterRepository._assert_same_model(self, repository)
 
316
 
 
317
    def all_revision_ids(self):
 
318
        """Returns a list of all the revision ids in the repository.
 
319
 
 
320
        This is conceptually deprecated because code should generally work on
 
321
        the graph reachable from a particular revision, and ignore any other
 
322
        revisions that might be present.  There is no direct replacement
 
323
        method.
 
324
        """
 
325
        if 'evil' in debug.debug_flags:
 
326
            mutter_callsite(2, "all_revision_ids is linear with history.")
 
327
        return self._all_revision_ids()
 
328
 
 
329
    def _all_revision_ids(self):
 
330
        """Returns a list of all the revision ids in the repository.
 
331
 
 
332
        These are in as much topological order as the underlying store can
 
333
        present.
 
334
        """
 
335
        raise NotImplementedError(self._all_revision_ids)
 
336
 
 
337
    def break_lock(self):
 
338
        """Break a lock if one is present from another instance.
 
339
 
 
340
        Uses the ui factory to ask for confirmation if the lock may be from
 
341
        an active process.
 
342
        """
 
343
        self.control_files.break_lock()
 
344
 
 
345
    @staticmethod
 
346
    def create(controldir):
 
347
        """Construct the current default format repository in controldir."""
 
348
        return RepositoryFormat.get_default_format().initialize(controldir)
 
349
 
 
350
    def __init__(self, _format, controldir, control_files):
 
351
        """instantiate a Repository.
 
352
 
 
353
        :param _format: The format of the repository on disk.
 
354
        :param controldir: The ControlDir of the repository.
 
355
        :param control_files: Control files to use for locking, etc.
 
356
        """
 
357
        # In the future we will have a single api for all stores for
 
358
        # getting file texts, inventories and revisions, then
 
359
        # this construct will accept instances of those things.
 
360
        super(Repository, self).__init__()
 
361
        self._format = _format
 
362
        # the following are part of the public API for Repository:
 
363
        self.controldir = controldir
 
364
        self.control_files = control_files
 
365
        # for tests
 
366
        self._write_group = None
 
367
        # Additional places to query for data.
 
368
        self._fallback_repositories = []
 
369
 
 
370
    @property
 
371
    def user_transport(self):
 
372
        return self.controldir.user_transport
 
373
 
 
374
    @property
 
375
    def control_transport(self):
 
376
        return self._transport
 
377
 
 
378
    def __repr__(self):
 
379
        if self._fallback_repositories:
 
380
            return '%s(%r, fallback_repositories=%r)' % (
 
381
                self.__class__.__name__,
 
382
                self.base,
 
383
                self._fallback_repositories)
 
384
        else:
 
385
            return '%s(%r)' % (self.__class__.__name__,
 
386
                               self.base)
 
387
 
 
388
    def _has_same_fallbacks(self, other_repo):
 
389
        """Returns true if the repositories have the same fallbacks."""
 
390
        my_fb = self._fallback_repositories
 
391
        other_fb = other_repo._fallback_repositories
 
392
        if len(my_fb) != len(other_fb):
 
393
            return False
 
394
        for f, g in zip(my_fb, other_fb):
 
395
            if not f.has_same_location(g):
 
396
                return False
 
397
        return True
 
398
 
 
399
    def has_same_location(self, other):
 
400
        """Returns a boolean indicating if this repository is at the same
 
401
        location as another repository.
 
402
 
 
403
        This might return False even when two repository objects are accessing
 
404
        the same physical repository via different URLs.
 
405
        """
 
406
        if self.__class__ is not other.__class__:
 
407
            return False
 
408
        return (self.control_url == other.control_url)
 
409
 
 
410
    def is_in_write_group(self):
 
411
        """Return True if there is an open write group.
 
412
 
 
413
        :seealso: start_write_group.
 
414
        """
 
415
        return self._write_group is not None
 
416
 
 
417
    def is_locked(self):
 
418
        return self.control_files.is_locked()
 
419
 
 
420
    def is_write_locked(self):
 
421
        """Return True if this object is write locked."""
 
422
        return self.is_locked() and self.control_files._lock_mode == 'w'
 
423
 
 
424
    def lock_write(self, token=None):
 
425
        """Lock this repository for writing.
 
426
 
 
427
        This causes caching within the repository obejct to start accumlating
 
428
        data during reads, and allows a 'write_group' to be obtained. Write
 
429
        groups must be used for actual data insertion.
 
430
 
 
431
        A token should be passed in if you know that you have locked the object
 
432
        some other way, and need to synchronise this object's state with that
 
433
        fact.
 
434
 
 
435
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
 
436
 
 
437
        :param token: if this is already locked, then lock_write will fail
 
438
            unless the token matches the existing lock.
 
439
        :returns: a token if this instance supports tokens, otherwise None.
 
440
        :raises TokenLockingNotSupported: when a token is given but this
 
441
            instance doesn't support using token locks.
 
442
        :raises MismatchedToken: if the specified token doesn't match the token
 
443
            of the existing lock.
 
444
        :seealso: start_write_group.
 
445
        :return: A RepositoryWriteLockResult.
 
446
        """
 
447
        locked = self.is_locked()
 
448
        token = self.control_files.lock_write(token=token)
 
449
        if not locked:
 
450
            self._warn_if_deprecated()
 
451
            self._note_lock('w')
 
452
            for repo in self._fallback_repositories:
 
453
                # Writes don't affect fallback repos
 
454
                repo.lock_read()
 
455
            self._refresh_data()
 
456
        return RepositoryWriteLockResult(self.unlock, token)
 
457
 
 
458
    def lock_read(self):
 
459
        """Lock the repository for read operations.
 
460
 
 
461
        :return: An object with an unlock method which will release the lock
 
462
            obtained.
 
463
        """
 
464
        locked = self.is_locked()
 
465
        self.control_files.lock_read()
 
466
        if not locked:
 
467
            self._warn_if_deprecated()
 
468
            self._note_lock('r')
 
469
            for repo in self._fallback_repositories:
 
470
                repo.lock_read()
 
471
            self._refresh_data()
 
472
        return LogicalLockResult(self.unlock)
 
473
 
 
474
    def get_physical_lock_status(self):
 
475
        return self.control_files.get_physical_lock_status()
 
476
 
 
477
    def leave_lock_in_place(self):
 
478
        """Tell this repository not to release the physical lock when this
 
479
        object is unlocked.
 
480
 
 
481
        If lock_write doesn't return a token, then this method is not supported.
 
482
        """
 
483
        self.control_files.leave_in_place()
 
484
 
 
485
    def dont_leave_lock_in_place(self):
 
486
        """Tell this repository to release the physical lock when this
 
487
        object is unlocked, even if it didn't originally acquire it.
 
488
 
 
489
        If lock_write doesn't return a token, then this method is not supported.
 
490
        """
 
491
        self.control_files.dont_leave_in_place()
 
492
 
 
493
    def gather_stats(self, revid=None, committers=None):
 
494
        """Gather statistics from a revision id.
 
495
 
 
496
        :param revid: The revision id to gather statistics from, if None, then
 
497
            no revision specific statistics are gathered.
 
498
        :param committers: Optional parameter controlling whether to grab
 
499
            a count of committers from the revision specific statistics.
 
500
        :return: A dictionary of statistics. Currently this contains:
 
501
            committers: The number of committers if requested.
 
502
            firstrev: A tuple with timestamp, timezone for the penultimate left
 
503
                most ancestor of revid, if revid is not the NULL_REVISION.
 
504
            latestrev: A tuple with timestamp, timezone for revid, if revid is
 
505
                not the NULL_REVISION.
 
506
            revisions: The total revision count in the repository.
 
507
            size: An estimate disk size of the repository in bytes.
 
508
        """
 
509
        with self.lock_read():
 
510
            result = {}
 
511
            if revid and committers:
 
512
                result['committers'] = 0
 
513
            if revid and revid != _mod_revision.NULL_REVISION:
 
514
                graph = self.get_graph()
 
515
                if committers:
 
516
                    all_committers = set()
 
517
                revisions = [r for (r, p) in graph.iter_ancestry([revid])
 
518
                             if r != _mod_revision.NULL_REVISION]
 
519
                last_revision = None
 
520
                if not committers:
 
521
                    # ignore the revisions in the middle - just grab first and last
 
522
                    revisions = revisions[0], revisions[-1]
 
523
                for revision in self.get_revisions(revisions):
 
524
                    if not last_revision:
 
525
                        last_revision = revision
 
526
                    if committers:
 
527
                        all_committers.add(revision.committer)
 
528
                first_revision = revision
 
529
                if committers:
 
530
                    result['committers'] = len(all_committers)
 
531
                result['firstrev'] = (first_revision.timestamp,
 
532
                                      first_revision.timezone)
 
533
                result['latestrev'] = (last_revision.timestamp,
 
534
                                       last_revision.timezone)
 
535
            return result
 
536
 
 
537
    def find_branches(self, using=False):
 
538
        """Find branches underneath this repository.
 
539
 
 
540
        This will include branches inside other branches.
 
541
 
 
542
        :param using: If True, list only branches using this repository.
 
543
        """
 
544
        if using and not self.is_shared():
 
545
            return self.controldir.list_branches()
 
546
 
 
547
        class Evaluator(object):
 
548
 
 
549
            def __init__(self):
 
550
                self.first_call = True
 
551
 
 
552
            def __call__(self, controldir):
 
553
                # On the first call, the parameter is always the controldir
 
554
                # containing the current repo.
 
555
                if not self.first_call:
 
556
                    try:
 
557
                        repository = controldir.open_repository()
 
558
                    except errors.NoRepositoryPresent:
 
559
                        pass
 
560
                    else:
 
561
                        return False, ([], repository)
 
562
                self.first_call = False
 
563
                value = (controldir.list_branches(), None)
 
564
                return True, value
 
565
 
 
566
        ret = []
 
567
        for branches, repository in controldir.ControlDir.find_controldirs(
 
568
                self.user_transport, evaluate=Evaluator()):
 
569
            if branches is not None:
 
570
                ret.extend(branches)
 
571
            if not using and repository is not None:
 
572
                ret.extend(repository.find_branches())
 
573
        return ret
 
574
 
 
575
    def search_missing_revision_ids(self, other,
 
576
                                    find_ghosts=True, revision_ids=None, if_present_ids=None,
 
577
                                    limit=None):
 
578
        """Return the revision ids that other has that this does not.
 
579
 
 
580
        These are returned in topological order.
 
581
 
 
582
        revision_ids: only return revision ids included by revision_id.
 
583
        """
 
584
        with self.lock_read():
 
585
            return InterRepository.get(other, self).search_missing_revision_ids(
 
586
                find_ghosts=find_ghosts, revision_ids=revision_ids,
 
587
                if_present_ids=if_present_ids, limit=limit)
 
588
 
 
589
    @staticmethod
 
590
    def open(base):
 
591
        """Open the repository rooted at base.
 
592
 
 
593
        For instance, if the repository is at URL/.bzr/repository,
 
594
        Repository.open(URL) -> a Repository instance.
 
595
        """
 
596
        control = controldir.ControlDir.open(base)
 
597
        return control.open_repository()
 
598
 
 
599
    def copy_content_into(self, destination, revision_id=None):
 
600
        """Make a complete copy of the content in self into destination.
 
601
 
 
602
        This is a destructive operation! Do not use it on existing
 
603
        repositories.
 
604
        """
 
605
        return InterRepository.get(self, destination).copy_content(revision_id)
 
606
 
 
607
    def commit_write_group(self):
 
608
        """Commit the contents accrued within the current write group.
 
609
 
 
610
        :seealso: start_write_group.
 
611
 
 
612
        :return: it may return an opaque hint that can be passed to 'pack'.
 
613
        """
 
614
        if self._write_group is not self.get_transaction():
 
615
            # has an unlock or relock occured ?
 
616
            raise errors.BzrError('mismatched lock context %r and '
 
617
                                  'write group %r.' %
 
618
                                  (self.get_transaction(), self._write_group))
 
619
        result = self._commit_write_group()
 
620
        self._write_group = None
 
621
        return result
 
622
 
 
623
    def _commit_write_group(self):
 
624
        """Template method for per-repository write group cleanup.
 
625
 
 
626
        This is called before the write group is considered to be
 
627
        finished and should ensure that all data handed to the repository
 
628
        for writing during the write group is safely committed (to the
 
629
        extent possible considering file system caching etc).
 
630
        """
 
631
 
 
632
    def suspend_write_group(self):
 
633
        """Suspend a write group.
 
634
 
 
635
        :raise UnsuspendableWriteGroup: If the write group can not be
 
636
            suspended.
 
637
        :return: List of tokens
 
638
        """
 
639
        raise errors.UnsuspendableWriteGroup(self)
 
640
 
 
641
    def refresh_data(self):
 
642
        """Re-read any data needed to synchronise with disk.
 
643
 
 
644
        This method is intended to be called after another repository instance
 
645
        (such as one used by a smart server) has inserted data into the
 
646
        repository. On all repositories this will work outside of write groups.
 
647
        Some repository formats (pack and newer for breezy native formats)
 
648
        support refresh_data inside write groups. If called inside a write
 
649
        group on a repository that does not support refreshing in a write group
 
650
        IsInWriteGroupError will be raised.
 
651
        """
 
652
        self._refresh_data()
 
653
 
 
654
    def resume_write_group(self, tokens):
 
655
        if not self.is_write_locked():
 
656
            raise errors.NotWriteLocked(self)
 
657
        if self._write_group:
 
658
            raise errors.BzrError('already in a write group')
 
659
        self._resume_write_group(tokens)
 
660
        # so we can detect unlock/relock - the write group is now entered.
 
661
        self._write_group = self.get_transaction()
 
662
 
 
663
    def _resume_write_group(self, tokens):
 
664
        raise errors.UnsuspendableWriteGroup(self)
 
665
 
 
666
    def fetch(self, source, revision_id=None, find_ghosts=False):
 
667
        """Fetch the content required to construct revision_id from source.
 
668
 
 
669
        If revision_id is None, then all content is copied.
 
670
 
 
671
        fetch() may not be used when the repository is in a write group -
 
672
        either finish the current write group before using fetch, or use
 
673
        fetch before starting the write group.
 
674
 
 
675
        :param find_ghosts: Find and copy revisions in the source that are
 
676
            ghosts in the target (and not reachable directly by walking out to
 
677
            the first-present revision in target from revision_id).
 
678
        :param revision_id: If specified, all the content needed for this
 
679
            revision ID will be copied to the target.  Fetch will determine for
 
680
            itself which content needs to be copied.
 
681
        """
 
682
        if self.is_in_write_group():
 
683
            raise errors.InternalBzrError(
 
684
                "May not fetch while in a write group.")
 
685
        # fast path same-url fetch operations
 
686
        # TODO: lift out to somewhere common with RemoteRepository
 
687
        # <https://bugs.launchpad.net/bzr/+bug/401646>
 
688
        if (self.has_same_location(source)
 
689
                and self._has_same_fallbacks(source)):
 
690
            # check that last_revision is in 'from' and then return a
 
691
            # no-operation.
 
692
            if (revision_id is not None and
 
693
                    not _mod_revision.is_null(revision_id)):
 
694
                self.get_revision(revision_id)
 
695
            return 0, []
 
696
        inter = InterRepository.get(source, self)
 
697
        return inter.fetch(revision_id=revision_id, find_ghosts=find_ghosts)
 
698
 
 
699
    def create_bundle(self, target, base, fileobj, format=None):
 
700
        return serializer.write_bundle(self, target, base, fileobj, format)
 
701
 
 
702
    def get_commit_builder(self, branch, parents, config_stack, timestamp=None,
 
703
                           timezone=None, committer=None, revprops=None,
 
704
                           revision_id=None, lossy=False):
 
705
        """Obtain a CommitBuilder for this repository.
 
706
 
 
707
        :param branch: Branch to commit to.
 
708
        :param parents: Revision ids of the parents of the new revision.
 
709
        :param config_stack: Configuration stack to use.
 
710
        :param timestamp: Optional timestamp recorded for commit.
 
711
        :param timezone: Optional timezone for timestamp.
 
712
        :param committer: Optional committer to set for commit.
 
713
        :param revprops: Optional dictionary of revision properties.
 
714
        :param revision_id: Optional revision id.
 
715
        :param lossy: Whether to discard data that can not be natively
 
716
            represented, when pushing to a foreign VCS
 
717
        """
 
718
        raise NotImplementedError(self.get_commit_builder)
 
719
 
 
720
    @only_raises(errors.LockNotHeld, errors.LockBroken)
 
721
    def unlock(self):
 
722
        if (self.control_files._lock_count == 1 and
 
723
                self.control_files._lock_mode == 'w'):
 
724
            if self._write_group is not None:
 
725
                self.abort_write_group()
 
726
                self.control_files.unlock()
 
727
                raise errors.BzrError(
 
728
                    'Must end write groups before releasing write locks.')
 
729
        self.control_files.unlock()
 
730
        if self.control_files._lock_count == 0:
 
731
            for repo in self._fallback_repositories:
 
732
                repo.unlock()
 
733
 
 
734
    def clone(self, controldir, revision_id=None):
 
735
        """Clone this repository into controldir using the current format.
 
736
 
 
737
        Currently no check is made that the format of this repository and
 
738
        the bzrdir format are compatible. FIXME RBC 20060201.
 
739
 
 
740
        :return: The newly created destination repository.
 
741
        """
 
742
        with self.lock_read():
 
743
            # TODO: deprecate after 0.16; cloning this with all its settings is
 
744
            # probably not very useful -- mbp 20070423
 
745
            dest_repo = self._create_sprouting_repo(
 
746
                controldir, shared=self.is_shared())
 
747
            self.copy_content_into(dest_repo, revision_id)
 
748
            return dest_repo
 
749
 
 
750
    def start_write_group(self):
 
751
        """Start a write group in the repository.
 
752
 
 
753
        Write groups are used by repositories which do not have a 1:1 mapping
 
754
        between file ids and backend store to manage the insertion of data from
 
755
        both fetch and commit operations.
 
756
 
 
757
        A write lock is required around the
 
758
        start_write_group/commit_write_group for the support of lock-requiring
 
759
        repository formats.
 
760
 
 
761
        One can only insert data into a repository inside a write group.
 
762
 
 
763
        :return: None.
 
764
        """
 
765
        if not self.is_write_locked():
 
766
            raise errors.NotWriteLocked(self)
 
767
        if self._write_group:
 
768
            raise errors.BzrError('already in a write group')
 
769
        self._start_write_group()
 
770
        # so we can detect unlock/relock - the write group is now entered.
 
771
        self._write_group = self.get_transaction()
 
772
 
 
773
    def _start_write_group(self):
 
774
        """Template method for per-repository write group startup.
 
775
 
 
776
        This is called before the write group is considered to be
 
777
        entered.
 
778
        """
 
779
 
 
780
    def sprout(self, to_bzrdir, revision_id=None):
 
781
        """Create a descendent repository for new development.
 
782
 
 
783
        Unlike clone, this does not copy the settings of the repository.
 
784
        """
 
785
        with self.lock_read():
 
786
            dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
 
787
            dest_repo.fetch(self, revision_id=revision_id)
 
788
            return dest_repo
 
789
 
 
790
    def _create_sprouting_repo(self, a_controldir, shared):
 
791
        if not isinstance(
 
792
                a_controldir._format, self.controldir._format.__class__):
 
793
            # use target default format.
 
794
            dest_repo = a_controldir.create_repository()
 
795
        else:
 
796
            # Most control formats need the repository to be specifically
 
797
            # created, but on some old all-in-one formats it's not needed
 
798
            try:
 
799
                dest_repo = self._format.initialize(
 
800
                    a_controldir, shared=shared)
 
801
            except errors.UninitializableFormat:
 
802
                dest_repo = a_controldir.open_repository()
 
803
        return dest_repo
 
804
 
 
805
    def has_revision(self, revision_id):
 
806
        """True if this repository has a copy of the revision."""
 
807
        with self.lock_read():
 
808
            return revision_id in self.has_revisions((revision_id,))
 
809
 
 
810
    def has_revisions(self, revision_ids):
 
811
        """Probe to find out the presence of multiple revisions.
 
812
 
 
813
        :param revision_ids: An iterable of revision_ids.
 
814
        :return: A set of the revision_ids that were present.
 
815
        """
 
816
        raise NotImplementedError(self.has_revisions)
 
817
 
 
818
    def get_revision(self, revision_id):
 
819
        """Return the Revision object for a named revision."""
 
820
        with self.lock_read():
 
821
            return self.get_revisions([revision_id])[0]
 
822
 
 
823
    def get_revision_reconcile(self, revision_id):
 
824
        """'reconcile' helper routine that allows access to a revision always.
 
825
 
 
826
        This variant of get_revision does not cross check the weave graph
 
827
        against the revision one as get_revision does: but it should only
 
828
        be used by reconcile, or reconcile-alike commands that are correcting
 
829
        or testing the revision graph.
 
830
        """
 
831
        raise NotImplementedError(self.get_revision_reconcile)
 
832
 
 
833
    def get_revisions(self, revision_ids):
 
834
        """Get many revisions at once.
 
835
 
 
836
        Repositories that need to check data on every revision read should
 
837
        subclass this method.
 
838
        """
 
839
        revs = {}
 
840
        for revid, rev in self.iter_revisions(revision_ids):
 
841
            if rev is None:
 
842
                raise errors.NoSuchRevision(self, revid)
 
843
            revs[revid] = rev
 
844
        return [revs[revid] for revid in revision_ids]
 
845
 
 
846
    def iter_revisions(self, revision_ids):
 
847
        """Iterate over revision objects.
 
848
 
 
849
        :param revision_ids: An iterable of revisions to examine. None may be
 
850
            passed to request all revisions known to the repository. Note that
 
851
            not all repositories can find unreferenced revisions; for those
 
852
            repositories only referenced ones will be returned.
 
853
        :return: An iterator of (revid, revision) tuples. Absent revisions (
 
854
            those asked for but not available) are returned as (revid, None).
 
855
            N.B.: Revisions are not necessarily yielded in order.
 
856
        """
 
857
        raise NotImplementedError(self.iter_revisions)
 
858
 
 
859
    def get_deltas_for_revisions(self, revisions, specific_fileids=None):
 
860
        """Produce a generator of revision deltas.
 
861
 
 
862
        Note that the input is a sequence of REVISIONS, not revision_ids.
 
863
        Trees will be held in memory until the generator exits.
 
864
        Each delta is relative to the revision's lefthand predecessor.
 
865
 
 
866
        :param specific_fileids: if not None, the result is filtered
 
867
          so that only those file-ids, their parents and their
 
868
          children are included.
 
869
        """
 
870
        raise NotImplementedError(self.get_deltas_for_revisions)
 
871
 
 
872
    def get_revision_delta(self, revision_id, specific_fileids=None):
 
873
        """Return the delta for one revision.
 
874
 
 
875
        The delta is relative to the left-hand predecessor of the
 
876
        revision.
 
877
 
 
878
        :param specific_fileids: if not None, the result is filtered
 
879
          so that only those file-ids, their parents and their
 
880
          children are included.
 
881
        """
 
882
        with self.lock_read():
 
883
            r = self.get_revision(revision_id)
 
884
            return list(self.get_deltas_for_revisions(
 
885
                [r], specific_fileids=specific_fileids))[0]
 
886
 
 
887
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
888
        raise NotImplementedError(self.store_revision_signature)
 
889
 
 
890
    def add_signature_text(self, revision_id, signature):
 
891
        """Store a signature text for a revision.
 
892
 
 
893
        :param revision_id: Revision id of the revision
 
894
        :param signature: Signature text.
 
895
        """
 
896
        raise NotImplementedError(self.add_signature_text)
 
897
 
 
898
    def iter_files_bytes(self, desired_files):
 
899
        """Iterate through file versions.
 
900
 
 
901
        Files will not necessarily be returned in the order they occur in
 
902
        desired_files.  No specific order is guaranteed.
 
903
 
 
904
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
 
905
        value supplied by the caller as part of desired_files.  It should
 
906
        uniquely identify the file version in the caller's context.  (Examples:
 
907
        an index number or a TreeTransform trans_id.)
 
908
 
 
909
        :param desired_files: a list of (file_id, revision_id, identifier)
 
910
            triples
 
911
        """
 
912
        raise NotImplementedError(self.iter_files_bytes)
 
913
 
 
914
    def get_rev_id_for_revno(self, revno, known_pair):
 
915
        """Return the revision id of a revno, given a later (revno, revid)
 
916
        pair in the same history.
 
917
 
 
918
        :return: if found (True, revid).  If the available history ran out
 
919
            before reaching the revno, then this returns
 
920
            (False, (closest_revno, closest_revid)).
 
921
        """
 
922
        known_revno, known_revid = known_pair
 
923
        partial_history = [known_revid]
 
924
        distance_from_known = known_revno - revno
 
925
        if distance_from_known < 0:
 
926
            raise ValueError(
 
927
                'requested revno (%d) is later than given known revno (%d)'
 
928
                % (revno, known_revno))
 
929
        try:
 
930
            _iter_for_revno(
 
931
                self, partial_history, stop_index=distance_from_known)
 
932
        except errors.RevisionNotPresent as err:
 
933
            if err.revision_id == known_revid:
 
934
                # The start revision (known_revid) wasn't found.
 
935
                raise
 
936
            # This is a stacked repository with no fallbacks, or a there's a
 
937
            # left-hand ghost.  Either way, even though the revision named in
 
938
            # the error isn't in this repo, we know it's the next step in this
 
939
            # left-hand history.
 
940
            partial_history.append(err.revision_id)
 
941
        if len(partial_history) <= distance_from_known:
 
942
            # Didn't find enough history to get a revid for the revno.
 
943
            earliest_revno = known_revno - len(partial_history) + 1
 
944
            return (False, (earliest_revno, partial_history[-1]))
 
945
        if len(partial_history) - 1 > distance_from_known:
 
946
            raise AssertionError('_iter_for_revno returned too much history')
 
947
        return (True, partial_history[-1])
 
948
 
 
949
    def is_shared(self):
 
950
        """Return True if this repository is flagged as a shared repository."""
 
951
        raise NotImplementedError(self.is_shared)
 
952
 
 
953
    def reconcile(self, other=None, thorough=False):
 
954
        """Reconcile this repository."""
 
955
        raise NotImplementedError(self.reconcile)
 
956
 
 
957
    def _refresh_data(self):
 
958
        """Helper called from lock_* to ensure coherency with disk.
 
959
 
 
960
        The default implementation does nothing; it is however possible
 
961
        for repositories to maintain loaded indices across multiple locks
 
962
        by checking inside their implementation of this method to see
 
963
        whether their indices are still valid. This depends of course on
 
964
        the disk format being validatable in this manner. This method is
 
965
        also called by the refresh_data() public interface to cause a refresh
 
966
        to occur while in a write lock so that data inserted by a smart server
 
967
        push operation is visible on the client's instance of the physical
 
968
        repository.
 
969
        """
 
970
 
 
971
    def revision_tree(self, revision_id):
 
972
        """Return Tree for a revision on this branch.
 
973
 
 
974
        `revision_id` may be NULL_REVISION for the empty tree revision.
 
975
        """
 
976
        raise NotImplementedError(self.revision_tree)
 
977
 
 
978
    def revision_trees(self, revision_ids):
 
979
        """Return Trees for revisions in this repository.
 
980
 
 
981
        :param revision_ids: a sequence of revision-ids;
 
982
          a revision-id may not be None or b'null:'
 
983
        """
 
984
        raise NotImplementedError(self.revision_trees)
 
985
 
 
986
    def pack(self, hint=None, clean_obsolete_packs=False):
 
987
        """Compress the data within the repository.
 
988
 
 
989
        This operation only makes sense for some repository types. For other
 
990
        types it should be a no-op that just returns.
 
991
 
 
992
        This stub method does not require a lock, but subclasses should use
 
993
        self.write_lock as this is a long running call it's reasonable to
 
994
        implicitly lock for the user.
 
995
 
 
996
        :param hint: If not supplied, the whole repository is packed.
 
997
            If supplied, the repository may use the hint parameter as a
 
998
            hint for the parts of the repository to pack. A hint can be
 
999
            obtained from the result of commit_write_group(). Out of
 
1000
            date hints are simply ignored, because concurrent operations
 
1001
            can obsolete them rapidly.
 
1002
 
 
1003
        :param clean_obsolete_packs: Clean obsolete packs immediately after
 
1004
            the pack operation.
 
1005
        """
 
1006
 
 
1007
    def get_transaction(self):
 
1008
        return self.control_files.get_transaction()
 
1009
 
 
1010
    def get_parent_map(self, revision_ids):
 
1011
        """See graph.StackedParentsProvider.get_parent_map"""
 
1012
        raise NotImplementedError(self.get_parent_map)
 
1013
 
 
1014
    def _get_parent_map_no_fallbacks(self, revision_ids):
 
1015
        """Same as Repository.get_parent_map except doesn't query fallbacks."""
 
1016
        # revisions index works in keys; this just works in revisions
 
1017
        # therefore wrap and unwrap
 
1018
        query_keys = []
 
1019
        result = {}
 
1020
        for revision_id in revision_ids:
 
1021
            if revision_id == _mod_revision.NULL_REVISION:
 
1022
                result[revision_id] = ()
 
1023
            elif revision_id is None:
 
1024
                raise ValueError('get_parent_map(None) is not valid')
 
1025
            else:
 
1026
                query_keys.append((revision_id,))
 
1027
        vf = self.revisions.without_fallbacks()
 
1028
        for (revision_id,), parent_keys in viewitems(
 
1029
                vf.get_parent_map(query_keys)):
 
1030
            if parent_keys:
 
1031
                result[revision_id] = tuple([parent_revid
 
1032
                                             for (parent_revid,) in parent_keys])
 
1033
            else:
 
1034
                result[revision_id] = (_mod_revision.NULL_REVISION,)
 
1035
        return result
 
1036
 
 
1037
    def _make_parents_provider(self):
 
1038
        if not self._format.supports_external_lookups:
 
1039
            return self
 
1040
        return graph.StackedParentsProvider(_LazyListJoin(
 
1041
            [self._make_parents_provider_unstacked()],
 
1042
            self._fallback_repositories))
 
1043
 
 
1044
    def _make_parents_provider_unstacked(self):
 
1045
        return graph.CallableToParentsProviderAdapter(
 
1046
            self._get_parent_map_no_fallbacks)
 
1047
 
 
1048
    def get_known_graph_ancestry(self, revision_ids):
 
1049
        """Return the known graph for a set of revision ids and their ancestors.
 
1050
        """
 
1051
        raise NotImplementedError(self.get_known_graph_ancestry)
 
1052
 
 
1053
    def get_file_graph(self):
 
1054
        """Return the graph walker for files."""
 
1055
        raise NotImplementedError(self.get_file_graph)
 
1056
 
 
1057
    def get_graph(self, other_repository=None):
 
1058
        """Return the graph walker for this repository format"""
 
1059
        parents_provider = self._make_parents_provider()
 
1060
        if (other_repository is not None and
 
1061
                not self.has_same_location(other_repository)):
 
1062
            parents_provider = graph.StackedParentsProvider(
 
1063
                [parents_provider, other_repository._make_parents_provider()])
 
1064
        return graph.Graph(parents_provider)
 
1065
 
 
1066
    def set_make_working_trees(self, new_value):
 
1067
        """Set the policy flag for making working trees when creating branches.
 
1068
 
 
1069
        This only applies to branches that use this repository.
 
1070
 
 
1071
        The default is 'True'.
 
1072
        :param new_value: True to restore the default, False to disable making
 
1073
                          working trees.
 
1074
        """
 
1075
        raise NotImplementedError(self.set_make_working_trees)
 
1076
 
 
1077
    def make_working_trees(self):
 
1078
        """Returns the policy for making working trees on new branches."""
 
1079
        raise NotImplementedError(self.make_working_trees)
 
1080
 
 
1081
    def sign_revision(self, revision_id, gpg_strategy):
 
1082
        raise NotImplementedError(self.sign_revision)
 
1083
 
 
1084
    def verify_revision_signature(self, revision_id, gpg_strategy):
 
1085
        """Verify the signature on a revision.
 
1086
 
 
1087
        :param revision_id: the revision to verify
 
1088
        :gpg_strategy: the GPGStrategy object to used
 
1089
 
 
1090
        :return: gpg.SIGNATURE_VALID or a failed SIGNATURE_ value
 
1091
        """
 
1092
        raise NotImplementedError(self.verify_revision_signature)
 
1093
 
 
1094
    def verify_revision_signatures(self, revision_ids, gpg_strategy):
 
1095
        """Verify revision signatures for a number of revisions.
 
1096
 
 
1097
        :param revision_id: the revision to verify
 
1098
        :gpg_strategy: the GPGStrategy object to used
 
1099
        :return: Iterator over tuples with revision id, result and keys
 
1100
        """
 
1101
        with self.lock_read():
 
1102
            for revid in revision_ids:
 
1103
                (result, key) = self.verify_revision_signature(revid, gpg_strategy)
 
1104
                yield revid, result, key
 
1105
 
 
1106
    def has_signature_for_revision_id(self, revision_id):
 
1107
        """Query for a revision signature for revision_id in the repository."""
 
1108
        raise NotImplementedError(self.has_signature_for_revision_id)
 
1109
 
 
1110
    def get_signature_text(self, revision_id):
 
1111
        """Return the text for a signature."""
 
1112
        raise NotImplementedError(self.get_signature_text)
 
1113
 
 
1114
    def check(self, revision_ids=None, callback_refs=None, check_repo=True):
 
1115
        """Check consistency of all history of given revision_ids.
 
1116
 
 
1117
        Different repository implementations should override _check().
 
1118
 
 
1119
        :param revision_ids: A non-empty list of revision_ids whose ancestry
 
1120
             will be checked.  Typically the last revision_id of a branch.
 
1121
        :param callback_refs: A dict of check-refs to resolve and callback
 
1122
            the check/_check method on the items listed as wanting the ref.
 
1123
            see breezy.check.
 
1124
        :param check_repo: If False do not check the repository contents, just
 
1125
            calculate the data callback_refs requires and call them back.
 
1126
        """
 
1127
        return self._check(revision_ids=revision_ids, callback_refs=callback_refs,
 
1128
                           check_repo=check_repo)
 
1129
 
 
1130
    def _check(self, revision_ids=None, callback_refs=None, check_repo=True):
 
1131
        raise NotImplementedError(self.check)
 
1132
 
 
1133
    def _warn_if_deprecated(self, branch=None):
 
1134
        if not self._format.is_deprecated():
 
1135
            return
 
1136
        global _deprecation_warning_done
 
1137
        if _deprecation_warning_done:
 
1138
            return
 
1139
        try:
 
1140
            if branch is None:
 
1141
                conf = config.GlobalStack()
 
1142
            else:
 
1143
                conf = branch.get_config_stack()
 
1144
            if 'format_deprecation' in conf.get('suppress_warnings'):
 
1145
                return
 
1146
            warning("Format %s for %s is deprecated -"
 
1147
                    " please use 'brz upgrade' to get better performance"
 
1148
                    % (self._format, self.controldir.transport.base))
 
1149
        finally:
 
1150
            _deprecation_warning_done = True
 
1151
 
 
1152
    def supports_rich_root(self):
 
1153
        return self._format.rich_root_data
 
1154
 
 
1155
    def _check_ascii_revisionid(self, revision_id, method):
 
1156
        """Private helper for ascii-only repositories."""
 
1157
        # weave repositories refuse to store revisionids that are non-ascii.
 
1158
        if revision_id is not None:
 
1159
            # weaves require ascii revision ids.
 
1160
            if isinstance(revision_id, text_type):
 
1161
                try:
 
1162
                    revision_id.encode('ascii')
 
1163
                except UnicodeEncodeError:
 
1164
                    raise errors.NonAsciiRevisionId(method, self)
 
1165
            else:
 
1166
                try:
 
1167
                    revision_id.decode('ascii')
 
1168
                except UnicodeDecodeError:
 
1169
                    raise errors.NonAsciiRevisionId(method, self)
 
1170
 
 
1171
 
 
1172
class RepositoryFormatRegistry(controldir.ControlComponentFormatRegistry):
 
1173
    """Repository format registry."""
 
1174
 
 
1175
    def get_default(self):
 
1176
        """Return the current default format."""
 
1177
        return controldir.format_registry.make_controldir('default').repository_format
 
1178
 
 
1179
 
 
1180
network_format_registry = registry.FormatRegistry()
 
1181
"""Registry of formats indexed by their network name.
 
1182
 
 
1183
The network name for a repository format is an identifier that can be used when
 
1184
referring to formats with smart server operations. See
 
1185
RepositoryFormat.network_name() for more detail.
 
1186
"""
 
1187
 
 
1188
 
 
1189
format_registry = RepositoryFormatRegistry(network_format_registry)
 
1190
"""Registry of formats, indexed by their BzrDirMetaFormat format string.
 
1191
 
 
1192
This can contain either format instances themselves, or classes/factories that
 
1193
can be called to obtain one.
 
1194
"""
 
1195
 
 
1196
 
 
1197
#####################################################################
 
1198
# Repository Formats
 
1199
 
 
1200
class RepositoryFormat(controldir.ControlComponentFormat):
 
1201
    """A repository format.
 
1202
 
 
1203
    Formats provide four things:
 
1204
     * An initialization routine to construct repository data on disk.
 
1205
     * a optional format string which is used when the BzrDir supports
 
1206
       versioned children.
 
1207
     * an open routine which returns a Repository instance.
 
1208
     * A network name for referring to the format in smart server RPC
 
1209
       methods.
 
1210
 
 
1211
    There is one and only one Format subclass for each on-disk format. But
 
1212
    there can be one Repository subclass that is used for several different
 
1213
    formats. The _format attribute on a Repository instance can be used to
 
1214
    determine the disk format.
 
1215
 
 
1216
    Formats are placed in a registry by their format string for reference
 
1217
    during opening. These should be subclasses of RepositoryFormat for
 
1218
    consistency.
 
1219
 
 
1220
    Once a format is deprecated, just deprecate the initialize and open
 
1221
    methods on the format class. Do not deprecate the object, as the
 
1222
    object may be created even when a repository instance hasn't been
 
1223
    created.
 
1224
 
 
1225
    Common instance attributes:
 
1226
    _matchingcontroldir - the controldir format that the repository format was
 
1227
    originally written to work with. This can be used if manually
 
1228
    constructing a bzrdir and repository, or more commonly for test suite
 
1229
    parameterization.
 
1230
    """
 
1231
 
 
1232
    # Set to True or False in derived classes. True indicates that the format
 
1233
    # supports ghosts gracefully.
 
1234
    supports_ghosts = None
 
1235
    # Can this repository be given external locations to lookup additional
 
1236
    # data. Set to True or False in derived classes.
 
1237
    supports_external_lookups = None
 
1238
    # Does this format support CHK bytestring lookups. Set to True or False in
 
1239
    # derived classes.
 
1240
    supports_chks = None
 
1241
    # Should fetch trigger a reconcile after the fetch? Only needed for
 
1242
    # some repository formats that can suffer internal inconsistencies.
 
1243
    _fetch_reconcile = False
 
1244
    # Does this format have < O(tree_size) delta generation. Used to hint what
 
1245
    # code path for commit, amongst other things.
 
1246
    fast_deltas = None
 
1247
    # Does doing a pack operation compress data? Useful for the pack UI command
 
1248
    # (so if there is one pack, the operation can still proceed because it may
 
1249
    # help), and for fetching when data won't have come from the same
 
1250
    # compressor.
 
1251
    pack_compresses = False
 
1252
    # Does the repository storage understand references to trees?
 
1253
    supports_tree_reference = None
 
1254
    # Is the format experimental ?
 
1255
    experimental = False
 
1256
    # Does this repository format escape funky characters, or does it create
 
1257
    # files with similar names as the versioned files in its contents on disk
 
1258
    # ?
 
1259
    supports_funky_characters = None
 
1260
    # Does this repository format support leaving locks?
 
1261
    supports_leaving_lock = None
 
1262
    # Does this format support the full VersionedFiles interface?
 
1263
    supports_full_versioned_files = None
 
1264
    # Does this format support signing revision signatures?
 
1265
    supports_revision_signatures = True
 
1266
    # Can the revision graph have incorrect parents?
 
1267
    revision_graph_can_have_wrong_parents = None
 
1268
    # Does this format support setting revision ids?
 
1269
    supports_setting_revision_ids = True
 
1270
    # Does this format support rich root data?
 
1271
    rich_root_data = None
 
1272
    # Does this format support explicitly versioned directories?
 
1273
    supports_versioned_directories = None
 
1274
    # Can other repositories be nested into one of this format?
 
1275
    supports_nesting_repositories = None
 
1276
    # Is it possible for revisions to be present without being referenced
 
1277
    # somewhere ?
 
1278
    supports_unreferenced_revisions = None
 
1279
    # Does this format store the current Branch.nick in a revision when
 
1280
    # creating commits?
 
1281
    supports_storing_branch_nick = True
 
1282
    # Does the format support overriding the transport to use
 
1283
    supports_overriding_transport = True
 
1284
    # Does the format support setting custom revision properties?
 
1285
    supports_custom_revision_properties = True
 
1286
    # Does the format record per-file revision metadata?
 
1287
    records_per_file_revision = True
 
1288
 
 
1289
    def __repr__(self):
 
1290
        return "%s()" % self.__class__.__name__
 
1291
 
 
1292
    def __eq__(self, other):
 
1293
        # format objects are generally stateless
 
1294
        return isinstance(other, self.__class__)
 
1295
 
 
1296
    def __ne__(self, other):
 
1297
        return not self == other
 
1298
 
 
1299
    def get_format_description(self):
 
1300
        """Return the short description for this format."""
 
1301
        raise NotImplementedError(self.get_format_description)
 
1302
 
 
1303
    def initialize(self, controldir, shared=False):
 
1304
        """Initialize a repository of this format in controldir.
 
1305
 
 
1306
        :param controldir: The controldir to put the new repository in it.
 
1307
        :param shared: The repository should be initialized as a sharable one.
 
1308
        :returns: The new repository object.
 
1309
 
 
1310
        This may raise UninitializableFormat if shared repository are not
 
1311
        compatible the controldir.
 
1312
        """
 
1313
        raise NotImplementedError(self.initialize)
 
1314
 
 
1315
    def is_supported(self):
 
1316
        """Is this format supported?
 
1317
 
 
1318
        Supported formats must be initializable and openable.
 
1319
        Unsupported formats may not support initialization or committing or
 
1320
        some other features depending on the reason for not being supported.
 
1321
        """
 
1322
        return True
 
1323
 
 
1324
    def is_deprecated(self):
 
1325
        """Is this format deprecated?
 
1326
 
 
1327
        Deprecated formats may trigger a user-visible warning recommending
 
1328
        the user to upgrade. They are still fully supported.
 
1329
        """
 
1330
        return False
 
1331
 
 
1332
    def network_name(self):
 
1333
        """A simple byte string uniquely identifying this format for RPC calls.
 
1334
 
 
1335
        MetaDir repository formats use their disk format string to identify the
 
1336
        repository over the wire. All in one formats such as bzr < 0.8, and
 
1337
        foreign formats like svn/git and hg should use some marker which is
 
1338
        unique and immutable.
 
1339
        """
 
1340
        raise NotImplementedError(self.network_name)
 
1341
 
 
1342
    def check_conversion_target(self, target_format):
 
1343
        if self.rich_root_data and not target_format.rich_root_data:
 
1344
            raise errors.BadConversionTarget(
 
1345
                'Does not support rich root data.', target_format,
 
1346
                from_format=self)
 
1347
        if (self.supports_tree_reference
 
1348
                and not getattr(target_format, 'supports_tree_reference', False)):
 
1349
            raise errors.BadConversionTarget(
 
1350
                'Does not support nested trees', target_format,
 
1351
                from_format=self)
 
1352
 
 
1353
    def open(self, controldir, _found=False):
 
1354
        """Return an instance of this format for a controldir.
 
1355
 
 
1356
        _found is a private parameter, do not use it.
 
1357
        """
 
1358
        raise NotImplementedError(self.open)
 
1359
 
 
1360
    def _run_post_repo_init_hooks(self, repository, controldir, shared):
 
1361
        from .controldir import ControlDir, RepoInitHookParams
 
1362
        hooks = ControlDir.hooks['post_repo_init']
 
1363
        if not hooks:
 
1364
            return
 
1365
        params = RepoInitHookParams(repository, self, controldir, shared)
 
1366
        for hook in hooks:
 
1367
            hook(params)
 
1368
 
 
1369
 
 
1370
# formats which have no format string are not discoverable or independently
 
1371
# creatable on disk, so are not registered in format_registry.  They're
 
1372
# all in breezy.bzr.knitreponow.  When an instance of one of these is
 
1373
# needed, it's constructed directly by the ControlDir.  Non-native formats where
 
1374
# the repository is not separately opened are similar.
 
1375
 
 
1376
format_registry.register_lazy(
 
1377
    b'Bazaar-NG Knit Repository Format 1',
 
1378
    'breezy.bzr.knitrepo',
 
1379
    'RepositoryFormatKnit1',
 
1380
    )
 
1381
 
 
1382
format_registry.register_lazy(
 
1383
    b'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
 
1384
    'breezy.bzr.knitrepo',
 
1385
    'RepositoryFormatKnit3',
 
1386
    )
 
1387
 
 
1388
format_registry.register_lazy(
 
1389
    b'Bazaar Knit Repository Format 4 (bzr 1.0)\n',
 
1390
    'breezy.bzr.knitrepo',
 
1391
    'RepositoryFormatKnit4',
 
1392
    )
 
1393
 
 
1394
# Pack-based formats. There is one format for pre-subtrees, and one for
 
1395
# post-subtrees to allow ease of testing.
 
1396
# NOTE: These are experimental in 0.92. Stable in 1.0 and above
 
1397
format_registry.register_lazy(
 
1398
    b'Bazaar pack repository format 1 (needs bzr 0.92)\n',
 
1399
    'breezy.bzr.knitpack_repo',
 
1400
    'RepositoryFormatKnitPack1',
 
1401
    )
 
1402
format_registry.register_lazy(
 
1403
    b'Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n',
 
1404
    'breezy.bzr.knitpack_repo',
 
1405
    'RepositoryFormatKnitPack3',
 
1406
    )
 
1407
format_registry.register_lazy(
 
1408
    b'Bazaar pack repository format 1 with rich root (needs bzr 1.0)\n',
 
1409
    'breezy.bzr.knitpack_repo',
 
1410
    'RepositoryFormatKnitPack4',
 
1411
    )
 
1412
format_registry.register_lazy(
 
1413
    b'Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n',
 
1414
    'breezy.bzr.knitpack_repo',
 
1415
    'RepositoryFormatKnitPack5',
 
1416
    )
 
1417
format_registry.register_lazy(
 
1418
    b'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n',
 
1419
    'breezy.bzr.knitpack_repo',
 
1420
    'RepositoryFormatKnitPack5RichRoot',
 
1421
    )
 
1422
format_registry.register_lazy(
 
1423
    b'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n',
 
1424
    'breezy.bzr.knitpack_repo',
 
1425
    'RepositoryFormatKnitPack5RichRootBroken',
 
1426
    )
 
1427
format_registry.register_lazy(
 
1428
    b'Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n',
 
1429
    'breezy.bzr.knitpack_repo',
 
1430
    'RepositoryFormatKnitPack6',
 
1431
    )
 
1432
format_registry.register_lazy(
 
1433
    b'Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n',
 
1434
    'breezy.bzr.knitpack_repo',
 
1435
    'RepositoryFormatKnitPack6RichRoot',
 
1436
    )
 
1437
format_registry.register_lazy(
 
1438
    b'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
 
1439
    'breezy.bzr.groupcompress_repo',
 
1440
    'RepositoryFormat2a',
 
1441
    )
 
1442
 
 
1443
# Development formats.
 
1444
# Check their docstrings to see if/when they are obsolete.
 
1445
format_registry.register_lazy(
 
1446
    (b"Bazaar development format 2 with subtree support "
 
1447
        b"(needs bzr.dev from before 1.8)\n"),
 
1448
    'breezy.bzr.knitpack_repo',
 
1449
    'RepositoryFormatPackDevelopment2Subtree',
 
1450
    )
 
1451
format_registry.register_lazy(
 
1452
    b'Bazaar development format 8\n',
 
1453
    'breezy.bzr.groupcompress_repo',
 
1454
    'RepositoryFormat2aSubtree',
 
1455
    )
 
1456
 
 
1457
 
 
1458
class InterRepository(InterObject):
 
1459
    """This class represents operations taking place between two repositories.
 
1460
 
 
1461
    Its instances have methods like copy_content and fetch, and contain
 
1462
    references to the source and target repositories these operations can be
 
1463
    carried out on.
 
1464
 
 
1465
    Often we will provide convenience methods on 'repository' which carry out
 
1466
    operations with another repository - they will always forward to
 
1467
    InterRepository.get(other).method_name(parameters).
 
1468
    """
 
1469
 
 
1470
    _optimisers = []
 
1471
    """The available optimised InterRepository types."""
 
1472
 
 
1473
    def copy_content(self, revision_id=None):
 
1474
        """Make a complete copy of the content in self into destination.
 
1475
 
 
1476
        This is a destructive operation! Do not use it on existing
 
1477
        repositories.
 
1478
 
 
1479
        :param revision_id: Only copy the content needed to construct
 
1480
                            revision_id and its parents.
 
1481
        """
 
1482
        with self.lock_write():
 
1483
            try:
 
1484
                self.target.set_make_working_trees(
 
1485
                    self.source.make_working_trees())
 
1486
            except NotImplementedError:
 
1487
                pass
 
1488
            self.target.fetch(self.source, revision_id=revision_id)
 
1489
 
 
1490
    def fetch(self, revision_id=None, find_ghosts=False):
 
1491
        """Fetch the content required to construct revision_id.
 
1492
 
 
1493
        The content is copied from self.source to self.target.
 
1494
 
 
1495
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
1496
                            content is copied.
 
1497
        :return: None.
 
1498
        """
 
1499
        raise NotImplementedError(self.fetch)
 
1500
 
 
1501
    def search_missing_revision_ids(
 
1502
            self, find_ghosts=True, revision_ids=None, if_present_ids=None,
 
1503
            limit=None):
 
1504
        """Return the revision ids that source has that target does not.
 
1505
 
 
1506
        :param revision_ids: return revision ids included by these
 
1507
            revision_ids.  NoSuchRevision will be raised if any of these
 
1508
            revisions are not present.
 
1509
        :param if_present_ids: like revision_ids, but will not cause
 
1510
            NoSuchRevision if any of these are absent, instead they will simply
 
1511
            not be in the result.  This is useful for e.g. finding revisions
 
1512
            to fetch for tags, which may reference absent revisions.
 
1513
        :param find_ghosts: If True find missing revisions in deep history
 
1514
            rather than just finding the surface difference.
 
1515
        :param limit: Maximum number of revisions to return, topologically
 
1516
            ordered
 
1517
        :return: A breezy.graph.SearchResult.
 
1518
        """
 
1519
        raise NotImplementedError(self.search_missing_revision_ids)
 
1520
 
 
1521
    @staticmethod
 
1522
    def _same_model(source, target):
 
1523
        """True if source and target have the same data representation.
 
1524
 
 
1525
        Note: this is always called on the base class; overriding it in a
 
1526
        subclass will have no effect.
 
1527
        """
 
1528
        try:
 
1529
            InterRepository._assert_same_model(source, target)
 
1530
            return True
 
1531
        except errors.IncompatibleRepositories as e:
 
1532
            return False
 
1533
 
 
1534
    @staticmethod
 
1535
    def _assert_same_model(source, target):
 
1536
        """Raise an exception if two repositories do not use the same model.
 
1537
        """
 
1538
        if source.supports_rich_root() != target.supports_rich_root():
 
1539
            raise errors.IncompatibleRepositories(source, target,
 
1540
                                                  "different rich-root support")
 
1541
        if source._serializer != target._serializer:
 
1542
            raise errors.IncompatibleRepositories(source, target,
 
1543
                                                  "different serializers")
 
1544
 
 
1545
 
 
1546
class CopyConverter(object):
 
1547
    """A repository conversion tool which just performs a copy of the content.
 
1548
 
 
1549
    This is slow but quite reliable.
 
1550
    """
 
1551
 
 
1552
    def __init__(self, target_format):
 
1553
        """Create a CopyConverter.
 
1554
 
 
1555
        :param target_format: The format the resulting repository should be.
 
1556
        """
 
1557
        self.target_format = target_format
 
1558
 
 
1559
    def convert(self, repo, pb):
 
1560
        """Perform the conversion of to_convert, giving feedback via pb.
 
1561
 
 
1562
        :param to_convert: The disk object to convert.
 
1563
        :param pb: a progress bar to use for progress information.
 
1564
        """
 
1565
        with ui.ui_factory.nested_progress_bar() as pb:
 
1566
            self.count = 0
 
1567
            self.total = 4
 
1568
            # this is only useful with metadir layouts - separated repo content.
 
1569
            # trigger an assertion if not such
 
1570
            repo._format.get_format_string()
 
1571
            self.repo_dir = repo.controldir
 
1572
            pb.update(gettext('Moving repository to repository.backup'))
 
1573
            self.repo_dir.transport.move('repository', 'repository.backup')
 
1574
            backup_transport = self.repo_dir.transport.clone(
 
1575
                'repository.backup')
 
1576
            repo._format.check_conversion_target(self.target_format)
 
1577
            self.source_repo = repo._format.open(self.repo_dir,
 
1578
                                                 _found=True,
 
1579
                                                 _override_transport=backup_transport)
 
1580
            pb.update(gettext('Creating new repository'))
 
1581
            converted = self.target_format.initialize(self.repo_dir,
 
1582
                                                      self.source_repo.is_shared())
 
1583
            converted.lock_write()
 
1584
            try:
 
1585
                pb.update(gettext('Copying content'))
 
1586
                self.source_repo.copy_content_into(converted)
 
1587
            finally:
 
1588
                converted.unlock()
 
1589
            pb.update(gettext('Deleting old repository content'))
 
1590
            self.repo_dir.transport.delete_tree('repository.backup')
 
1591
            ui.ui_factory.note(gettext('repository converted'))
 
1592
 
 
1593
 
 
1594
def _strip_NULL_ghosts(revision_graph):
 
1595
    """Also don't use this. more compatibility code for unmigrated clients."""
 
1596
    # Filter ghosts, and null:
 
1597
    if _mod_revision.NULL_REVISION in revision_graph:
 
1598
        del revision_graph[_mod_revision.NULL_REVISION]
 
1599
    for key, parents in viewitems(revision_graph):
 
1600
        revision_graph[key] = tuple(parent for parent in parents if parent
 
1601
                                    in revision_graph)
 
1602
    return revision_graph
 
1603
 
 
1604
 
 
1605
def _iter_for_revno(repo, partial_history_cache, stop_index=None,
 
1606
                    stop_revision=None):
 
1607
    """Extend the partial history to include a given index
 
1608
 
 
1609
    If a stop_index is supplied, stop when that index has been reached.
 
1610
    If a stop_revision is supplied, stop when that revision is
 
1611
    encountered.  Otherwise, stop when the beginning of history is
 
1612
    reached.
 
1613
 
 
1614
    :param stop_index: The index which should be present.  When it is
 
1615
        present, history extension will stop.
 
1616
    :param stop_revision: The revision id which should be present.  When
 
1617
        it is encountered, history extension will stop.
 
1618
    """
 
1619
    start_revision = partial_history_cache[-1]
 
1620
    graph = repo.get_graph()
 
1621
    iterator = graph.iter_lefthand_ancestry(start_revision,
 
1622
                                            (_mod_revision.NULL_REVISION,))
 
1623
    try:
 
1624
        # skip the last revision in the list
 
1625
        next(iterator)
 
1626
        while True:
 
1627
            if (stop_index is not None and
 
1628
                    len(partial_history_cache) > stop_index):
 
1629
                break
 
1630
            if partial_history_cache[-1] == stop_revision:
 
1631
                break
 
1632
            revision_id = next(iterator)
 
1633
            partial_history_cache.append(revision_id)
 
1634
    except StopIteration:
 
1635
        # No more history
 
1636
        return
 
1637
 
 
1638
 
 
1639
class _LazyListJoin(object):
 
1640
    """An iterable yielding the contents of many lists as one list.
 
1641
 
 
1642
    Each iterator made from this will reflect the current contents of the lists
 
1643
    at the time the iterator is made.
 
1644
 
 
1645
    This is used by Repository's _make_parents_provider implementation so that
 
1646
    it is safe to do::
 
1647
 
 
1648
      pp = repo._make_parents_provider()      # uses a list of fallback repos
 
1649
      pp.add_fallback_repository(other_repo)  # appends to that list
 
1650
      result = pp.get_parent_map(...)
 
1651
      # The result will include revs from other_repo
 
1652
    """
 
1653
 
 
1654
    def __init__(self, *list_parts):
 
1655
        self.list_parts = list_parts
 
1656
 
 
1657
    def __iter__(self):
 
1658
        full_list = []
 
1659
        for list_part in self.list_parts:
 
1660
            full_list.extend(list_part)
 
1661
        return iter(full_list)
 
1662
 
 
1663
    def __repr__(self):
 
1664
        return "%s.%s(%s)" % (self.__module__, self.__class__.__name__,
 
1665
                              self.list_parts)