/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Robert Collins
  • Date: 2009-02-24 08:09:17 UTC
  • mfrom: (4037 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4038.
  • Revision ID: robertc@robertcollins.net-20090224080917-9k7ib4oj1godlp3k
Merge bzr (resolve conflicts).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
 
18
import sys
 
19
 
 
20
from bzrlib.lazy_import import lazy_import
 
21
lazy_import(globals(), """
 
22
from itertools import chain
 
23
from bzrlib import (
 
24
        bzrdir,
 
25
        cache_utf8,
 
26
        config as _mod_config,
 
27
        debug,
 
28
        errors,
 
29
        lockdir,
 
30
        lockable_files,
 
31
        repository,
 
32
        revision as _mod_revision,
 
33
        transport,
 
34
        tsort,
 
35
        ui,
 
36
        urlutils,
 
37
        )
 
38
from bzrlib.config import BranchConfig
 
39
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
 
40
from bzrlib.tag import (
 
41
    BasicTags,
 
42
    DisabledTags,
 
43
    )
 
44
""")
 
45
 
 
46
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
47
from bzrlib.hooks import Hooks
 
48
from bzrlib import registry
 
49
from bzrlib.symbol_versioning import (
 
50
    deprecated_in,
 
51
    deprecated_method,
 
52
    )
 
53
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
 
54
 
 
55
 
 
56
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
57
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
 
58
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
 
59
 
 
60
 
 
61
# TODO: Maybe include checks for common corruption of newlines, etc?
 
62
 
 
63
# TODO: Some operations like log might retrieve the same revisions
 
64
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
65
# cache in memory to make this faster.  In general anything can be
 
66
# cached in memory between lock and unlock operations. .. nb thats
 
67
# what the transaction identity map provides
 
68
 
 
69
 
 
70
######################################################################
 
71
# branch objects
 
72
 
 
73
class Branch(object):
 
74
    """Branch holding a history of revisions.
 
75
 
 
76
    base
 
77
        Base directory/url of the branch.
 
78
 
 
79
    hooks: An instance of BranchHooks.
 
80
    """
 
81
    # this is really an instance variable - FIXME move it there
 
82
    # - RBC 20060112
 
83
    base = None
 
84
 
 
85
    # override this to set the strategy for storing tags
 
86
    def _make_tags(self):
 
87
        return DisabledTags(self)
 
88
 
 
89
    def __init__(self, *ignored, **ignored_too):
 
90
        self.tags = self._make_tags()
 
91
        self._revision_history_cache = None
 
92
        self._revision_id_to_revno_cache = None
 
93
        self._partial_revision_id_to_revno_cache = {}
 
94
        self._last_revision_info_cache = None
 
95
        self._merge_sorted_revisions_cache = None
 
96
        self._open_hook()
 
97
        hooks = Branch.hooks['open']
 
98
        for hook in hooks:
 
99
            hook(self)
 
100
 
 
101
    def _open_hook(self):
 
102
        """Called by init to allow simpler extension of the base class."""
 
103
 
 
104
    def break_lock(self):
 
105
        """Break a lock if one is present from another instance.
 
106
 
 
107
        Uses the ui factory to ask for confirmation if the lock may be from
 
108
        an active process.
 
109
 
 
110
        This will probe the repository for its lock as well.
 
111
        """
 
112
        self.control_files.break_lock()
 
113
        self.repository.break_lock()
 
114
        master = self.get_master_branch()
 
115
        if master is not None:
 
116
            master.break_lock()
 
117
 
 
118
    @staticmethod
 
119
    def open(base, _unsupported=False, possible_transports=None):
 
120
        """Open the branch rooted at base.
 
121
 
 
122
        For instance, if the branch is at URL/.bzr/branch,
 
123
        Branch.open(URL) -> a Branch instance.
 
124
        """
 
125
        control = bzrdir.BzrDir.open(base, _unsupported,
 
126
                                     possible_transports=possible_transports)
 
127
        return control.open_branch(_unsupported)
 
128
 
 
129
    @staticmethod
 
130
    def open_from_transport(transport, _unsupported=False):
 
131
        """Open the branch rooted at transport"""
 
132
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
 
133
        return control.open_branch(_unsupported)
 
134
 
 
135
    @staticmethod
 
136
    def open_containing(url, possible_transports=None):
 
137
        """Open an existing branch which contains url.
 
138
 
 
139
        This probes for a branch at url, and searches upwards from there.
 
140
 
 
141
        Basically we keep looking up until we find the control directory or
 
142
        run into the root.  If there isn't one, raises NotBranchError.
 
143
        If there is one and it is either an unrecognised format or an unsupported
 
144
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
145
        If there is one, it is returned, along with the unused portion of url.
 
146
        """
 
147
        control, relpath = bzrdir.BzrDir.open_containing(url,
 
148
                                                         possible_transports)
 
149
        return control.open_branch(), relpath
 
150
 
 
151
    def get_config(self):
 
152
        return BranchConfig(self)
 
153
 
 
154
    def _get_nick(self, local=False, possible_transports=None):
 
155
        config = self.get_config()
 
156
        # explicit overrides master, but don't look for master if local is True
 
157
        if not local and not config.has_explicit_nickname():
 
158
            try:
 
159
                master = self.get_master_branch(possible_transports)
 
160
                if master is not None:
 
161
                    # return the master branch value
 
162
                    return master.nick
 
163
            except errors.BzrError, e:
 
164
                # Silently fall back to local implicit nick if the master is
 
165
                # unavailable
 
166
                mutter("Could not connect to bound branch, "
 
167
                    "falling back to local nick.\n " + str(e))
 
168
        return config.get_nickname()
 
169
 
 
170
    def _set_nick(self, nick):
 
171
        self.get_config().set_user_option('nickname', nick, warn_masked=True)
 
172
 
 
173
    nick = property(_get_nick, _set_nick)
 
174
 
 
175
    def is_locked(self):
 
176
        raise NotImplementedError(self.is_locked)
 
177
 
 
178
    def _lefthand_history(self, revision_id, last_rev=None,
 
179
                          other_branch=None):
 
180
        if 'evil' in debug.debug_flags:
 
181
            mutter_callsite(4, "_lefthand_history scales with history.")
 
182
        # stop_revision must be a descendant of last_revision
 
183
        graph = self.repository.get_graph()
 
184
        if last_rev is not None:
 
185
            if not graph.is_ancestor(last_rev, revision_id):
 
186
                # our previous tip is not merged into stop_revision
 
187
                raise errors.DivergedBranches(self, other_branch)
 
188
        # make a new revision history from the graph
 
189
        parents_map = graph.get_parent_map([revision_id])
 
190
        if revision_id not in parents_map:
 
191
            raise errors.NoSuchRevision(self, revision_id)
 
192
        current_rev_id = revision_id
 
193
        new_history = []
 
194
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
195
        # Do not include ghosts or graph origin in revision_history
 
196
        while (current_rev_id in parents_map and
 
197
               len(parents_map[current_rev_id]) > 0):
 
198
            check_not_reserved_id(current_rev_id)
 
199
            new_history.append(current_rev_id)
 
200
            current_rev_id = parents_map[current_rev_id][0]
 
201
            parents_map = graph.get_parent_map([current_rev_id])
 
202
        new_history.reverse()
 
203
        return new_history
 
204
 
 
205
    def lock_write(self):
 
206
        raise NotImplementedError(self.lock_write)
 
207
 
 
208
    def lock_read(self):
 
209
        raise NotImplementedError(self.lock_read)
 
210
 
 
211
    def unlock(self):
 
212
        raise NotImplementedError(self.unlock)
 
213
 
 
214
    def peek_lock_mode(self):
 
215
        """Return lock mode for the Branch: 'r', 'w' or None"""
 
216
        raise NotImplementedError(self.peek_lock_mode)
 
217
 
 
218
    def get_physical_lock_status(self):
 
219
        raise NotImplementedError(self.get_physical_lock_status)
 
220
 
 
221
    @needs_read_lock
 
222
    def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
 
223
        """Return the revision_id for a dotted revno.
 
224
 
 
225
        :param revno: a tuple like (1,) or (1,1,2)
 
226
        :param _cache_reverse: a private parameter enabling storage
 
227
           of the reverse mapping in a top level cache. (This should
 
228
           only be done in selective circumstances as we want to
 
229
           avoid having the mapping cached multiple times.)
 
230
        :return: the revision_id
 
231
        :raises errors.NoSuchRevision: if the revno doesn't exist
 
232
        """
 
233
        rev_id = self._do_dotted_revno_to_revision_id(revno)
 
234
        if _cache_reverse:
 
235
            self._partial_revision_id_to_revno_cache[rev_id] = revno
 
236
        return rev_id
 
237
 
 
238
    def _do_dotted_revno_to_revision_id(self, revno):
 
239
        """Worker function for dotted_revno_to_revision_id.
 
240
 
 
241
        Subclasses should override this if they wish to
 
242
        provide a more efficient implementation.
 
243
        """
 
244
        if len(revno) == 1:
 
245
            return self.get_rev_id(revno[0])
 
246
        revision_id_to_revno = self.get_revision_id_to_revno_map()
 
247
        revision_ids = [revision_id for revision_id, this_revno
 
248
                        in revision_id_to_revno.iteritems()
 
249
                        if revno == this_revno]
 
250
        if len(revision_ids) == 1:
 
251
            return revision_ids[0]
 
252
        else:
 
253
            revno_str = '.'.join(map(str, revno))
 
254
            raise errors.NoSuchRevision(self, revno_str)
 
255
 
 
256
    @needs_read_lock
 
257
    def revision_id_to_dotted_revno(self, revision_id):
 
258
        """Given a revision id, return its dotted revno.
 
259
 
 
260
        :return: a tuple like (1,) or (400,1,3).
 
261
        """
 
262
        return self._do_revision_id_to_dotted_revno(revision_id)
 
263
 
 
264
    def _do_revision_id_to_dotted_revno(self, revision_id):
 
265
        """Worker function for revision_id_to_revno."""
 
266
        # Try the caches if they are loaded
 
267
        result = self._partial_revision_id_to_revno_cache.get(revision_id)
 
268
        if result is not None:
 
269
            return result
 
270
        if self._revision_id_to_revno_cache:
 
271
            result = self._revision_id_to_revno_cache.get(revision_id)
 
272
            if result is None:
 
273
                raise errors.NoSuchRevision(self, revision_id)
 
274
        # Try the mainline as it's optimised
 
275
        try:
 
276
            revno = self.revision_id_to_revno(revision_id)
 
277
            return (revno,)
 
278
        except errors.NoSuchRevision:
 
279
            # We need to load and use the full revno map after all
 
280
            result = self.get_revision_id_to_revno_map().get(revision_id)
 
281
            if result is None:
 
282
                raise errors.NoSuchRevision(self, revision_id)
 
283
        return result
 
284
 
 
285
    @needs_read_lock
 
286
    def get_revision_id_to_revno_map(self):
 
287
        """Return the revision_id => dotted revno map.
 
288
 
 
289
        This will be regenerated on demand, but will be cached.
 
290
 
 
291
        :return: A dictionary mapping revision_id => dotted revno.
 
292
            This dictionary should not be modified by the caller.
 
293
        """
 
294
        if self._revision_id_to_revno_cache is not None:
 
295
            mapping = self._revision_id_to_revno_cache
 
296
        else:
 
297
            mapping = self._gen_revno_map()
 
298
            self._cache_revision_id_to_revno(mapping)
 
299
        # TODO: jam 20070417 Since this is being cached, should we be returning
 
300
        #       a copy?
 
301
        # I would rather not, and instead just declare that users should not
 
302
        # modify the return value.
 
303
        return mapping
 
304
 
 
305
    def _gen_revno_map(self):
 
306
        """Create a new mapping from revision ids to dotted revnos.
 
307
 
 
308
        Dotted revnos are generated based on the current tip in the revision
 
309
        history.
 
310
        This is the worker function for get_revision_id_to_revno_map, which
 
311
        just caches the return value.
 
312
 
 
313
        :return: A dictionary mapping revision_id => dotted revno.
 
314
        """
 
315
        revision_id_to_revno = dict((rev_id, revno)
 
316
            for rev_id, depth, revno, end_of_merge
 
317
             in self.iter_merge_sorted_revisions())
 
318
        return revision_id_to_revno
 
319
 
 
320
    @needs_read_lock
 
321
    def iter_merge_sorted_revisions(self, start_revision_id=None,
 
322
            stop_revision_id=None, stop_rule='exclude', direction='reverse'):
 
323
        """Walk the revisions for a branch in merge sorted order.
 
324
 
 
325
        Merge sorted order is the output from a merge-aware,
 
326
        topological sort, i.e. all parents come before their
 
327
        children going forward; the opposite for reverse.
 
328
 
 
329
        :param start_revision_id: the revision_id to begin walking from.
 
330
            If None, the branch tip is used.
 
331
        :param stop_revision_id: the revision_id to terminate the walk
 
332
            after. If None, the rest of history is included.
 
333
        :param stop_rule: if stop_revision_id is not None, the precise rule
 
334
            to use for termination:
 
335
            * 'exclude' - leave the stop revision out of the result (default)
 
336
            * 'include' - the stop revision is the last item in the result
 
337
            * 'with-merges' - include the stop revision and all of its
 
338
              merged revisions in the result
 
339
        :param direction: either 'reverse' or 'forward':
 
340
            * reverse means return the start_revision_id first, i.e.
 
341
              start at the most recent revision and go backwards in history
 
342
            * forward returns tuples in the opposite order to reverse.
 
343
              Note in particular that forward does *not* do any intelligent
 
344
              ordering w.r.t. depth as some clients of this API may like.
 
345
              (If required, that ought to be done at higher layers.)
 
346
 
 
347
        :return: an iterator over (revision_id, depth, revno, end_of_merge)
 
348
            tuples where:
 
349
 
 
350
            * revision_id: the unique id of the revision
 
351
            * depth: How many levels of merging deep this node has been
 
352
              found.
 
353
            * revno_sequence: This field provides a sequence of
 
354
              revision numbers for all revisions. The format is:
 
355
              (REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
 
356
              branch that the revno is on. From left to right the REVNO numbers
 
357
              are the sequence numbers within that branch of the revision.
 
358
            * end_of_merge: When True the next node (earlier in history) is
 
359
              part of a different merge.
 
360
        """
 
361
        # Note: depth and revno values are in the context of the branch so
 
362
        # we need the full graph to get stable numbers, regardless of the
 
363
        # start_revision_id.
 
364
        if self._merge_sorted_revisions_cache is None:
 
365
            last_revision = self.last_revision()
 
366
            graph = self.repository.get_graph()
 
367
            parent_map = dict(((key, value) for key, value in
 
368
                     graph.iter_ancestry([last_revision]) if value is not None))
 
369
            revision_graph = repository._strip_NULL_ghosts(parent_map)
 
370
            revs = tsort.merge_sort(revision_graph, last_revision, None,
 
371
                generate_revno=True)
 
372
            # Drop the sequence # before caching
 
373
            self._merge_sorted_revisions_cache = [r[1:] for r in revs]
 
374
 
 
375
        filtered = self._filter_merge_sorted_revisions(
 
376
            self._merge_sorted_revisions_cache, start_revision_id,
 
377
            stop_revision_id, stop_rule)
 
378
        if direction == 'reverse':
 
379
            return filtered
 
380
        if direction == 'forward':
 
381
            return reversed(list(filtered))
 
382
        else:
 
383
            raise ValueError('invalid direction %r' % direction)
 
384
 
 
385
    def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
 
386
        start_revision_id, stop_revision_id, stop_rule):
 
