/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: Canonical.com Patch Queue Manager
  • Date: 2011-04-18 23:19:16 UTC
  • mfrom: (5784.3.1 cleanup)
  • Revision ID: pqm@pqm.ubuntu.com-20110418231916-8x8pvhwr2q8l6gq1
(mbp) remove unnecessary TestShowDiffTreesHelper from tests (Martin Pool)

Show diffs side-by-side

added added

removed removed

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