/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: John Arbash Meinel
  • Date: 2009-08-16 17:22:08 UTC
  • mto: This revision was merged to the branch mainline in revision 4629.
  • Revision ID: john@arbash-meinel.com-20090816172208-2mh7z0uapy6y0gsv
Expose KnownGraph off of VersionedFiles
handle ghosts (needs tests, doesn't seem to effect performance)
list(tuple[1:]) is a couple ms slower than using my own loop.
Net effect is:
  time bzr log -n0 -r -10..-1
  real    0m2.559s

  time wbzr log -n0 -r -10..-1
  real    0m1.170s

  time bzr log -n1 -r -10..-1
  real    0m0.453s

So the overhead for the extra graph is down from 2.1s to 0.7s

Show diffs side-by-side

added added

removed removed

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