387
        """Iterate over an inclusive range of sorted revisions."""
 
388
        rev_iter = iter(merge_sorted_revisions)
 
389
        if start_revision_id is not None:
 
390
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
391
                if rev_id != start_revision_id:
 
392
                    continue
 
393
                else:
 
394
                    # The decision to include the start or not
 
395
                    # depends on the stop_rule if a stop is provided
 
396
                    rev_iter = chain(
 
397
                        iter([(rev_id, depth, revno, end_of_merge)]),
 
398
                        rev_iter)
 
399
                    break
 
400
        if stop_revision_id is None:
 
401
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
402
                yield rev_id, depth, revno, end_of_merge
 
403
        elif stop_rule == 'exclude':
 
404
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
405
                if rev_id == stop_revision_id:
 
406
                    return
 
407
                yield rev_id, depth, revno, end_of_merge
 
408
        elif stop_rule == 'include':
 
409
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
410
                yield rev_id, depth, revno, end_of_merge
 
411
                if rev_id == stop_revision_id:
 
412
                    return
 
413
        elif stop_rule == 'with-merges':
 
414
            stop_rev = self.repository.get_revision(stop_revision_id)
 
415
            if stop_rev.parent_ids:
 
416
                left_parent = stop_rev.parent_ids[0]
 
417
            else:
 
418
                left_parent = _mod_revision.NULL_REVISION
 
419
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
420
                if rev_id == left_parent:
 
421
                    return
 
422
                yield rev_id, depth, revno, end_of_merge
 
423
        else:
 
424
            raise ValueError('invalid stop_rule %r' % stop_rule)
 
425
 
 
426
    def leave_lock_in_place(self):
 
427
        """Tell this branch object not to release the physical lock when this
 
428
        object is unlocked.
 
429
 
 
430
        If lock_write doesn't return a token, then this method is not supported.
 
431
        """
 
432
        self.control_files.leave_in_place()
 
433
 
 
434
    def dont_leave_lock_in_place(self):
 
435
        """Tell this branch object to release the physical lock when this
 
436
        object is unlocked, even if it didn't originally acquire it.
 
437
 
 
438
        If lock_write doesn't return a token, then this method is not supported.
 
439
        """
 
440
        self.control_files.dont_leave_in_place()
 
441
 
 
442
    def bind(self, other):
 
443
        """Bind the local branch the other branch.
 
444
 
 
445
        :param other: The branch to bind to
 
446
        :type other: Branch
 
447
        """
 
448
        raise errors.UpgradeRequired(self.base)
 
449
 
 
450
    @needs_write_lock
 
451
    def fetch(self, from_branch, last_revision=None, pb=None):
 
452
        """Copy revisions from from_branch into this branch.
 
453
 
 
454
        :param from_branch: Where to copy from.
 
455
        :param last_revision: What revision to stop at (None for at the end
 
456
                              of the branch.
 
457
        :param pb: An optional progress bar to use.
 
458
 
 
459
        Returns the copied revision count and the failed revisions in a tuple:
 
460
        (copied, failures).
 
461
        """
 
462
        if self.base == from_branch.base:
 
463
            return (0, [])
 
464
        if pb is None:
 
465
            nested_pb = ui.ui_factory.nested_progress_bar()
 
466
            pb = nested_pb
 
467
        else:
 
468
            nested_pb = None
 
469
 
 
470
        from_branch.lock_read()
 
471
        try:
 
472
            if last_revision is None:
 
473
                pb.update('get source history')
 
474
                last_revision = from_branch.last_revision()
 
475
                last_revision = _mod_revision.ensure_null(last_revision)
 
476
            return self.repository.fetch(from_branch.repository,
 
477
                                         revision_id=last_revision,
 
478
                                         pb=nested_pb)
 
479
        finally:
 
480
            if nested_pb is not None:
 
481
                nested_pb.finished()
 
482
            from_branch.unlock()
 
483
 
 
484
    def get_bound_location(self):
 
485
        """Return the URL of the branch we are bound to.
 
486
 
 
487
        Older format branches cannot bind, please be sure to use a metadir
 
488
        branch.
 
489
        """
 
490
        return None
 
491
 
 
492
    def get_old_bound_location(self):
 
493
        """Return the URL of the branch we used to be bound to
 
494
        """
 
495
        raise errors.UpgradeRequired(self.base)
 
496
 
 
497
    def get_commit_builder(self, parents, config=None, timestamp=None,
 
498
                           timezone=None, committer=None, revprops=None,
 
499
                           revision_id=None):
 
500
        """Obtain a CommitBuilder for this branch.
 
501
 
 
502
        :param parents: Revision ids of the parents of the new revision.
 
503
        :param config: Optional configuration to use.
 
504
        :param timestamp: Optional timestamp recorded for commit.
 
505
        :param timezone: Optional timezone for timestamp.
 
506
        :param committer: Optional committer to set for commit.
 
507
        :param revprops: Optional dictionary of revision properties.
 
508
        :param revision_id: Optional revision id.
 
509
        """
 
510
 
 
511
        if config is None:
 
512
            config = self.get_config()
 
513
 
 
514
        return self.repository.get_commit_builder(self, parents, config,
 
515
            timestamp, timezone, committer, revprops, revision_id)
 
516
 
 
517
    def get_master_branch(self, possible_transports=None):
 
518
        """Return the branch we are bound to.
 
519
 
 
520
        :return: Either a Branch, or None
 
521
        """
 
522
        return None
 
523
 
 
524
    def get_revision_delta(self, revno):
 
525
        """Return the delta for one revision.
 
526
 
 
527
        The delta is relative to its mainline predecessor, or the
 
528
        empty tree for revision 1.
 
529
        """
 
530
        rh = self.revision_history()
 
531
        if not (1 <= revno <= len(rh)):
 
532
            raise errors.InvalidRevisionNumber(revno)
 
533
        return self.repository.get_revision_delta(rh[revno-1])
 
534
 
 
535
    def get_stacked_on_url(self):
 
536
        """Get the URL this branch is stacked against.
 
537
 
 
538
        :raises NotStacked: If the branch is not stacked.
 
539
        :raises UnstackableBranchFormat: If the branch does not support
 
540
            stacking.
 
541
        """
 
542
        raise NotImplementedError(self.get_stacked_on_url)
 
543
 
 
544
    def print_file(self, file, revision_id):
 
545
        """Print `file` to stdout."""
 
546
        raise NotImplementedError(self.print_file)
 
547
 
 
548
    def set_revision_history(self, rev_history):
 
549
        raise NotImplementedError(self.set_revision_history)
 
550
 
 
551
    def set_stacked_on_url(self, url):
 
552
        """Set the URL this branch is stacked against.
 
553
 
 
554
        :raises UnstackableBranchFormat: If the branch does not support
 
555
            stacking.
 
556
        :raises UnstackableRepositoryFormat: If the repository does not support
 
557
            stacking.
 
558
        """
 
559
        raise NotImplementedError(self.set_stacked_on_url)
 
560
 
 
561
    def _cache_revision_history(self, rev_history):
 
562
        """Set the cached revision history to rev_history.
 
563
 
 
564
        The revision_history method will use this cache to avoid regenerating
 
565
        the revision history.
 
566
 
 
567
        This API is semi-public; it only for use by subclasses, all other code
 
568
        should consider it to be private.
 
569
        """
 
570
        self._revision_history_cache = rev_history
 
571
 
 
572
    def _cache_revision_id_to_revno(self, revision_id_to_revno):
 
573
        """Set the cached revision_id => revno map to revision_id_to_revno.
 
574
 
 
575
        This API is semi-public; it only for use by subclasses, all other code
 
576
        should consider it to be private.
 
577
        """
 
578
        self._revision_id_to_revno_cache = revision_id_to_revno
 
579
 
 
580
    def _clear_cached_state(self):
 
581
        """Clear any cached data on this branch, e.g. cached revision history.
 
582
 
 
583
        This means the next call to revision_history will need to call
 
584
        _gen_revision_history.
 
585
 
 
586
        This API is semi-public; it only for use by subclasses, all other code
 
587
        should consider it to be private.
 
588
        """
 
589
        self._revision_history_cache = None
 
590
        self._revision_id_to_revno_cache = None
 
591
        self._last_revision_info_cache = None
 
592
        self._merge_sorted_revisions_cache = None
 
593
 
 
594
    def _gen_revision_history(self):
 
595
        """Return sequence of revision hashes on to this branch.
 
596
 
 
597
        Unlike revision_history, this method always regenerates or rereads the
 
598
        revision history, i.e. it does not cache the result, so repeated calls
 
599
        may be expensive.
 
600
 
 
601
        Concrete subclasses should override this instead of revision_history so
 
602
        that subclasses do not need to deal with caching logic.
 
603
 
 
604
        This API is semi-public; it only for use by subclasses, all other code
 
605
        should consider it to be private.
 
606
        """
 
607
        raise NotImplementedError(self._gen_revision_history)
 
608
 
 
609
    @needs_read_lock
 
610
    def revision_history(self):
 
611
        """Return sequence of revision ids on this branch.
 
612
 
 
613
        This method will cache the revision history for as long as it is safe to
 
614
        do so.
 
615
        """
 
616
        if 'evil' in debug.debug_flags:
 
617
            mutter_callsite(3, "revision_history scales with history.")
 
618
        if self._revision_history_cache is not None:
 
619
            history = self._revision_history_cache
 
620
        else:
 
621
            history = self._gen_revision_history()
 
622
            self._cache_revision_history(history)
 
623
        return list(history)
 
624
 
 
625
    def revno(self):
 
626
        """Return current revision number for this branch.
 
627
 
 
628
        That is equivalent to the number of revisions committed to
 
629
        this branch.
 
630
        """
 
631
        return self.last_revision_info()[0]
 
632
 
 
633
    def unbind(self):
 
634
        """Older format branches cannot bind or unbind."""
 
635
        raise errors.UpgradeRequired(self.base)
 
636
 
 
637
    def set_append_revisions_only(self, enabled):
 
638
        """Older format branches are never restricted to append-only"""
 
639
        raise errors.UpgradeRequired(self.base)
 
640
 
 
641
    def last_revision(self):
 
642
        """Return last revision id, or NULL_REVISION."""
 
643
        return self.last_revision_info()[1]
 
644
 
 
645
    @needs_read_lock
 
646
    def last_revision_info(self):
 
647
        """Return information about the last revision.
 
648
 
 
649
        :return: A tuple (revno, revision_id).
 
650
        """
 
651
        if self._last_revision_info_cache is None:
 
652
            self._last_revision_info_cache = self._last_revision_info()
 
653
        return self._last_revision_info_cache
 
654
 
 
655
    def _last_revision_info(self):
 
656
        rh = self.revision_history()
 
657
        revno = len(rh)
 
658
        if revno:
 
659
            return (revno, rh[-1])
 
660
        else:
 
661
            return (0, _mod_revision.NULL_REVISION)
 
662
 
 
663
    @deprecated_method(deprecated_in((1, 6, 0)))
 
664
    def missing_revisions(self, other, stop_revision=None):
 
665
        """Return a list of new revisions that would perfectly fit.
 
666
 
 
667
        If self and other have not diverged, return a list of the revisions
 
668
        present in other, but missing from self.
 
669
        """
 
670
        self_history = self.revision_history()
 
671
        self_len = len(self_history)
 
672
        other_history = other.revision_history()
 
673
        other_len = len(other_history)
 
674
        common_index = min(self_len, other_len) -1
 
675
        if common_index >= 0 and \
 
676
            self_history[common_index] != other_history[common_index]:
 
677
            raise errors.DivergedBranches(self, other)
 
678
 
 
679
        if stop_revision is None:
 
680
            stop_revision = other_len
 
681
        else:
 
682
            if stop_revision > other_len:
 
683
                raise errors.NoSuchRevision(self, stop_revision)
 
684
        return other_history[self_len:stop_revision]
 
685
 
 
686
    @needs_write_lock
 
687
    def update_revisions(self, other, stop_revision=None, overwrite=False,
 
688
                         graph=None):
 
689
        """Pull in new perfect-fit revisions.
 
690
 
 
691
        :param other: Another Branch to pull from
 
692
        :param stop_revision: Updated until the given revision
 
693
        :param overwrite: Always set the branch pointer, rather than checking
 
694
            to see if it is a proper descendant.
 
695
        :param graph: A Graph object that can be used to query history
 
696
            information. This can be None.
 
697
        :return: None
 
698
        """
 
699
        other.lock_read()
 
700
        try:
 
701
            other_revno, other_last_revision = other.last_revision_info()
 
702
            stop_revno = None # unknown
 
703
            if stop_revision is None:
 
704
                stop_revision = other_last_revision
 
705
                if _mod_revision.is_null(stop_revision):
 
706
                    # if there are no commits, we're done.
 
707
                    return
 
708
                stop_revno = other_revno
 
709
 
 
710
            # what's the current last revision, before we fetch [and change it
 
711
            # possibly]
 
712
            last_rev = _mod_revision.ensure_null(self.last_revision())
 
