~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-09-11 06:10:59 UTC
  • mfrom: (3702.1.1 trivial)
  • Revision ID: pqm@pqm.ubuntu.com-20080911061059-svzqfejar17ui4zw
(mbp) KnitVersionedFiles repr

Show diffs side-by-side

added added

removed removed

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