713
            # we fetch here so that we don't process data twice in the common
 
714
            # case of having something to pull, and so that the check for
 
715
            # already merged can operate on the just fetched graph, which will
 
716
            # be cached in memory.
 
717
            self.fetch(other, stop_revision)
 
718
            # Check to see if one is an ancestor of the other
 
719
            if not overwrite:
 
720
                if graph is None:
 
721
                    graph = self.repository.get_graph()
 
722
                if self._check_if_descendant_or_diverged(
 
723
                        stop_revision, last_rev, graph, other):
 
724
                    # stop_revision is a descendant of last_rev, but we aren't
 
725
                    # overwriting, so we're done.
 
726
                    return
 
727
            if stop_revno is None:
 
728
                if graph is None:
 
729
                    graph = self.repository.get_graph()
 
730
                this_revno, this_last_revision = self.last_revision_info()
 
731
                stop_revno = graph.find_distance_to_null(stop_revision,
 
732
                                [(other_last_revision, other_revno),
 
733
                                 (this_last_revision, this_revno)])
 
734
            self.set_last_revision_info(stop_revno, stop_revision)
 
735
        finally:
 
736
            other.unlock()
 
737
 
 
738
    def revision_id_to_revno(self, revision_id):
 
739
        """Given a revision id, return its revno"""
 
740
        if _mod_revision.is_null(revision_id):
 
741
            return 0
 
742
        history = self.revision_history()
 
743
        try:
 
744
            return history.index(revision_id) + 1
 
745
        except ValueError:
 
746
            raise errors.NoSuchRevision(self, revision_id)
 
747
 
 
748
    def get_rev_id(self, revno, history=None):
 
749
        """Find the revision id of the specified revno."""
 
750
        if revno == 0:
 
751
            return _mod_revision.NULL_REVISION
 
752
        if history is None:
 
753
            history = self.revision_history()
 
754
        if revno <= 0 or revno > len(history):
 
755
            raise errors.NoSuchRevision(self, revno)
 
756
        return history[revno - 1]
 
757
 
 
758
    def pull(self, source, overwrite=False, stop_revision=None,
 
759
             possible_transports=None, _override_hook_target=None):
 
760
        """Mirror source into this branch.
 
761
 
 
762
        This branch is considered to be 'local', having low latency.
 
763
 
 
764
        :returns: PullResult instance
 
765
        """
 
766
        raise NotImplementedError(self.pull)
 
767
 
 
768
    def push(self, target, overwrite=False, stop_revision=None):
 
769
        """Mirror this branch into target.
 
770
 
 
771
        This branch is considered to be 'local', having low latency.
 
772
        """
 
773
        raise NotImplementedError(self.push)
 
774
 
 
775
    def basis_tree(self):
 
776
        """Return `Tree` object for last revision."""
 
777
        return self.repository.revision_tree(self.last_revision())
 
778
 
 
779
    def get_parent(self):
 
780
        """Return the parent location of the branch.
 
781
 
 
782
        This is the default location for pull/missing.  The usual
 
783
        pattern is that the user can override it by specifying a
 
784
        location.
 
785
        """
 
786
        raise NotImplementedError(self.get_parent)
 
787
 
 
788
    def _set_config_location(self, name, url, config=None,
 
789
                             make_relative=False):
 
790
        if config is None:
 
791
            config = self.get_config()
 
792
        if url is None:
 
793
            url = ''
 
794
        elif make_relative:
 
795
            url = urlutils.relative_url(self.base, url)
 
796
        config.set_user_option(name, url, warn_masked=True)
 
797
 
 
798
    def _get_config_location(self, name, config=None):
 
799
        if config is None:
 
800
            config = self.get_config()
 
801
        location = config.get_user_option(name)
 
802
        if location == '':
 
803
            location = None
 
804
        return location
 
805
 
 
806
    def get_submit_branch(self):
 
807
        """Return the submit location of the branch.
 
808
 
 
809
        This is the default location for bundle.  The usual
 
810
        pattern is that the user can override it by specifying a
 
811
        location.
 
812
        """
 
813
        return self.get_config().get_user_option('submit_branch')
 
814
 
 
815
    def set_submit_branch(self, location):
 
816
        """Return the submit location of the branch.
 
817
 
 
818
        This is the default location for bundle.  The usual
 
819
        pattern is that the user can override it by specifying a
 
820
        location.
 
821
        """
 
822
        self.get_config().set_user_option('submit_branch', location,
 
823
            warn_masked=True)
 
824
 
 
825
    def get_public_branch(self):
 
826
        """Return the public location of the branch.
 
827
 
 
828
        This is is used by merge directives.
 
829
        """
 
830
        return self._get_config_location('public_branch')
 
831
 
 
832
    def set_public_branch(self, location):
 
833
        """Return the submit location of the branch.
 
834
 
 
835
        This is the default location for bundle.  The usual
 
836
        pattern is that the user can override it by specifying a
 
837
        location.
 
838
        """
 
839
        self._set_config_location('public_branch', location)
 
840
 
 
841
    def get_push_location(self):
 
842
        """Return the None or the location to push this branch to."""
 
843
        push_loc = self.get_config().get_user_option('push_location')
 
844
        return push_loc
 
845
 
 
846
    def set_push_location(self, location):
 
847
        """Set a new push location for this branch."""
 
848
        raise NotImplementedError(self.set_push_location)
 
849
 
 
850
    def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
 
851
        """Run the post_change_branch_tip hooks."""
 
852
        hooks = Branch.hooks['post_change_branch_tip']
 
853
        if not hooks:
 
854
            return
 
855
        new_revno, new_revid = self.last_revision_info()
 
856
        params = ChangeBranchTipParams(
 
857
            self, old_revno, new_revno, old_revid, new_revid)
 
858
        for hook in hooks:
 
859
            hook(params)
 
860
 
 
861
    def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
 
862
        """Run the pre_change_branch_tip hooks."""
 
863
        hooks = Branch.hooks['pre_change_branch_tip']
 
864
        if not hooks:
 
865
            return
 
866
        old_revno, old_revid = self.last_revision_info()
 
867
        params = ChangeBranchTipParams(
 
868
            self, old_revno, new_revno, old_revid, new_revid)
 
869
        for hook in hooks:
 
870
            try:
 
871
                hook(params)
 
872
            except errors.TipChangeRejected:
 
873
                raise
 
874
            except Exception:
 
875
                exc_info = sys.exc_info()
 
876
                hook_name = Branch.hooks.get_hook_name(hook)
 
877
                raise errors.HookFailed(
 
878
                    'pre_change_branch_tip', hook_name, exc_info)
 
879
 
 
880
    def set_parent(self, url):
 
881
        raise NotImplementedError(self.set_parent)
 
882
 
 
883
    @needs_write_lock
 
884
    def update(self):
 
885
        """Synchronise this branch with the master branch if any.
 
886
 
 
887
        :return: None or the last_revision pivoted out during the update.
 
888
        """
 
889
        return None
 
890
 
 
891
    def check_revno(self, revno):
 
892
        """\
 
893
        Check whether a revno corresponds to any revision.
 
894
        Zero (the NULL revision) is considered valid.
 
895
        """
 
896
        if revno != 0:
 
897
            self.check_real_revno(revno)
 
898
 
 
899
    def check_real_revno(self, revno):
 
900
        """\
 
901
        Check whether a revno corresponds to a real revision.
 
902
        Zero (the NULL revision) is considered invalid
 
903
        """
 
904
        if revno < 1 or revno > self.revno():
 
905
            raise errors.InvalidRevisionNumber(revno)
 
906
 
 
907
    @needs_read_lock
 
908
    def clone(self, to_bzrdir, revision_id=None):
 
909
        """Clone this branch into to_bzrdir preserving all semantic values.
 
910
 
 
911
        revision_id: if not None, the revision history in the new branch will
 
912
                     be truncated to end with revision_id.
 
913
        """
 
914
        result = to_bzrdir.create_branch()
 
915
        self.copy_content_into(result, revision_id=revision_id)
 
916
        return  result
 
917
 
 
918
    @needs_read_lock
 
919
    def sprout(self, to_bzrdir, revision_id=None):
 
920
        """Create a new line of development from the branch, into to_bzrdir.
 
921
 
 
922
        to_bzrdir controls the branch format.
 
923
 
 
924
        revision_id: if not None, the revision history in the new branch will
 
925
                     be truncated to end with revision_id.
 
926
        """
 
927
        result = to_bzrdir.create_branch()
 
928
        self.copy_content_into(result, revision_id=revision_id)
 
929
        result.set_parent(self.bzrdir.root_transport.base)
 
930
        return result
 
931
 
 
932
    def _synchronize_history(self, destination, revision_id):
 
933
        """Synchronize last revision and revision history between branches.
 
934
 
 
935
        This version is most efficient when the destination is also a
 
936
        BzrBranch6, but works for BzrBranch5, as long as the destination's
 
937
        repository contains all the lefthand ancestors of the intended
 
938
        last_revision.  If not, set_last_revision_info will fail.
 
939
 
 
940
        :param destination: The branch to copy the history into
 
941
        :param revision_id: The revision-id to truncate history at.  May
 
942
          be None to copy complete history.
 
943
        """
 
944
        source_revno, source_revision_id = self.last_revision_info()
 
945
        if revision_id is None:
 
946
            revno, revision_id = source_revno, source_revision_id
 
947
        elif source_revision_id == revision_id:
 
948
            # we know the revno without needing to walk all of history
 
949
            revno = source_revno
 
950
        else:
 
951
            # To figure out the revno for a random revision, we need to build
 
952
            # the revision history, and count its length.
 
953
            # We don't care about the order, just how long it is.
 
954
            # Alternatively, we could start at the current location, and count
 
955
            # backwards. But there is no guarantee that we will find it since
 
956
            # it may be a merged revision.
 
957
            revno = len(list(self.repository.iter_reverse_revision_history(
 
958
                                                                revision_id)))
 
959
        destination.set_last_revision_info(revno, revision_id)
 
960
 
 
961
    @needs_read_lock
 
962
    def copy_content_into(self, destination, revision_id=None):
 
963
        """Copy the content of self into destination.
 
964
 
 
965
        revision_id: if not None, the revision history in the new branch will
 
966
                     be truncated to end with revision_id.
 
967
        """
 
968
        self._synchronize_history(destination, revision_id)
 
969
        try:
 
970
            parent = self.get_parent()
 
971
        except errors.InaccessibleParent, e:
 
972
            mutter('parent was not accessible to copy: %s', e)
 
973
        else:
 
974
            if parent:
 
975
                destination.set_parent(parent)
 
976
        if self._push_should_merge_tags():
 
977
            self.tags.merge_to(destination.tags)
 
978
 
 
979
    @needs_read_lock
 
980
    def check(self):
 
981
        """Check consistency of the branch.
 
982
 
 
983
        In particular this checks that revisions given in the revision-history
 
984
        do actually match up in the revision graph, and that they're all
 
985
        present in the repository.
 
986
 
 
987
        Callers will typically also want to check the repository.
 
988
 
 
989
        :return: A BranchCheckResult.
 
990
        """
 
991
        mainline_parent_id = None
 
992
        last_revno, last_revision_id = self.last_revision_info()
 
993
        real_rev_history = list(self.repository.iter_reverse_revision_history(
 
994
                                last_revision_id))
 
995
        real_rev_history.reverse()
 
996
        if len(real_rev_history) != last_revno:
 
997
            raise errors.BzrCheckError('revno does not match len(mainline)'
 
998
                ' %s != %s' % (last_revno, len(real_rev_history)))
 
999
        # TODO: We should probably also check that real_rev_history actually
 
1000
        #       matches self.revision_history()
 
1001
        for revision_id in real_rev_history:
 
1002
            try:
 
1003
                revision = self.repository.get_revision(revision_id)
 
1004
            except errors.NoSuchRevision, e:
 
1005
                raise errors.BzrCheckError("mainline revision {%s} not in repository"
 
1006
                            % revision_id)
 
1007
            # In general the first entry on the revision history has no parents.
 
1008
            # But it's not illegal for it to have parents listed; this can happen
 
1009
            # in imports from Arch when the parents weren't reachable.
 
1010
            if mainline_parent_id is not None:
 
1011
                if mainline_parent_id not in revision.parent_ids:
 
1012
                    raise errors.BzrCheckError("previous revision {%s} not listed among "
 
1013
                                        "parents of {%s}"
 
1014
                                        % (mainline_parent_id, revision_id))
 
1015
            mainline_parent_id = revision_id
 
1016
        return BranchCheckResult(self)
 
1017
 
 
1018
    def _get_checkout_format(self):
 
1019
        """Return the most suitable metadir for a checkout of this branch.
 
1020
        Weaves are used if this branch's repository uses weaves.
 
1021
        """
 
1022
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
 
1023
            from bzrlib.repofmt import weaverepo
 
1024
            format = bzrdir.BzrDirMetaFormat1()
 
1025
            format.repository_format = weaverepo.RepositoryFormat7()
 
1026
        else:
 
1027
            format = self.repository.bzrdir.checkout_metadir()
 
1028
            format.set_branch_format(self._format)
 
1029
        return format
 
1030
 
 
1031
    def create_checkout(self, to_location, revision_id=None,
 
1032
                        lightweight=False, accelerator_tree=None,
 
1033
                        hardlink=False):
 
1034
        """Create a checkout of a branch.
 
1035
 
 
1036
        :param to_location: The url to produce the checkout at
 
1037
        :param revision_id: The revision to check out
 
1038
        :param lightweight: If True, produce a lightweight checkout, otherwise,
 
1039
        produce a bound branch (heavyweight checkout)
 
1040
        :param accelerator_tree: A tree which can be used for retrieving file
 
1041
            contents more quickly than the revision tree, i.e. a workingtree.
 
1042
            The revision tree will be used for cases where accelerator_tree's
 
1043
            content is different.
 
1044
        :param hardlink: If true, hard-link files from accelerator_tree,
 
1045
            where possible.
 
1046
        :return: The tree of the created checkout
 
1047
        """
 
1048
        t = transport.get_transport(to_location)
 
1049
        t.ensure_base()
 
1050
        if lightweight:
 
1051
            format = self._get_checkout_format()
 
1052
            checkout = format.initialize_on_transport(t)
 
1053
            from_branch = BranchReferenceFormat().initialize(checkout, self)
 
1054
        else:
 
1055
            format = self._get_checkout_format()
 
1056
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
 
1057
                to_location, force_new_tree=False, format=format)
 
1058
            checkout = checkout_branch.bzrdir
 
1059
            checkout_branch.bind(self)
 
1060
            # pull up to the specified revision_id to set the initial
 
1061
            # branch tip correctly, and seed it with history.
 
1062
            checkout_branch.pull(self, stop_revision=revision_id)
 
1063
            from_branch=None
 
1064
        tree = checkout.create_workingtree(revision_id,
 
1065
                                           from_branch=from_branch,
 
1066
                                           accelerator_tree=accelerator_tree,
 
1067
                                           hardlink=hardlink)
 
1068
        basis_tree = tree.basis_tree()
 
1069
        basis_tree.lock_read()
 
1070
        try:
 
1071
            for path, file_id in basis_tree.iter_references():
 
1072
                reference_parent = self.reference_parent(file_id, path)
 
1073
                reference_parent.create_checkout(tree.abspath(path),
 
1074
                    basis_tree.get_reference_revision(file_id, path),
 
1075
                    lightweight)
 
1076
        finally:
 
1077
            basis_tree.unlock()
 
1078
        return tree
 
1079
 
 
1080
    @needs_write_lock
 
1081
    def reconcile(self, thorough=True):
 
1082
        """Make sure the data stored in this branch is consistent."""
 
1083
        from bzrlib.reconcile import BranchReconciler
 
1084
        reconciler = BranchReconciler(self, thorough=thorough)
 
1085
        reconciler.reconcile()
 
1086
        return reconciler
 
1087
 
 
1088
    def reference_parent(self, file_id, path):
 
1089
        """Return the parent branch for a tree-reference file_id
 
1090
        :param file_id: The file_id of the tree reference
 
1091
        :param path: The path of the file_id in the tree
 
1092
        :return: A branch associated with the file_id
 
1093
        """
 
1094
        # FIXME should provide multiple branches, based on config
 
1095
        return Branch.open(self.bzrdir.root_transport.clone(path).base)
 
1096
 
 
1097
    def supports_tags(self):
 
1098
        return self._format.supports_tags()
 
1099
 
 
1100
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
 
1101
                                         other_branch):
 
1102
        """Ensure that revision_b is a descendant of revision_a.
 
1103
 
 
1104
        This is a helper function for update_revisions.
 
1105
 
 
1106
        :raises: DivergedBranches if revision_b has diverged from revision_a.
 
1107
        :returns: True if revision_b is a descendant of revision_a.
 
1108
        """
 
1109
        relation = self._revision_relations(revision_a, revision_b, graph)
 
1110
        if relation == 'b_descends_from_a':
 
1111
            return True
 
1112
        elif relation == 'diverged':
 
1113
            raise errors.DivergedBranches(self, other_branch)
 
1114
        elif relation == 'a_descends_from_b':
 
1115
            return False
 
1116
        else:
 
1117
            raise AssertionError("invalid relation: %r" % (relation,))
 
1118
 
 
1119
    def _revision_relations(self, revision_a, revision_b, graph):
 
1120
        """Determine the relationship between two revisions.
 
1121
 
 
1122
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
 
1123
        """
 
1124
        heads = graph.heads([revision_a, revision_b])
 
1125
        if heads == set([revision_b]):
 
1126
            return 'b_descends_from_a'
 
1127
        elif heads == set([revision_a, revision_b]):
 
1128
            # These branches have diverged
 
1129
            return 'diverged'
 
1130
        elif heads == set([revision_a]):
 
1131
            return 'a_descends_from_b'
 
1132
        else:
 
1133
            raise AssertionError("invalid heads: %r" % (heads,))
 
1134
 
 
1135
 
 
1136
class BranchFormat(object):
 
1137
    """An encapsulation of the initialization and open routines for a format.
 
1138
 
 
1139
    Formats provide three things:
 
1140
     * An initialization routine,
 
1141
     * a format string,
 
1142
     * an open routine.
 
1143
 
 
1144
    Formats are placed in an dict by their format string for reference
 
1145
    during branch opening. Its not required that these be instances, they
 
1146
    can be classes themselves with class methods - it simply depends on
 
1147
    whether state is needed for a given format or not.
 
1148
 
 
1149
    Once a format is deprecated, just deprecate the initialize and open
 
1150
    methods on the format class. Do not deprecate the object, as the
 
1151
    object will be created every time regardless.
 
1152
    """
 
1153
 
 
1154
    _default_format = None
 
1155
    """The default format used for new branches."""
 
1156
 
 
1157
    _formats = {}
 
1158
    """The known formats."""
 
1159
 
 
1160
    def __eq__(self, other):
 
1161
        return self.__class__ is other.__class__
 
1162
 
 
1163
    def __ne__(self, other):
 
1164
        return not (self == other)
 
1165
 
 
1166
    @classmethod
 
1167
    def find_format(klass, a_bzrdir):
 
1168
        """Return the format for the branch object in a_bzrdir."""
 
1169
        try:
 
1170
            transport = a_bzrdir.get_branch_transport(None)
 
1171
            format_string = transport.get("format").read()
 
1172
            return klass._formats[format_string]
 
1173
        except errors.NoSuchFile:
 
1174
            raise errors.NotBranchError(path=transport.base)
 
1175
        except KeyError:
 
1176
            raise errors.UnknownFormatError(format=format_string, kind='branch')
 
1177
 
 
1178
    @classmethod
 
1179
    def get_default_format(klass):
 
1180
        """Return the current default format."""
 
1181
        return klass._default_format
 
1182
 
 
1183
    def get_reference(self, a_bzrdir):
 
1184
        """Get the target reference of the branch in a_bzrdir.
 
1185
 
 
1186
        format probing must have been completed before calling
 
1187
        this method - it is assumed that the format of the branch
 
1188
        in a_bzrdir is correct.
 
1189
 
 
1190
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1191
        :return: None if the branch is not a reference branch.
 
1192
        """
 
1193
        return None
 
1194
 
 
1195
    @classmethod
 
1196
    def set_reference(self, a_bzrdir, to_branch):
 
1197
        """Set the target reference of the branch in a_bzrdir.
 
1198
 
 
1199
        format probing must have been completed before calling
 
1200
        this method - it is assumed that the format of the branch
 
1201
        in a_bzrdir is correct.
 
1202
 
 
1203
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1204
        :param to_branch: branch that the checkout is to reference
 
1205
        """
 
1206
        raise NotImplementedError(self.set_reference)
 
1207
 
 
1208
    def get_format_string(self):
 
1209
        """Return the ASCII format string that identifies this format."""
 
1210
        raise NotImplementedError(self.get_format_string)
 
1211
 
 
1212
    def get_format_description(self):
 
1213
        """Return the short format description for this format."""
 
1214
        raise NotImplementedError(self.get_format_description)
 
1215
 
 
1216
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1217
                           set_format=True):
 
1218
        """Initialize a branch in a bzrdir, with specified files
 
1219
 
 
1220
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1221
        :param utf8_files: The files to create as a list of
 
1222
            (filename, content) tuples
 
1223
        :param set_format: If True, set the format with
 
1224
            self.get_format_string.  (BzrBranch4 has its format set
 
1225
            elsewhere)
 
1226
        :return: a branch in this format
 
1227
        """
 
1228
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1229
        branch_transport = a_bzrdir.get_branch_transport(self)
 
1230
        lock_map = {
 
1231
            'metadir': ('lock', lockdir.LockDir),
 
1232
            'branch4': ('branch-lock', lockable_files.TransportLock),
 
1233
        }
 
1234
        lock_name, lock_class = lock_map[lock_type]
 
1235
        control_files = lockable_files.LockableFiles(branch_transport,
 
1236
            lock_name, lock_class)
 
1237
        control_files.create_lock()
 
1238
        control_files.lock_write()
 
1239
        if set_format:
 
1240
            utf8_files += [('format', self.get_format_string())]
 
1241
        try:
 
1242
            for (filename, content) in utf8_files:
 
1243
                branch_transport.put_bytes(
 
1244
                    filename, content,
 
1245
                    mode=a_bzrdir._get_file_mode())
 
1246
        finally:
 
1247
            control_files.unlock()
 
1248
        return self.open(a_bzrdir, _found=True)
 
1249
 
 
1250
    def initialize(self, a_bzrdir):
 
1251
        """Create a branch of this format in a_bzrdir."""
 
1252
        raise NotImplementedError(self.initialize)
 
1253
 
 
1254
    def is_supported(self):
 
1255
        """Is this format supported?
 
1256
 
 
1257
        Supported formats can be initialized and opened.
 
1258
        Unsupported formats may not support initialization or committing or
 
1259
        some other features depending on the reason for not being supported.
 
1260
        """
 
1261
        return True
 
1262
 
 
1263
    def network_name(self):
 
1264
        """A simple byte string uniquely identifying this format for RPC calls.
 
1265
 
 
1266
        MetaDir branch formats use their disk format string to identify the
 
1267
        repository over the wire. All in one formats such as bzr < 0.8, and
 
1268
        foreign formats like svn/git and hg should use some marker which is
 
1269
        unique and immutable.
 
1270
        """
 
1271
        raise NotImplementedError(self.network_name)
 
1272
 
 
1273
    def open(self, a_bzrdir, _found=False):
 
1274
        """Return the branch object for a_bzrdir
 
1275
 
 
1276
        _found is a private parameter, do not use it. It is used to indicate
 
1277
               if format probing has already be done.
 
1278
        """
 
1279
        raise NotImplementedError(self.open)
 
1280
 
 
1281
    @classmethod
 
1282
    def register_format(klass, format):
 
1283
        """Register a metadir format."""
 
1284
        klass._formats[format.get_format_string()] = format
 
1285
        # Metadir formats have a network name of their format string.
 
1286
        network_format_registry.register(format.get_format_string(), format)
 
1287
 
 
1288
    @classmethod
 
1289
    def set_default_format(klass, format):
 
1290
        klass._default_format = format
 
1291
 
 
1292
    def supports_stacking(self):
 
1293
        """True if this format records a stacked-on branch."""
 
1294
        return False
 
1295
 
 
1296
    @classmethod
 
1297
    def unregister_format(klass, format):
 
1298
        del klass._formats[format.get_format_string()]
 
1299
 
 
1300
    def __str__(self):
 
1301
        return self.get_format_description().rstrip()
 
1302
 
 
1303
    def supports_tags(self):
 
1304
        """True if this format supports tags stored in the branch"""
 
1305
        return False  # by default
 
1306
 
 
1307
 
 
1308
class BranchHooks(Hooks):
 
1309
    """A dictionary mapping hook name to a list of callables for branch hooks.
 
1310
 
 
1311
    e.g. ['set_rh'] Is the list of items to be called when the
 
1312
    set_revision_history function is invoked.
 
1313
    """
 
1314
 
 
1315
    def __init__(self):
 
1316
        """Create the default hooks.
 
1317
 
 
1318
        These are all empty initially, because by default nothing should get
 
1319
        notified.
 
1320
        """
 
1321
        Hooks.__init__(self)
 
1322
        # Introduced in 0.15:
 
1323
        # invoked whenever the revision history has been set
 
1324
        # with set_revision_history. The api signature is
 
1325
        # (branch, revision_history), and the branch will
 
1326
        # be write-locked.
 
1327
        self['set_rh'] = []
 
1328
        # Invoked after a branch is opened. The api signature is (branch).
 
1329
        self['open'] = []
 
1330
        # invoked after a push operation completes.
 
1331
        # the api signature is
 
1332
        # (push_result)
 
1333
        # containing the members
 
1334
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
 
1335
        # where local is the local target branch or None, master is the target
 
1336
        # master branch, and the rest should be self explanatory. The source
 
1337
        # is read locked and the target branches write locked. Source will
 
1338
        # be the local low-latency branch.
 
1339
        self['post_push'] = []
 
1340
        # invoked after a pull operation completes.
 
1341
        # the api signature is
 
1342
        # (pull_result)
 
1343
        # containing the members
 
1344
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
 
1345
        # where local is the local branch or None, master is the target
 
1346
        # master branch, and the rest should be self explanatory. The source
 
1347
        # is read locked and the target branches write locked. The local
 
1348
        # branch is the low-latency branch.
 
1349
        self['post_pull'] = []
 
1350
        # invoked before a commit operation takes place.
 
1351
        # the api signature is
 
1352
        # (local, master, old_revno, old_revid, future_revno, future_revid,
 
1353
        #  tree_delta, future_tree).
 
1354
        # old_revid is NULL_REVISION for the first commit to a branch
 
1355
        # tree_delta is a TreeDelta object describing changes from the basis
 
1356
        # revision, hooks MUST NOT modify this delta
 
1357
        # future_tree is an in-memory tree obtained from
 
1358
        # CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
 
1359
        self['pre_commit'] = []
 
1360
        # invoked after a commit operation completes.
 
1361
        # the api signature is
 
1362
        # (local, master, old_revno, old_revid, new_revno, new_revid)
 
1363
        # old_revid is NULL_REVISION for the first commit to a branch.
 
1364
        self['post_commit'] = []
 
1365
        # invoked after a uncommit operation completes.
 
1366
        # the api signature is
 
1367
        # (local, master, old_revno, old_revid, new_revno, new_revid) where
 
1368
        # local is the local branch or None, master is the target branch,
 
1369
        # and an empty branch recieves new_revno of 0, new_revid of None.
 
1370
        self['post_uncommit'] = []
 
1371
        # Introduced in 1.6
 
1372
        # Invoked before the tip of a branch changes.
 
1373
        # the api signature is
 
1374
        # (params) where params is a ChangeBranchTipParams with the members
 
1375
        # (branch, old_revno, new_revno, old_revid, new_revid)
 
1376
        self['pre_change_branch_tip'] = []
 
1377
        # Introduced in 1.4
 
1378
        # Invoked after the tip of a branch changes.
 
1379
        # the api signature is
 
1380
        # (params) where params is a ChangeBranchTipParams with the members
 
1381
        # (branch, old_revno, new_revno, old_revid, new_revid)
 
1382
        self['post_change_branch_tip'] = []
 
1383
        # Introduced in 1.9
 
1384
        # Invoked when a stacked branch activates its fallback locations and
 
1385
        # allows the transformation of the url of said location.
 
1386
        # the api signature is
 
1387
        # (branch, url) where branch is the branch having its fallback
 
1388
        # location activated and url is the url for the fallback location.
 
1389
        # The hook should return a url.
 
1390
        self['transform_fallback_location'] = []
 
1391
 
 
1392
 
 
1393
# install the default hooks into the Branch class.
 
1394
Branch.hooks = BranchHooks()
 
1395
 
 
1396
 
 
1397
class ChangeBranchTipParams(object):
 
1398
    """Object holding parameters passed to *_change_branch_tip hooks.
 
1399
 
 
1400
    There are 5 fields that hooks may wish to access:
 
1401
 
 
1402
    :ivar branch: the branch being changed
 
1403
    :ivar old_revno: revision number before the change
 
1404
    :ivar new_revno: revision number after the change
 
1405
    :ivar old_revid: revision id before the change
 
1406
    :ivar new_revid: revision id after the change
 
1407
 
 
1408
    The revid fields are strings. The revno fields are integers.
 
1409
    """
 
1410
 
 
1411
    def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
 
1412
        """Create a group of ChangeBranchTip parameters.
 
1413
 
 
1414
        :param branch: The branch being changed.
 
1415
        :param old_revno: Revision number before the change.
 
1416
        :param new_revno: Revision number after the change.
 
1417
        :param old_revid: Tip revision id before the change.
 
1418
        :param new_revid: Tip revision id after the change.
 
1419
        """
 
1420
        self.branch = branch
 
1421
        self.old_revno = old_revno
 
1422
        self.new_revno = new_revno
 
1423
        self.old_revid = old_revid
 
1424
        self.new_revid = new_revid
 
1425
 
 
1426
    def __eq__(self, other):
 
1427
        return self.__dict__ == other.__dict__
 
1428
 
 
1429
    def __repr__(self):
 
1430
        return "<%s of %s from (%s, %s) to (%s, %s)>" % (
 
1431
            self.__class__.__name__, self.branch,
 
1432
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
 
1433
 
 
1434
 
 
1435
class BzrBranchFormat4(BranchFormat):
 
1436
    """Bzr branch format 4.
 
1437
 
 
1438
    This format has:
 
1439
     - a revision-history file.
 
1440
     - a branch-lock lock file [ to be shared with the bzrdir ]
 
1441
    """
 
1442
 
 
1443
    def get_format_description(self):
 
1444
        """See BranchFormat.get_format_description()."""
 
1445
        return "Branch format 4"
 
1446
 
 
1447
    def initialize(self, a_bzrdir):
 
1448
        """Create a branch of this format in a_bzrdir."""
 
1449
        utf8_files = [('revision-history', ''),
 
1450
                      ('branch-name', ''),
 
1451
                      ]
 
1452
        return self._initialize_helper(a_bzrdir, utf8_files,
 
1453
                                       lock_type='branch4', set_format=False)
 
1454
 
 
1455
    def __init__(self):
 
1456
        super(BzrBranchFormat4, self).__init__()
 
1457
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1458
 
 
1459
    def network_name(self):
 
1460
        """The network name for this format is the control dirs disk label."""
 
1461
        return self._matchingbzrdir.get_format_string()
 
1462
 
 
1463
    def open(self, a_bzrdir, _found=False):
 
1464
        """Return the branch object for a_bzrdir
 
1465
 
 
1466
        _found is a private parameter, do not use it. It is used to indicate
 
1467
               if format probing has already be done.
 
1468
        """
 
1469
        if not _found:
 
1470
            # we are being called directly and must probe.
 
1471
            raise NotImplementedError
 
1472
        return BzrBranch(_format=self,
 
1473
                         _control_files=a_bzrdir._control_files,
 
1474
                         a_bzrdir=a_bzrdir,
 
1475
                         _repository=a_bzrdir.open_repository())
 
1476
 
 
1477
    def __str__(self):
 
1478
        return "Bazaar-NG branch format 4"
 
1479
 
 
1480
 
 
1481
class BranchFormatMetadir(BranchFormat):
 
1482
    """Common logic for meta-dir based branch formats."""
 
1483
 
 
1484
    def _branch_class(self):
 
1485
        """What class to instantiate on open calls."""
 
1486
        raise NotImplementedError(self._branch_class)
 
1487
 
 
1488
    def network_name(self):
 
1489
        """A simple byte string uniquely identifying this format for RPC calls.
 
1490
 
 
1491
        Metadir branch formats use their format string.
 
1492
        """
 
1493
        return self.get_format_string()
 
1494
 
 
1495
    def open(self, a_bzrdir, _found=False):
 
1496
        """Return the branch object for a_bzrdir.
 
1497
 
 
1498
        _found is a private parameter, do not use it. It is used to indicate
 
1499
               if format probing has already be done.
 
1500
        """
 
1501
        if not _found:
 
1502
            format = BranchFormat.find_format(a_bzrdir)
 
1503
            if format.__class__ != self.__class__:
 
1504
                raise AssertionError("wrong format %r found for %r" %
 
1505
                    (format, self))
 
1506
        try:
 
1507
            transport = a_bzrdir.get_branch_transport(None)
 
1508
            control_files = lockable_files.LockableFiles(transport, 'lock',
 
1509
                                                         lockdir.LockDir)
 
1510
            return self._branch_class()(_format=self,
 
1511
                              _control_files=control_files,
 
1512
                              a_bzrdir=a_bzrdir,
 
1513
                              _repository=a_bzrdir.find_repository())
 
1514
        except errors.NoSuchFile:
 
1515
            raise errors.NotBranchError(path=transport.base)
 
1516
 
 
1517
    def __init__(self):
 
1518
        super(BranchFormatMetadir, self).__init__()
 
1519
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1520
        self._matchingbzrdir.set_branch_format(self)
 
1521
 
 
1522
    def supports_tags(self):
 
1523
        return True
 
1524
 
 
1525
 
 
1526
class BzrBranchFormat5(BranchFormatMetadir):
 
1527
    """Bzr branch format 5.
 
1528
 
 
1529
    This format has:
 
1530
     - a revision-history file.
 
1531
     - a format string
 
1532
     - a lock dir guarding the branch itself
 
1533
     - all of this stored in a branch/ subdirectory
 
1534
     - works with shared repositories.
 
1535
 
 
1536
    This format is new in bzr 0.8.
 
1537
    """
 
1538
 
 
1539
    def _branch_class(self):
 
1540
        return BzrBranch5
 
1541
 
 
1542
    def get_format_string(self):
 
1543
        """See BranchFormat.get_format_string()."""
 
1544
        return "Bazaar-NG branch format 5\n"
 
1545
 
 
1546
    def get_format_description(self):
 
1547
        """See BranchFormat.get_format_description()."""
 
1548
        return "Branch format 5"
 
1549
 
 
1550
    def initialize(self, a_bzrdir):
 
1551
        """Create a branch of this format in a_bzrdir."""
 
1552
        utf8_files = [('revision-history', ''),
 
1553
                      ('branch-name', ''),
 
1554
                      ]
 
1555
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1556
 
 
1557
    def supports_tags(self):
 
1558
        return False
 
1559
 
 
1560
 
 
1561
class BzrBranchFormat6(BranchFormatMetadir):
 
1562
    """Branch format with last-revision and tags.
 
1563
 
 
1564
    Unlike previous formats, this has no explicit revision history. Instead,
 
1565
    this just stores the last-revision, and the left-hand history leading
 
1566
    up to there is the history.
 
1567
 
 
1568
    This format was introduced in bzr 0.15
 
1569
    and became the default in 0.91.
 
1570
    """
 
1571
 
 
1572
    def _branch_class(self):
 
1573
        return BzrBranch6
 
1574
 
 
1575
    def get_format_string(self):
 
1576
        """See BranchFormat.get_format_string()."""
 
1577
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
 
1578
 
 
1579
    def get_format_description(self):
 
1580
        """See BranchFormat.get_format_description()."""
 
1581
        return "Branch format 6"
 
1582
 
 
1583
    def initialize(self, a_bzrdir):
 
1584
        """Create a branch of this format in a_bzrdir."""
 
1585
        utf8_files = [('last-revision', '0 null:\n'),
 
1586
                      ('branch.conf', ''),
 
1587
                      ('tags', ''),
 
1588
                      ]
 
1589
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1590
 
 
1591
 
 
1592
class BzrBranchFormat7(BranchFormatMetadir):
 
1593
    """Branch format with last-revision, tags, and a stacked location pointer.
 
1594
 
 
1595
    The stacked location pointer is passed down to the repository and requires
 
1596
    a repository format with supports_external_lookups = True.
 
1597
 
 
1598
    This format was introduced in bzr 1.6.
 
1599
    """
 
1600
 
 
1601
    def _branch_class(self):
 
1602
        return BzrBranch7
 
1603
 
 
1604
    def get_format_string(self):
 
1605
        """See BranchFormat.get_format_string()."""
 
1606
        return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
 
1607
 
 
1608
    def get_format_description(self):
 
1609
        """See BranchFormat.get_format_description()."""
 
1610
        return "Branch format 7"
 
1611
 
 
1612
    def initialize(self, a_bzrdir):
 
1613
        """Create a branch of this format in a_bzrdir."""
 
1614
        utf8_files = [('last-revision', '0 null:\n'),
 
1615
                      ('branch.conf', ''),
 
1616
                      ('tags', ''),
 
1617
                      ]
 
1618
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1619
 
 
1620
    def __init__(self):
 
1621
        super(BzrBranchFormat7, self).__init__()
 
1622
        self._matchingbzrdir.repository_format = \
 
1623
            RepositoryFormatKnitPack5RichRoot()
 
1624
 
 
1625
    def supports_stacking(self):
 
1626
        return True
 
1627
 
 
1628
 
 
1629
class BranchReferenceFormat(BranchFormat):
 
1630
    """Bzr branch reference format.
 
1631
 
 
1632
    Branch references are used in implementing checkouts, they
 
1633
    act as an alias to the real branch which is at some other url.
 
1634
 
 
1635
    This format has:
 
1636
     - A location file
 
1637
     - a format string
 
1638
    """
 
1639
 
 
1640
    def get_format_string(self):
 
1641
        """See BranchFormat.get_format_string()."""
 
1642
        return "Bazaar-NG Branch Reference Format 1\n"
 
1643
 
 
1644
    def get_format_description(self):
 
1645
        """See BranchFormat.get_format_description()."""
 
1646
        return "Checkout reference format 1"
 
1647
 
 
1648
    def get_reference(self, a_bzrdir):
 
1649
        """See BranchFormat.get_reference()."""
 
1650
        transport = a_bzrdir.get_branch_transport(None)
 
1651
        return transport.get('location').read()
 
1652
 
 
1653
    def set_reference(self, a_bzrdir, to_branch):
 
1654
        """See BranchFormat.set_reference()."""
 
1655
        transport = a_bzrdir.get_branch_transport(None)
 
1656
        location = transport.put_bytes('location', to_branch.base)
 
1657
 
 
1658
    def initialize(self, a_bzrdir, target_branch=None):
 
1659
        """Create a branch of this format in a_bzrdir."""
 
1660
        if target_branch is None:
 
1661
            # this format does not implement branch itself, thus the implicit
 
1662
            # creation contract must see it as uninitializable
 
1663
            raise errors.UninitializableFormat(self)
 
1664
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1665
        branch_transport = a_bzrdir.get_branch_transport(self)
 
1666
        branch_transport.put_bytes('location',
 
1667
            target_branch.bzrdir.root_transport.base)
 
1668
        branch_transport.put_bytes('format', self.get_format_string())
 
1669
        return self.open(
 
1670
            a_bzrdir, _found=True,
 
1671
            possible_transports=[target_branch.bzrdir.root_transport])
 
1672
 
 
1673
    def __init__(self):
 
1674
        super(BranchReferenceFormat, self).__init__()
 
1675
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1676
        self._matchingbzrdir.set_branch_format(self)
 
1677
 
 
1678
    def _make_reference_clone_function(format, a_branch):
 
1679
        """Create a clone() routine for a branch dynamically."""
 
1680
        def clone(to_bzrdir, revision_id=None):
 
1681
            """See Branch.clone()."""
 
1682
            return format.initialize(to_bzrdir, a_branch)
 
1683
            # cannot obey revision_id limits when cloning a reference ...
 
1684
            # FIXME RBC 20060210 either nuke revision_id for clone, or
 
1685
            # emit some sort of warning/error to the caller ?!
 
1686
        return clone
 
1687
 
 
1688
    def open(self, a_bzrdir, _found=False, location=None,
 
1689
             possible_transports=None):
 
1690
        """Return the branch that the branch reference in a_bzrdir points at.
 
1691
 
 
1692
        _found is a private parameter, do not use it. It is used to indicate
 
1693
               if format probing has already be done.
 
1694
        """
 
1695
        if not _found:
 
1696
            format = BranchFormat.find_format(a_bzrdir)
 
1697
            if format.__class__ != self.__class__:
 
1698
                raise AssertionError("wrong format %r found for %r" %
 
1699
                    (format, self))
 
1700
        if location is None:
 
1701
            location = self.get_reference(a_bzrdir)
 
1702
        real_bzrdir = bzrdir.BzrDir.open(
 
1703
            location, possible_transports=possible_transports)
 
1704
        result = real_bzrdir.open_branch()
 
1705
        # this changes the behaviour of result.clone to create a new reference
 
1706
        # rather than a copy of the content of the branch.
 
1707
        # I did not use a proxy object because that needs much more extensive
 
1708
        # testing, and we are only changing one behaviour at the moment.
 
1709
        # If we decide to alter more behaviours - i.e. the implicit nickname
 
1710
        # then this should be refactored to introduce a tested proxy branch
 
1711
        # and a subclass of that for use in overriding clone() and ....
 
1712
        # - RBC 20060210
 
1713
        result.clone = self._make_reference_clone_function(result)
 
1714
        return result
 
1715
 
 
1716
 
 
1717
network_format_registry = registry.FormatRegistry()
 
1718
"""Registry of formats indexed by their network name.
 
1719
 
 
1720
The network name for a repository format is an identifier that can be used when
 
1721
referring to formats with smart server operations. See
 
1722
BranchFormat.network_name() for more detail.
 
1723
"""
 
1724
 
 
1725
 
 
1726
# formats which have no format string are not discoverable
 
1727
# and not independently creatable, so are not registered.
 
1728
__format5 = BzrBranchFormat5()
 
1729
__format6 = BzrBranchFormat6()
 
1730
__format7 = BzrBranchFormat7()
 
1731
BranchFormat.register_format(__format5)
 
1732
BranchFormat.register_format(BranchReferenceFormat())
 
1733
BranchFormat.register_format(__format6)
 
1734
BranchFormat.register_format(__format7)
 
1735
BranchFormat.set_default_format(__format6)
 
1736
_legacy_formats = [BzrBranchFormat4(),
 
1737
    ]
 
1738
network_format_registry.register(
 
1739
    _legacy_formats[0].network_name(), _legacy_formats[0])
 
1740
 
 
1741
 
 
1742
class BzrBranch(Branch):
 
1743
    """A branch stored in the actual filesystem.
 
1744
 
 
1745
    Note that it's "local" in the context of the filesystem; it doesn't
 
1746
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
1747
    it's writable, and can be accessed via the normal filesystem API.
 
1748
 
 
1749
    :ivar _transport: Transport for file operations on this branch's
 
1750
        control files, typically pointing to the .bzr/branch directory.
 
1751
    :ivar repository: Repository for this branch.
 
1752
    :ivar base: The url of the base directory for this branch; the one
 
1753
        containing the .bzr directory.
 
1754
    """
 
1755
 
 
1756
    def __init__(self, _format=None,
 
1757
                 _control_files=None, a_bzrdir=None, _repository=None):
 
1758
        """Create new branch object at a particular location."""
 
1759
        if a_bzrdir is None:
 
1760
            raise ValueError('a_bzrdir must be supplied')
 
1761
        else:
 
1762
            self.bzrdir = a_bzrdir
 
1763
        self._base = self.bzrdir.transport.clone('..').base
 
1764
        # XXX: We should be able to just do
 
1765
        #   self.base = self.bzrdir.root_transport.base
 
1766
        # but this does not quite work yet -- mbp 20080522
 
1767
        self._format = _format
 
1768
        if _control_files is None:
 
1769
            raise ValueError('BzrBranch _control_files is None')
 
1770
        self.control_files = _control_files
 
1771
        self._transport = _control_files._transport
 
1772
        self.repository = _repository
 
1773
        Branch.__init__(self)
 
1774
 
 
1775
    def __str__(self):
 
1776
        return '%s(%r)' % (self.__class__.__name__, self.base)
 
1777
 
 
1778
    __repr__ = __str__
 
1779
 
 
1780
    def _get_base(self):
 
1781
        """Returns the directory containing the control directory."""
 
1782
        return self._base
 
1783
 
 
1784
    base = property(_get_base, doc="The URL for the root of this branch.")
 
1785
 
 
1786
    def is_locked(self):
 
1787
        return self.control_files.is_locked()
 
1788
 
 
1789
    def lock_write(self, token=None):
 
1790
        repo_token = self.repository.lock_write()
 
1791
        try:
 
1792
            token = self.control_files.lock_write(token=token)
 
1793
        except:
 
1794
            self.repository.unlock()
 
1795
            raise
 
1796
        return token
 
1797
 
 
1798
    def lock_read(self):
 
1799
        self.repository.lock_read()
 
1800
        try:
 
1801
            self.control_files.lock_read()
 
1802
        except:
 
1803
            self.repository.unlock()
 
1804
            raise
 
1805
 
 
1806
    def unlock(self):
 
1807
        # TODO: test for failed two phase locks. This is known broken.
 
1808
        try:
 
1809
            self.control_files.unlock()
 
1810
        finally:
 
1811
            self.repository.unlock()
 
1812
        if not self.control_files.is_locked():
 
1813
            # we just released the lock
 
1814
            self._clear_cached_state()
 
1815
 
 
1816
    def peek_lock_mode(self):
 
1817
        if self.control_files._lock_count == 0:
 
1818
            return None
 
1819
        else:
 
1820
            return self.control_files._lock_mode
 
1821
 
 
1822
    def get_physical_lock_status(self):
 
1823
        return self.control_files.get_physical_lock_status()
 
1824
 
 
1825
    @needs_read_lock
 
1826
    def print_file(self, file, revision_id):
 
1827
        """See Branch.print_file."""
 
1828
        return self.repository.print_file(file, revision_id)
 
1829
 
 
1830
    def _write_revision_history(self, history):
 
1831
        """Factored out of set_revision_history.
 
1832
 
 
1833
        This performs the actual writing to disk.
 
1834
        It is intended to be called by BzrBranch5.set_revision_history."""
 
1835
        self._transport.put_bytes(
 
1836
            'revision-history', '\n'.join(history),
 
1837
            mode=self.bzrdir._get_file_mode())
 
1838
 
 
1839
    @needs_write_lock
 
1840
    def set_revision_history(self, rev_history):
 
1841
        """See Branch.set_revision_history."""
 
1842
        if 'evil' in debug.debug_flags:
 
1843
            mutter_callsite(3, "set_revision_history scales with history.")
 
1844
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
1845
        for rev_id in rev_history:
 
1846
            check_not_reserved_id(rev_id)
 
1847
        if Branch.hooks['post_change_branch_tip']:
 
1848
            # Don't calculate the last_revision_info() if there are no hooks
 
1849
            # that will use it.
 
1850
            old_revno, old_revid = self.last_revision_info()
 
1851
        if len(rev_history) == 0:
 
1852
            revid = _mod_revision.NULL_REVISION
 
1853
        else:
 
1854
            revid = rev_history[-1]
 
1855
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
1856
        self._write_revision_history(rev_history)
 
1857
        self._clear_cached_state()
 
1858
        self._cache_revision_history(rev_history)
 
1859
        for hook in Branch.hooks['set_rh']:
 
1860
            hook(self, rev_history)
 
1861
        if Branch.hooks['post_change_branch_tip']:
 
1862
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
1863
 
 
1864
    def _synchronize_history(self, destination, revision_id):
 
1865
        """Synchronize last revision and revision history between branches.
 
1866
 
 
1867
        This version is most efficient when the destination is also a
 
1868
        BzrBranch5, but works for BzrBranch6 as long as the revision
 
1869
        history is the true lefthand parent history, and all of the revisions
 
1870
        are in the destination's repository.  If not, set_revision_history
 
1871
        will fail.
 
1872
 
 
1873
        :param destination: The branch to copy the history into
 
1874
        :param revision_id: The revision-id to truncate history at.  May
 
1875
          be None to copy complete history.
 
1876
        """
 
1877
        if not isinstance(destination._format, BzrBranchFormat5):
 
1878
            super(BzrBranch, self)._synchronize_history(
 
1879
                destination, revision_id)
 
1880
            return
 
1881
        if revision_id == _mod_revision.NULL_REVISION:
 
1882
            new_history = []
 
1883
        else:
 
1884
            new_history = self.revision_history()
 
1885
        if revision_id is not None and new_history != []:
 
1886
            try:
 
1887
                new_history = new_history[:new_history.index(revision_id) + 1]
 
1888
            except ValueError:
 
1889
                rev = self.repository.get_revision(revision_id)
 
1890
                new_history = rev.get_history(self.repository)[1:]
 
1891
        destination.set_revision_history(new_history)
 
1892
 
 
1893
    @needs_write_lock
 
1894
    def set_last_revision_info(self, revno, revision_id):
 
1895
        """Set the last revision of this branch.
 
1896
 
 
1897
        The caller is responsible for checking that the revno is correct
 
1898
        for this revision id.
 
1899
 
 
1900
        It may be possible to set the branch last revision to an id not
 
1901
        present in the repository.  However, branches can also be
 
1902
        configured to check constraints on history, in which case this may not
 
1903
        be permitted.
 
1904
        """
 
1905
        revision_id = _mod_revision.ensure_null(revision_id)
 
1906
        # this old format stores the full history, but this api doesn't
 
1907
        # provide it, so we must generate, and might as well check it's
 
1908
        # correct
 
1909
        history = self._lefthand_history(revision_id)
 
1910
        if len(history) != revno:
 
1911
            raise AssertionError('%d != %d' % (len(history), revno))
 
1912
        self.set_revision_history(history)
 
1913
 
 
1914
    def _gen_revision_history(self):
 
1915
        history = self._transport.get_bytes('revision-history').split('\n')
 
1916
        if history[-1:] == ['']:
 
1917
            # There shouldn't be a trailing newline, but just in case.
 
1918
            history.pop()
 
1919
        return history
 
1920
 
 
1921
    @needs_write_lock
 
1922
    def generate_revision_history(self, revision_id, last_rev=None,
 
1923
        other_branch=None):
 
1924
        """Create a new revision history that will finish with revision_id.
 
1925
 
 
1926
        :param revision_id: the new tip to use.
 
1927
        :param last_rev: The previous last_revision. If not None, then this
 
1928
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
1929
        :param other_branch: The other branch that DivergedBranches should
 
1930
            raise with respect to.
 
1931
        """
 
1932
        self.set_revision_history(self._lefthand_history(revision_id,
 
1933
            last_rev, other_branch))
 
1934
 
 
1935
    def basis_tree(self):
 
1936
        """See Branch.basis_tree."""
 
1937
        return self.repository.revision_tree(self.last_revision())
 
1938
 
 
1939
    @needs_write_lock
 
1940
    def pull(self, source, overwrite=False, stop_revision=None,
 
1941
             _hook_master=None, run_hooks=True, possible_transports=None,
 
1942
             _override_hook_target=None):
 
1943
        """See Branch.pull.
 
1944
 
 
1945
        :param _hook_master: Private parameter - set the branch to
 
1946
            be supplied as the master to pull hooks.
 
1947
        :param run_hooks: Private parameter - if false, this branch
 
1948
            is being called because it's the master of the primary branch,
 
1949
            so it should not run its hooks.
 
1950
        :param _override_hook_target: Private parameter - set the branch to be
 
1951
            supplied as the target_branch to pull hooks.
 
1952
        """
 
1953
        result = PullResult()
 
1954
        result.source_branch = source
 
1955
        if _override_hook_target is None:
 
1956
            result.target_branch = self
 
1957
        else:
 
1958
            result.target_branch = _override_hook_target
 
1959
        source.lock_read()
 
1960
        try:
 
1961
            # We assume that during 'pull' the local repository is closer than
 
1962
            # the remote one.
 
1963
            graph = self.repository.get_graph(source.repository)
 
1964
            result.old_revno, result.old_revid = self.last_revision_info()
 
1965
            self.update_revisions(source, stop_revision, overwrite=overwrite,
 
1966
                                  graph=graph)
 
1967
            result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
 
1968
            result.new_revno, result.new_revid = self.last_revision_info()
 
1969
            if _hook_master:
 
1970
                result.master_branch = _hook_master
 
1971
                result.local_branch = result.target_branch
 
1972
            else:
 
1973
                result.master_branch = result.target_branch
 
1974
                result.local_branch = None
 
1975
            if run_hooks:
 
1976
                for hook in Branch.hooks['post_pull']:
 
1977
                    hook(result)
 
1978
        finally:
 
1979
            source.unlock()
 
1980
        return result
 
1981
 
 
1982
    def _get_parent_location(self):
 
1983
        _locs = ['parent', 'pull', 'x-pull']
 
1984
        for l in _locs:
 
1985
            try:
 
1986
                return self._transport.get_bytes(l).strip('\n')
 
1987
            except errors.NoSuchFile:
 
1988
                pass
 
1989
        return None
 
1990
 
 
1991
    @needs_read_lock
 
1992
    def push(self, target, overwrite=False, stop_revision=None,
 
1993
             _override_hook_source_branch=None):
 
1994
        """See Branch.push.
 
1995
 
 
1996
        This is the basic concrete implementation of push()
 
1997
 
 
1998
        :param _override_hook_source_branch: If specified, run
 
1999
        the hooks passing this Branch as the source, rather than self.
 
2000
        This is for use of RemoteBranch, where push is delegated to the
 
2001
        underlying vfs-based Branch.
 
2002
        """
 
2003
        # TODO: Public option to disable running hooks - should be trivial but
 
2004
        # needs tests.
 
2005
        return _run_with_write_locked_target(
 
2006
            target, self._push_with_bound_branches, target, overwrite,
 
2007
            stop_revision,
 
2008
            _override_hook_source_branch=_override_hook_source_branch)
 
2009
 
 
2010
    def _push_with_bound_branches(self, target, overwrite,
 
2011
            stop_revision,
 
2012
            _override_hook_source_branch=None):
 
2013
        """Push from self into target, and into target's master if any.
 
2014
 
 
2015
        This is on the base BzrBranch class even though it doesn't support
 
2016
        bound branches because the *target* might be bound.
 
2017
        """
 
2018
        def _run_hooks():
 
2019
            if _override_hook_source_branch:
 
2020
                result.source_branch = _override_hook_source_branch
 
2021
            for hook in Branch.hooks['post_push']:
 
2022
                hook(result)
 
2023
 
 
2024
        bound_location = target.get_bound_location()
 
2025
        if bound_location and target.base != bound_location:
 
2026
            # there is a master branch.
 
2027
            #
 
2028
            # XXX: Why the second check?  Is it even supported for a branch to
 
2029
            # be bound to itself? -- mbp 20070507
 
2030
            master_branch = target.get_master_branch()
 
2031
            master_branch.lock_write()
 
2032
            try:
 
2033
                # push into the master from this branch.
 
2034
                self._basic_push(master_branch, overwrite, stop_revision)
 
2035
                # and push into the target branch from this. Note that we push from
 
2036
                # this branch again, because its considered the highest bandwidth
 
2037
                # repository.
 
2038
                result = self._basic_push(target, overwrite, stop_revision)
 
2039
                result.master_branch = master_branch
 
2040
                result.local_branch = target
 
2041
                _run_hooks()
 
2042
                return result
 
2043
            finally:
 
2044
                master_branch.unlock()
 
2045
        else:
 
2046
            # no master branch
 
2047
            result = self._basic_push(target, overwrite, stop_revision)
 
2048
            # TODO: Why set master_branch and local_branch if there's no
 
2049
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
2050
            # 20070504
 
2051
            result.master_branch = target
 
2052
            result.local_branch = None
 
2053
            _run_hooks()
 
2054
            return result
 
2055
 
 
2056
    def _basic_push(self, target, overwrite, stop_revision):
 
2057
        """Basic implementation of push without bound branches or hooks.
 
2058
 
 
2059
        Must be called with self read locked and target write locked.
 
2060
        """
 
2061
        result = PushResult()
 
2062
        result.source_branch = self
 
2063
        result.target_branch = target
 
2064
        result.old_revno, result.old_revid = target.last_revision_info()
 
2065
        if result.old_revid != self.last_revision():
 
2066
            # We assume that during 'push' this repository is closer than
 
2067
            # the target.
 
2068
            graph = self.repository.get_graph(target.repository)
 
2069
            target.update_revisions(self, stop_revision, overwrite=overwrite,
 
2070
                                    graph=graph)
 
2071
        if self._push_should_merge_tags():
 
2072
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
 
2073
        result.new_revno, result.new_revid = target.last_revision_info()
 
2074
        return result
 
2075
 
 
2076
    def _push_should_merge_tags(self):
 
2077
        """Should _basic_push merge this branch's tags into the target?
 
2078
 
 
2079
        The default implementation returns False if this branch has no tags,
 
2080
        and True the rest of the time.  Subclasses may override this.
 
2081
        """
 
2082
        return self.tags.supports_tags() and self.tags.get_tag_dict()
 
2083
 
 
2084
    def get_parent(self):
 
2085
        """See Branch.get_parent."""
 
2086
        parent = self._get_parent_location()
 
2087
        if parent is None:
 
2088
            return parent
 
2089
        # This is an old-format absolute path to a local branch
 
2090
        # turn it into a url
 
2091
        if parent.startswith('/'):
 
2092
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
 
2093
        try:
 
2094
            return urlutils.join(self.base[:-1], parent)
 
2095
        except errors.InvalidURLJoin, e:
 
2096
            raise errors.InaccessibleParent(parent, self.base)
 
2097
 
 
2098
    def get_stacked_on_url(self):
 
2099
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2100
 
 
2101
    def set_push_location(self, location):
 
2102
        """See Branch.set_push_location."""
 
2103
        self.get_config().set_user_option(
 
2104
            'push_location', location,
 
2105
            store=_mod_config.STORE_LOCATION_NORECURSE)
 
2106
 
 
2107
    @needs_write_lock
 
2108
    def set_parent(self, url):
 
2109
        """See Branch.set_parent."""
 
2110
        # TODO: Maybe delete old location files?
 
2111
        # URLs should never be unicode, even on the local fs,
 
2112
        # FIXUP this and get_parent in a future branch format bump:
 
2113
        # read and rewrite the file. RBC 20060125
 
2114
        if url is not None:
 
2115
            if isinstance(url, unicode):
 
2116
                try:
 
2117
                    url = url.encode('ascii')
 
2118
                except UnicodeEncodeError:
 
2119
                    raise errors.InvalidURL(url,
 
2120
                        "Urls must be 7-bit ascii, "
 
2121
                        "use bzrlib.urlutils.escape")
 
2122
            url = urlutils.relative_url(self.base, url)
 
2123
        self._set_parent_location(url)
 
2124
 
 
2125
    def _set_parent_location(self, url):
 
2126
        if url is None:
 
2127
            self._transport.delete('parent')
 
2128
        else:
 
2129
            self._transport.put_bytes('parent', url + '\n',
 
2130
                mode=self.bzrdir._get_file_mode())
 
2131
 
 
2132
    def set_stacked_on_url(self, url):
 
2133
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2134
 
 
2135
 
 
2136
class BzrBranch5(BzrBranch):
 
2137
    """A format 5 branch. This supports new features over plain branches.
 
2138
 
 
2139
    It has support for a master_branch which is the data for bound branches.
 
2140
    """
 
2141
 
 
2142
    @needs_write_lock
 
2143
    def pull(self, source, overwrite=False, stop_revision=None,
 
2144
             run_hooks=True, possible_transports=None,
 
2145
             _override_hook_target=None):
 
2146
        """Pull from source into self, updating my master if any.
 
2147
 
 
2148
        :param run_hooks: Private parameter - if false, this branch
 
2149
            is being called because it's the master of the primary branch,
 
2150
            so it should not run its hooks.
 
2151
        """
 
2152
        bound_location = self.get_bound_location()
 
2153
        master_branch = None
 
2154
        if bound_location and source.base != bound_location:
 
2155
            # not pulling from master, so we need to update master.
 
2156
            master_branch = self.get_master_branch(possible_transports)
 
2157
            master_branch.lock_write()
 
2158
        try:
 
2159
            if master_branch:
 
2160
                # pull from source into master.
 
2161
                master_branch.pull(source, overwrite, stop_revision,
 
2162
                    run_hooks=False)
 
2163
            return super(BzrBranch5, self).pull(source, overwrite,
 
2164
                stop_revision, _hook_master=master_branch,
 
2165
                run_hooks=run_hooks,
 
2166
                _override_hook_target=_override_hook_target)
 
2167
        finally:
 
2168
            if master_branch:
 
2169
                master_branch.unlock()
 
2170
 
 
2171
    def get_bound_location(self):
 
2172
        try:
 
2173
            return self._transport.get_bytes('bound')[:-1]
 
2174
        except errors.NoSuchFile:
 
2175
            return None
 
2176
 
 
2177
    @needs_read_lock
 
2178
    def get_master_branch(self, possible_transports=None):
 
2179
        """Return the branch we are bound to.
 
2180
 
 
2181
        :return: Either a Branch, or None
 
2182
 
 
2183
        This could memoise the branch, but if thats done
 
2184
        it must be revalidated on each new lock.
 
2185
        So for now we just don't memoise it.
 
2186
        # RBC 20060304 review this decision.
 
2187
        """
 
2188
        bound_loc = self.get_bound_location()
 
2189
        if not bound_loc:
 
2190
            return None
 
2191
        try:
 
2192
            return Branch.open(bound_loc,
 
2193
                               possible_transports=possible_transports)
 
2194
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2195
            raise errors.BoundBranchConnectionFailure(
 
2196
                    self, bound_loc, e)
 
2197
 
 
2198
    @needs_write_lock
 
2199
    def set_bound_location(self, location):
 
2200
        """Set the target where this branch is bound to.
 
2201
 
 
2202
        :param location: URL to the target branch
 
2203
        """
 
2204
        if location:
 
2205
            self._transport.put_bytes('bound', location+'\n',
 
2206
                mode=self.bzrdir._get_file_mode())
 
2207
        else:
 
2208
            try:
 
2209
                self._transport.delete('bound')
 
2210
            except errors.NoSuchFile:
 
2211
                return False
 
2212
            return True
 
2213
 
 
2214
    @needs_write_lock
 
2215
    def bind(self, other):
 
2216
        """Bind this branch to the branch other.
 
2217
 
 
2218
        This does not push or pull data between the branches, though it does
 
2219
        check for divergence to raise an error when the branches are not
 
2220
        either the same, or one a prefix of the other. That behaviour may not
 
2221
        be useful, so that check may be removed in future.
 
2222
 
 
2223
        :param other: The branch to bind to
 
2224
        :type other: Branch
 
2225
        """
 
2226
        # TODO: jam 20051230 Consider checking if the target is bound
 
2227
        #       It is debatable whether you should be able to bind to
 
2228
        #       a branch which is itself bound.
 
2229
        #       Committing is obviously forbidden,
 
2230
        #       but binding itself may not be.
 
2231
        #       Since we *have* to check at commit time, we don't
 
2232
        #       *need* to check here
 
2233
 
 
2234
        # we want to raise diverged if:
 
2235
        # last_rev is not in the other_last_rev history, AND
 
2236
        # other_last_rev is not in our history, and do it without pulling
 
2237
        # history around
 
2238
        self.set_bound_location(other.base)
 
2239
 
 
2240
    @needs_write_lock
 
2241
    def unbind(self):
 
2242
        """If bound, unbind"""
 
2243
        return self.set_bound_location(None)
 
2244
 
 
2245
    @needs_write_lock
 
2246
    def update(self, possible_transports=None):
 
2247
        """Synchronise this branch with the master branch if any.
 
2248
 
 
2249
        :return: None or the last_revision that was pivoted out during the
 
2250
                 update.
 
2251
        """
 
2252
        master = self.get_master_branch(possible_transports)
 
2253
        if master is not None:
 
2254
            old_tip = _mod_revision.ensure_null(self.last_revision())
 
2255
            self.pull(master, overwrite=True)
 
2256
            if self.repository.get_graph().is_ancestor(old_tip,
 
2257
                _mod_revision.ensure_null(self.last_revision())):
 
2258
                return None
 
2259
            return old_tip
 
2260
        return None
 
2261
 
 
2262
 
 
2263
class BzrBranch7(BzrBranch5):
 
2264
    """A branch with support for a fallback repository."""
 
2265
 
 
2266
    def _get_fallback_repository(self, url):
 
2267
        """Get the repository we fallback to at url."""
 
2268
        url = urlutils.join(self.base, url)
 
2269
        a_bzrdir = bzrdir.BzrDir.open(url,
 
2270
                                      possible_transports=[self._transport])
 
2271
        return a_bzrdir.open_branch().repository
 
2272
 
 
2273
    def _activate_fallback_location(self, url):
 
2274
        """Activate the branch/repository from url as a fallback repository."""
 
2275
        self.repository.add_fallback_repository(
 
2276
            self._get_fallback_repository(url))
 
2277
 
 
2278
    def _open_hook(self):
 
2279
        try:
 
2280
            url = self.get_stacked_on_url()
 
2281
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
 
2282
            errors.UnstackableBranchFormat):
 
2283
            pass
 
2284
        else:
 
2285
            for hook in Branch.hooks['transform_fallback_location']:
 
2286
                url = hook(self, url)
 
2287
                if url is None:
 
2288
                    hook_name = Branch.hooks.get_hook_name(hook)
 
2289
                    raise AssertionError(
 
2290
                        "'transform_fallback_location' hook %s returned "
 
2291
                        "None, not a URL." % hook_name)
 
2292
            self._activate_fallback_location(url)
 
2293
 
 
2294
    def _check_stackable_repo(self):
 
2295
        if not self.repository._format.supports_external_lookups:
 
2296
            raise errors.UnstackableRepositoryFormat(self.repository._format,
 
2297
                self.repository.base)
 
2298
 
 
2299
    def __init__(self, *args, **kwargs):
 
2300
        super(BzrBranch7, self).__init__(*args, **kwargs)
 
2301
        self._last_revision_info_cache = None
 
2302
        self._partial_revision_history_cache = []
 
2303
 
 
2304
    def _clear_cached_state(self):
 
2305
        super(BzrBranch7, self)._clear_cached_state()
 
2306
        self._last_revision_info_cache = None
 
2307
        self._partial_revision_history_cache = []
 
2308
 
 
2309
    def _last_revision_info(self):
 
2310
        revision_string = self._transport.get_bytes('last-revision')
 
2311
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2312
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2313
        revno = int(revno)
 
2314
        return revno, revision_id
 
2315
 
 
2316
    def _write_last_revision_info(self, revno, revision_id):
 
2317
        """Simply write out the revision id, with no checks.
 
2318
 
 
2319
        Use set_last_revision_info to perform this safely.
 
2320
 
 
2321
        Does not update the revision_history cache.
 
2322
        Intended to be called by set_last_revision_info and
 
2323
        _write_revision_history.
 
2324
        """
 
2325
        revision_id = _mod_revision.ensure_null(revision_id)
 
2326
        out_string = '%d %s\n' % (revno, revision_id)
 
2327
        self._transport.put_bytes('last-revision', out_string,
 
2328
            mode=self.bzrdir._get_file_mode())
 
2329
 
 
2330
    @needs_write_lock
 
2331
    def set_last_revision_info(self, revno, revision_id):
 
2332
        revision_id = _mod_revision.ensure_null(revision_id)
 
2333
        old_revno, old_revid = self.last_revision_info()
 
2334
        if self._get_append_revisions_only():
 
2335
            self._check_history_violation(revision_id)
 
2336
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2337
        self._write_last_revision_info(revno, revision_id)
 
2338
        self._clear_cached_state()
 
2339
        self._last_revision_info_cache = revno, revision_id
 
2340
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2341
 
 
2342
    def _synchronize_history(self, destination, revision_id):
 
2343
        """Synchronize last revision and revision history between branches.
 
2344
 
 
2345
        :see: Branch._synchronize_history
 
2346
        """
 
2347
        # XXX: The base Branch has a fast implementation of this method based
 
2348
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
 
2349
        # that uses set_revision_history.  This class inherits from BzrBranch5,
 
2350
        # but wants the fast implementation, so it calls
 
2351
        # Branch._synchronize_history directly.
 
2352
        Branch._synchronize_history(self, destination, revision_id)
 
2353
 
 
2354
    def _check_history_violation(self, revision_id):
 
2355
        last_revision = _mod_revision.ensure_null(self.last_revision())
 
2356
        if _mod_revision.is_null(last_revision):
 
2357
            return
 
2358
        if last_revision not in self._lefthand_history(revision_id):
 
2359
            raise errors.AppendRevisionsOnlyViolation(self.base)
 
2360
 
 
2361
    def _gen_revision_history(self):
 
2362
        """Generate the revision history from last revision
 
2363
        """
 
2364
        last_revno, last_revision = self.last_revision_info()
 
2365
        self._extend_partial_history(stop_index=last_revno-1)
 
2366
        return list(reversed(self._partial_revision_history_cache))
 
2367
 
 
2368
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
 
2369
        """Extend the partial history to include a given index
 
2370
 
 
2371
        If a stop_index is supplied, stop when that index has been reached.
 
2372
        If a stop_revision is supplied, stop when that revision is
 
2373
        encountered.  Otherwise, stop when the beginning of history is
 
2374
        reached.
 
2375
 
 
2376
        :param stop_index: The index which should be present.  When it is
 
2377
            present, history extension will stop.
 
2378
        :param revision_id: The revision id which should be present.  When
 
2379
            it is encountered, history extension will stop.
 
2380
        """
 
2381
        repo = self.repository
 
2382
        if len(self._partial_revision_history_cache) == 0:
 
2383
            iterator = repo.iter_reverse_revision_history(self.last_revision())
 
2384
        else:
 
2385
            start_revision = self._partial_revision_history_cache[-1]
 
2386
            iterator = repo.iter_reverse_revision_history(start_revision)
 
2387
            #skip the last revision in the list
 
2388
            next_revision = iterator.next()
 
2389
        for revision_id in iterator:
 
2390
            self._partial_revision_history_cache.append(revision_id)
 
2391
            if (stop_index is not None and
 
2392
                len(self._partial_revision_history_cache) > stop_index):
 
2393
                break
 
2394
            if revision_id == stop_revision:
 
2395
                break
 
2396
 
 
2397
    def _write_revision_history(self, history):
 
2398
        """Factored out of set_revision_history.
 
2399
 
 
2400
        This performs the actual writing to disk, with format-specific checks.
 
2401
        It is intended to be called by BzrBranch5.set_revision_history.
 
2402
        """
 
2403
        if len(history) == 0:
 
2404
            last_revision = 'null:'
 
2405
        else:
 
2406
            if history != self._lefthand_history(history[-1]):
 
2407
                raise errors.NotLefthandHistory(history)
 
2408
            last_revision = history[-1]
 
2409
        if self._get_append_revisions_only():
 
2410
            self._check_history_violation(last_revision)
 
2411
        self._write_last_revision_info(len(history), last_revision)
 
2412
 
 
2413
    @needs_write_lock
 
2414
    def _set_parent_location(self, url):
 
2415
        """Set the parent branch"""
 
2416
        self._set_config_location('parent_location', url, make_relative=True)
 
2417
 
 
2418
    @needs_read_lock
 
2419
    def _get_parent_location(self):
 
2420
        """Set the parent branch"""
 
2421
        return self._get_config_location('parent_location')
 
2422
 
 
2423
    def set_push_location(self, location):
 
2424
        """See Branch.set_push_location."""
 
2425
        self._set_config_location('push_location', location)
 
2426
 
 
2427
    def set_bound_location(self, location):
 
2428
        """See Branch.set_push_location."""
 
2429
        result = None
 
2430
        config = self.get_config()
 
2431
        if location is None:
 
2432
            if config.get_user_option('bound') != 'True':
 
2433
                return False
 
2434
            else:
 
2435
                config.set_user_option('bound', 'False', warn_masked=True)
 
2436
                return True
 
2437
        else:
 
2438
            self._set_config_location('bound_location', location,
 
2439
                                      config=config)
 
2440
            config.set_user_option('bound', 'True', warn_masked=True)
 
2441
        return True
 
2442
 
 
2443
    def _get_bound_location(self, bound):
 
2444
        """Return the bound location in the config file.
 
2445
 
 
2446
        Return None if the bound parameter does not match"""
 
2447
        config = self.get_config()
 
2448
        config_bound = (config.get_user_option('bound') == 'True')
 
2449
        if config_bound != bound:
 
2450
            return None
 
2451
        return self._get_config_location('bound_location', config=config)
 
2452
 
 
2453
    def get_bound_location(self):
 
2454
        """See Branch.set_push_location."""
 
2455
        return self._get_bound_location(True)
 
2456
 
 
2457
    def get_old_bound_location(self):
 
2458
        """See Branch.get_old_bound_location"""
 
2459
        return self._get_bound_location(False)
 
2460
 
 
2461
    def get_stacked_on_url(self):
 
2462
        # you can always ask for the URL; but you might not be able to use it
 
2463
        # if the repo can't support stacking.
 
2464
        ## self._check_stackable_repo()
 
2465
        stacked_url = self._get_config_location('stacked_on_location')
 
2466
        if stacked_url is None:
 
2467
            raise errors.NotStacked(self)
 
2468
        return stacked_url
 
2469
 
 
2470
    def set_append_revisions_only(self, enabled):
 
2471
        if enabled:
 
2472
            value = 'True'
 
2473
        else:
 
2474
            value = 'False'
 
2475
        self.get_config().set_user_option('append_revisions_only', value,
 
2476
            warn_masked=True)
 
2477
 
 
2478
    def set_stacked_on_url(self, url):
 
2479
        self._check_stackable_repo()
 
2480
        if not url:
 
2481
            try:
 
2482
                old_url = self.get_stacked_on_url()
 
2483
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
2484
                errors.UnstackableRepositoryFormat):
 
2485
                return
 
2486
            url = ''
 
2487
            # repositories don't offer an interface to remove fallback
 
2488
            # repositories today; take the conceptually simpler option and just
 
2489
            # reopen it.
 
2490
            self.repository = self.bzrdir.find_repository()
 
2491
            # for every revision reference the branch has, ensure it is pulled
 
2492
            # in.
 
2493
            source_repository = self._get_fallback_repository(old_url)
 
2494
            for revision_id in chain([self.last_revision()],
 
2495
                self.tags.get_reverse_tag_dict()):
 
2496
                self.repository.fetch(source_repository, revision_id,
 
2497
                    find_ghosts=True)
 
2498
        else:
 
2499
            self._activate_fallback_location(url)
 
2500
        # write this out after the repository is stacked to avoid setting a
 
2501
        # stacked config that doesn't work.
 
2502
        self._set_config_location('stacked_on_location', url)
 
2503
 
 
2504
    def _get_append_revisions_only(self):
 
2505
        value = self.get_config().get_user_option('append_revisions_only')
 
2506
        return value == 'True'
 
2507
 
 
2508
    def _make_tags(self):
 
2509
        return BasicTags(self)
 
2510
 
 
2511
    @needs_write_lock
 
2512
    def generate_revision_history(self, revision_id, last_rev=None,
 
2513
                                  other_branch=None):
 
2514
        """See BzrBranch5.generate_revision_history"""
 
2515
        history = self._lefthand_history(revision_id, last_rev, other_branch)
 
2516
        revno = len(history)
 
2517
        self.set_last_revision_info(revno, revision_id)
 
2518
 
 
2519
    @needs_read_lock
 
2520
    def get_rev_id(self, revno, history=None):
 
2521
        """Find the revision id of the specified revno."""
 
2522
        if revno == 0:
 
2523
            return _mod_revision.NULL_REVISION
 
2524
 
 
2525
        last_revno, last_revision_id = self.last_revision_info()
 
2526
        if revno <= 0 or revno > last_revno:
 
2527
            raise errors.NoSuchRevision(self, revno)
 
2528
 
 
2529
        if history is not None:
 
2530
            return history[revno - 1]
 
2531
 
 
2532
        index = last_revno - revno
 
2533
        if len(self._partial_revision_history_cache) <= index:
 
2534
            self._extend_partial_history(stop_index=index)
 
2535
        if len(self._partial_revision_history_cache) > index:
 
2536
            return self._partial_revision_history_cache[index]
 
2537
        else:
 
2538
            raise errors.NoSuchRevision(self, revno)
 
2539
 
 
2540
    @needs_read_lock
 
2541
    def revision_id_to_revno(self, revision_id):
 
2542
        """Given a revision id, return its revno"""
 
2543
        if _mod_revision.is_null(revision_id):
 
2544
            return 0
 
2545
        try:
 
2546
            index = self._partial_revision_history_cache.index(revision_id)
 
2547
        except ValueError:
 
2548
            self._extend_partial_history(stop_revision=revision_id)
 
2549
            index = len(self._partial_revision_history_cache) - 1
 
2550
            if self._partial_revision_history_cache[index] != revision_id:
 
2551
                raise errors.NoSuchRevision(self, revision_id)
 
2552
        return self.revno() - index
 
2553
 
 
2554
 
 
2555
class BzrBranch6(BzrBranch7):
 
2556
    """See BzrBranchFormat6 for the capabilities of this branch.
 
2557
 
 
2558
    This subclass of BzrBranch7 disables the new features BzrBranch7 added,
 
2559
    i.e. stacking.
 
2560
    """
 
2561
 
 
2562
    def get_stacked_on_url(self):
 
2563
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2564
 
 
2565
    def set_stacked_on_url(self, url):
 
2566
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2567
 
 
2568
 
 
2569
######################################################################
 
2570
# results of operations
 
2571
 
 
2572
 
 
2573
class _Result(object):
 
2574
 
 
2575
    def _show_tag_conficts(self, to_file):
 
2576
        if not getattr(self, 'tag_conflicts', None):
 
2577
            return
 
2578
        to_file.write('Conflicting tags:\n')
 
2579
        for name, value1, value2 in self.tag_conflicts:
 
2580
            to_file.write('    %s\n' % (name, ))
 
2581
 
 
2582
 
 
2583
class PullResult(_Result):
 
2584
    """Result of a Branch.pull operation.
 
2585
 
 
2586
    :ivar old_revno: Revision number before pull.
 
2587
    :ivar new_revno: Revision number after pull.
 
2588
    :ivar old_revid: Tip revision id before pull.
 
2589
    :ivar new_revid: Tip revision id after pull.
 
2590
    :ivar source_branch: Source (local) branch object.
 
2591
    :ivar master_branch: Master branch of the target, or the target if no
 
2592
        Master
 
2593
    :ivar local_branch: target branch if there is a Master, else None
 
2594
    :ivar target_branch: Target/destination branch object.
 
2595
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
 
2596
    """
 
2597
 
 
2598
    def __int__(self):
 
2599
        # DEPRECATED: pull used to return the change in revno
 
2600
        return self.new_revno - self.old_revno
 
2601
 
 
2602
    def report(self, to_file):
 
2603
        if not is_quiet():
 
2604
            if self.old_revid == self.new_revid:
 
2605
                to_file.write('No revisions to pull.\n')
 
2606
            else:
 
2607
                to_file.write('Now on revision %d.\n' % self.new_revno)
 
2608
        self._show_tag_conficts(to_file)
 
2609
 
 
2610
 
 
2611
class PushResult(_Result):
 
2612
    """Result of a Branch.push operation.
 
2613
 
 
2614
    :ivar old_revno: Revision number before push.
 
2615
    :ivar new_revno: Revision number after push.
 
2616
    :ivar old_revid: Tip revision id before push.
 
2617
    :ivar new_revid: Tip revision id after push.
 
2618
    :ivar source_branch: Source branch object.
 
2619
    :ivar master_branch: Master branch of the target, or None.
 
2620
    :ivar target_branch: Target/destination branch object.
 
2621
    """
 
2622
 
 
2623
    def __int__(self):
 
2624
        # DEPRECATED: push used to return the change in revno
 
2625
        return self.new_revno - self.old_revno
 
2626
 
 
2627
    def report(self, to_file):
 
2628
        """Write a human-readable description of the result."""
 
2629
        if self.old_revid == self.new_revid:
 
2630
            to_file.write('No new revisions to push.\n')
 
2631
        else:
 
2632
            to_file.write('Pushed up to revision %d.\n' % self.new_revno)
 
2633
        self._show_tag_conficts(to_file)
 
2634
 
 
2635
 
 
2636
class BranchCheckResult(object):
 
2637
    """Results of checking branch consistency.
 
2638
 
 
2639
    :see: Branch.check
 
2640
    """
 
2641
 
 
2642
    def __init__(self, branch):
 
2643
        self.branch = branch
 
2644
 
 
2645
    def report_results(self, verbose):
 
2646
        """Report the check results via trace.note.
 
2647
 
 
2648
        :param verbose: Requests more detailed display of what was checked,
 
2649
            if any.
 
2650
        """
 
2651
        note('checked branch %s format %s',
 
2652
             self.branch.base,
 
2653
             self.branch._format)
 
2654
 
 
2655
 
 
2656
class Converter5to6(object):
 
2657
    """Perform an in-place upgrade of format 5 to format 6"""
 
2658
 
 
2659
    def convert(self, branch):
 
2660
        # Data for 5 and 6 can peacefully coexist.
 
2661
        format = BzrBranchFormat6()
 
2662
        new_branch = format.open(branch.bzrdir, _found=True)
 
2663
 
 
2664
        # Copy source data into target
 
2665
        new_branch._write_last_revision_info(*branch.last_revision_info())
 
2666
        new_branch.set_parent(branch.get_parent())
 
2667
        new_branch.set_bound_location(branch.get_bound_location())
 
2668
        new_branch.set_push_location(branch.get_push_location())
 
2669
 
 
2670
        # New branch has no tags by default
 
2671
        new_branch.tags._set_tag_dict({})
 
2672
 
 
2673
        # Copying done; now update target format
 
2674
        new_branch._transport.put_bytes('format',
 
2675
            format.get_format_string(),
 
2676
            mode=new_branch.bzrdir._get_file_mode())
 
2677
 
 
2678
        # Clean up old files
 
2679
        new_branch._transport.delete('revision-history')
 
2680
        try:
 
2681
            branch.set_parent(None)
 
2682
        except errors.NoSuchFile:
 
2683
            pass
 
2684
        branch.set_bound_location(None)
 
2685
 
 
2686
 
 
2687
class Converter6to7(object):
 
2688
    """Perform an in-place upgrade of format 6 to format 7"""
 
2689
 
 
2690
    def convert(self, branch):
 
2691
        format = BzrBranchFormat7()
 
2692
        branch._set_config_location('stacked_on_location', '')
 
2693
        # update target format
 
2694
        branch._transport.put_bytes('format', format.get_format_string())
 
2695
 
 
2696
 
 
2697
 
 
2698
def _run_with_write_locked_target(target, callable, *args, **kwargs):
 
2699
    """Run ``callable(*args, **kwargs)``, write-locking target for the
 
2700
    duration.
 
2701
 
 
2702
    _run_with_write_locked_target will attempt to release the lock it acquires.
 
2703
 
 
2704
    If an exception is raised by callable, then that exception *will* be
 
2705
    propagated, even if the unlock attempt raises its own error.  Thus
 
2706
    _run_with_write_locked_target should be preferred to simply doing::
 
2707
 
 
2708
        target.lock_write()
 
2709
        try:
 
2710
            return callable(*args, **kwargs)
 
2711
        finally:
 
2712
            target.unlock()
 
2713
 
 
2714
    """
 
2715
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
 
2716
    # should share code?
 
2717
    target.lock_write()
 
2718
    try:
 
2719
        result = callable(*args, **kwargs)
 
2720
    except:
 
2721
        exc_info = sys.exc_info()
 
2722
        try:
 
2723
            target.unlock()
 
2724
        finally:
 
2725
            raise exc_info[0], exc_info[1], exc_info[2]
 
2726
    else:
 
2727
        target.unlock()
 
2728
        return result