/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to brzlib/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2017-05-21 12:41:27 UTC
  • mto: This revision was merged to the branch mainline in revision 6623.
  • Revision ID: jelmer@jelmer.uk-20170521124127-iv8etg0vwymyai6y
s/bzr/brz/ in apport config.

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
from .lazy_import import lazy_import
 
17
from __future__ import absolute_import
 
18
 
 
19
import brzlib.bzrdir
 
20
 
 
21
from cStringIO import StringIO
 
22
 
 
23
from brzlib.lazy_import import lazy_import
18
24
lazy_import(globals(), """
19
 
import contextlib
20
25
import itertools
21
 
from breezy import (
 
26
from brzlib import (
 
27
    bzrdir,
 
28
    controldir,
 
29
    cache_utf8,
 
30
    cleanup,
22
31
    config as _mod_config,
23
32
    debug,
24
 
    memorytree,
 
33
    errors,
 
34
    fetch,
 
35
    graph as _mod_graph,
 
36
    lockdir,
 
37
    lockable_files,
 
38
    remote,
25
39
    repository,
26
40
    revision as _mod_revision,
 
41
    rio,
 
42
    shelf,
27
43
    tag as _mod_tag,
28
44
    transport,
29
45
    ui,
30
46
    urlutils,
31
 
    )
32
 
from breezy.bzr import (
33
 
    fetch,
34
 
    remote,
35
47
    vf_search,
36
48
    )
37
 
from breezy.i18n import gettext, ngettext
 
49
from brzlib.i18n import gettext, ngettext
38
50
""")
39
51
 
40
 
from . import (
 
52
# Explicitly import brzlib.bzrdir so that the BzrProber
 
53
# is guaranteed to be registered.
 
54
import brzlib.bzrdir
 
55
 
 
56
from brzlib import (
 
57
    bzrdir,
41
58
    controldir,
42
 
    errors,
43
 
    registry,
44
 
    )
45
 
from .hooks import Hooks
46
 
from .inter import InterObject
47
 
from .lock import LogicalLockResult
48
 
from .trace import mutter, mutter_callsite, note, is_quiet, warning
49
 
 
50
 
 
51
 
class UnstackableBranchFormat(errors.BzrError):
52
 
 
53
 
    _fmt = ("The branch '%(url)s'(%(format)s) is not a stackable format. "
54
 
            "You will need to upgrade the branch to permit branch stacking.")
55
 
 
56
 
    def __init__(self, format, url):
57
 
        errors.BzrError.__init__(self)
58
 
        self.format = format
59
 
        self.url = url
 
59
    )
 
60
from brzlib.decorators import (
 
61
    needs_read_lock,
 
62
    needs_write_lock,
 
63
    only_raises,
 
64
    )
 
65
from brzlib.hooks import Hooks
 
66
from brzlib.inter import InterObject
 
67
from brzlib.lock import _RelockDebugMixin, LogicalLockResult
 
68
from brzlib import registry
 
69
from brzlib.symbol_versioning import (
 
70
    deprecated_in,
 
71
    deprecated_method,
 
72
    )
 
73
from brzlib.trace import mutter, mutter_callsite, note, is_quiet
60
74
 
61
75
 
62
76
class Branch(controldir.ControlComponent):
79
93
 
80
94
    @property
81
95
    def user_transport(self):
82
 
        return self.controldir.user_transport
 
96
        return self.bzrdir.user_transport
83
97
 
84
98
    def __init__(self, possible_transports=None):
85
99
        self.tags = self._format.make_tags(self)
87
101
        self._revision_id_to_revno_cache = None
88
102
        self._partial_revision_id_to_revno_cache = {}
89
103
        self._partial_revision_history_cache = []
 
104
        self._tags_bytes = None
90
105
        self._last_revision_info_cache = None
91
106
        self._master_branch_cache = None
92
107
        self._merge_sorted_revisions_cache = None
103
118
        for existing_fallback_repo in self.repository._fallback_repositories:
104
119
            if existing_fallback_repo.user_url == url:
105
120
                # This fallback is already configured.  This probably only
106
 
                # happens because ControlDir.sprout is a horrible mess.  To
107
 
                # avoid confusing _unstack we don't add this a second time.
 
121
                # happens because ControlDir.sprout is a horrible mess.  To avoid
 
122
                # confusing _unstack we don't add this a second time.
108
123
                mutter('duplicate activation of fallback %r on %r', url, self)
109
124
                return
110
125
        repo = self._get_fallback_repository(url, possible_transports)
128
143
 
129
144
    def _check_stackable_repo(self):
130
145
        if not self.repository._format.supports_external_lookups:
131
 
            raise errors.UnstackableRepositoryFormat(
132
 
                self.repository._format, self.repository.base)
 
146
            raise errors.UnstackableRepositoryFormat(self.repository._format,
 
147
                self.repository.base)
133
148
 
134
149
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
135
150
        """Extend the partial history to include a given index
149
164
        repository._iter_for_revno(
150
165
            self.repository, self._partial_revision_history_cache,
151
166
            stop_index=stop_index, stop_revision=stop_revision)
152
 
        if self._partial_revision_history_cache[-1] == \
153
 
                _mod_revision.NULL_REVISION:
 
167
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
154
168
            self._partial_revision_history_cache.pop()
155
169
 
156
170
    def _get_check_refs(self):
157
171
        """Get the references needed for check().
158
172
 
159
 
        See breezy.check.
 
173
        See brzlib.check.
160
174
        """
161
175
        revid = self.last_revision()
162
176
        return [('revision-existence', revid), ('lefthand-distance', revid)]
168
182
        For instance, if the branch is at URL/.bzr/branch,
169
183
        Branch.open(URL) -> a Branch instance.
170
184
        """
171
 
        control = controldir.ControlDir.open(
172
 
            base, possible_transports=possible_transports,
173
 
            _unsupported=_unsupported)
174
 
        return control.open_branch(
175
 
            unsupported=_unsupported,
 
185
        control = controldir.ControlDir.open(base,
 
186
            possible_transports=possible_transports, _unsupported=_unsupported)
 
187
        return control.open_branch(unsupported=_unsupported,
176
188
            possible_transports=possible_transports)
177
189
 
178
190
    @staticmethod
179
191
    def open_from_transport(transport, name=None, _unsupported=False,
180
 
                            possible_transports=None):
 
192
            possible_transports=None):
181
193
        """Open the branch rooted at transport"""
182
 
        control = controldir.ControlDir.open_from_transport(
183
 
            transport, _unsupported)
184
 
        return control.open_branch(
185
 
            name=name, unsupported=_unsupported,
 
194
        control = controldir.ControlDir.open_from_transport(transport, _unsupported)
 
195
        return control.open_branch(name=name, unsupported=_unsupported,
186
196
            possible_transports=possible_transports)
187
197
 
188
198
    @staticmethod
193
203
 
194
204
        Basically we keep looking up until we find the control directory or
195
205
        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
197
 
        unsupported format, UnknownFormatError or UnsupportedFormatError are
198
 
        raised.  If there is one, it is returned, along with the unused portion
199
 
        of url.
 
206
        If there is one and it is either an unrecognised format or an unsupported
 
207
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
208
        If there is one, it is returned, along with the unused portion of url.
200
209
        """
201
 
        control, relpath = controldir.ControlDir.open_containing(
202
 
            url, possible_transports)
 
210
        control, relpath = controldir.ControlDir.open_containing(url,
 
211
                                                         possible_transports)
203
212
        branch = control.open_branch(possible_transports=possible_transports)
204
213
        return (branch, relpath)
205
214
 
212
221
        return self.supports_tags() and self.tags.get_tag_dict()
213
222
 
214
223
    def get_config(self):
215
 
        """Get a breezy.config.BranchConfig for this Branch.
 
224
        """Get a brzlib.config.BranchConfig for this Branch.
216
225
 
217
226
        This can then be used to get and set configuration options for the
218
227
        branch.
219
228
 
220
 
        :return: A breezy.config.BranchConfig.
 
229
        :return: A brzlib.config.BranchConfig.
221
230
        """
222
231
        return _mod_config.BranchConfig(self)
223
232
 
224
233
    def get_config_stack(self):
225
 
        """Get a breezy.config.BranchStack for this Branch.
 
234
        """Get a brzlib.config.BranchStack for this Branch.
226
235
 
227
236
        This can then be used to get and set configuration options for the
228
237
        branch.
229
238
 
230
 
        :return: A breezy.config.BranchStack.
 
239
        :return: A brzlib.config.BranchStack.
231
240
        """
232
241
        return _mod_config.BranchStack(self)
233
242
 
 
243
    def _get_config(self):
 
244
        """Get the concrete config for just the config in this branch.
 
245
 
 
246
        This is not intended for client use; see Branch.get_config for the
 
247
        public API.
 
248
 
 
249
        Added in 1.14.
 
250
 
 
251
        :return: An object supporting get_option and set_option.
 
252
        """
 
253
        raise NotImplementedError(self._get_config)
 
254
 
234
255
    def store_uncommitted(self, creator):
235
256
        """Store uncommitted changes from a ShelfCreator.
236
257
 
254
275
        a_branch = Branch.open(url, possible_transports=possible_transports)
255
276
        return a_branch.repository
256
277
 
 
278
    @needs_read_lock
 
279
    def _get_tags_bytes(self):
 
280
        """Get the bytes of a serialised tags dict.
 
281
 
 
282
        Note that not all branches support tags, nor do all use the same tags
 
283
        logic: this method is specific to BasicTags. Other tag implementations
 
284
        may use the same method name and behave differently, safely, because
 
285
        of the double-dispatch via
 
286
        format.make_tags->tags_instance->get_tags_dict.
 
287
 
 
288
        :return: The bytes of the tags file.
 
289
        :seealso: Branch._set_tags_bytes.
 
290
        """
 
291
        if self._tags_bytes is None:
 
292
            self._tags_bytes = self._transport.get_bytes('tags')
 
293
        return self._tags_bytes
 
294
 
257
295
    def _get_nick(self, local=False, possible_transports=None):
258
296
        config = self.get_config()
259
297
        # explicit overrides master, but don't look for master if local is True
265
303
                if master is not None:
266
304
                    # return the master branch value
267
305
                    return master.nick
268
 
            except errors.RecursiveBind as e:
 
306
            except errors.RecursiveBind, e:
269
307
                raise e
270
 
            except errors.BzrError as e:
 
308
            except errors.BzrError, e:
271
309
                # Silently fall back to local implicit nick if the master is
272
310
                # unavailable
273
311
                mutter("Could not connect to bound branch, "
274
 
                       "falling back to local nick.\n " + str(e))
 
312
                    "falling back to local nick.\n " + str(e))
275
313
        return config.get_nickname()
276
314
 
277
315
    def _set_nick(self, nick):
300
338
        new_history = []
301
339
        check_not_reserved_id = _mod_revision.check_not_reserved_id
302
340
        # Do not include ghosts or graph origin in revision_history
303
 
        while (current_rev_id in parents_map
304
 
               and len(parents_map[current_rev_id]) > 0):
 
341
        while (current_rev_id in parents_map and
 
342
               len(parents_map[current_rev_id]) > 0):
305
343
            check_not_reserved_id(current_rev_id)
306
344
            new_history.append(current_rev_id)
307
345
            current_rev_id = parents_map[current_rev_id][0]
321
359
    def lock_read(self):
322
360
        """Lock the branch for read operations.
323
361
 
324
 
        :return: A breezy.lock.LogicalLockResult.
 
362
        :return: A brzlib.lock.LogicalLockResult.
325
363
        """
326
364
        raise NotImplementedError(self.lock_read)
327
365
 
335
373
    def get_physical_lock_status(self):
336
374
        raise NotImplementedError(self.get_physical_lock_status)
337
375
 
 
376
    @needs_read_lock
338
377
    def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
339
378
        """Return the revision_id for a dotted revno.
340
379
 
346
385
        :return: the revision_id
347
386
        :raises errors.NoSuchRevision: if the revno doesn't exist
348
387
        """
349
 
        with self.lock_read():
350
 
            rev_id = self._do_dotted_revno_to_revision_id(revno)
351
 
            if _cache_reverse:
352
 
                self._partial_revision_id_to_revno_cache[rev_id] = revno
353
 
            return rev_id
 
388
        rev_id = self._do_dotted_revno_to_revision_id(revno)
 
389
        if _cache_reverse:
 
390
            self._partial_revision_id_to_revno_cache[rev_id] = revno
 
391
        return rev_id
354
392
 
355
393
    def _do_dotted_revno_to_revision_id(self, revno):
356
394
        """Worker function for dotted_revno_to_revision_id.
359
397
        provide a more efficient implementation.
360
398
        """
361
399
        if len(revno) == 1:
362
 
            try:
363
 
                return self.get_rev_id(revno[0])
364
 
            except errors.RevisionNotPresent as e:
365
 
                raise errors.GhostRevisionsHaveNoRevno(revno[0], e.revision_id)
 
400
            return self.get_rev_id(revno[0])
366
401
        revision_id_to_revno = self.get_revision_id_to_revno_map()
367
402
        revision_ids = [revision_id for revision_id, this_revno
368
 
                        in revision_id_to_revno.items()
 
403
                        in revision_id_to_revno.iteritems()
369
404
                        if revno == this_revno]
370
405
        if len(revision_ids) == 1:
371
406
            return revision_ids[0]
373
408
            revno_str = '.'.join(map(str, revno))
374
409
            raise errors.NoSuchRevision(self, revno_str)
375
410
 
 
411
    @needs_read_lock
376
412
    def revision_id_to_dotted_revno(self, revision_id):
377
413
        """Given a revision id, return its dotted revno.
378
414
 
379
415
        :return: a tuple like (1,) or (400,1,3).
380
416
        """
381
 
        with self.lock_read():
382
 
            return self._do_revision_id_to_dotted_revno(revision_id)
 
417
        return self._do_revision_id_to_dotted_revno(revision_id)
383
418
 
384
419
    def _do_revision_id_to_dotted_revno(self, revision_id):
385
420
        """Worker function for revision_id_to_revno."""
402
437
                raise errors.NoSuchRevision(self, revision_id)
403
438
        return result
404
439
 
 
440
    @needs_read_lock
405
441
    def get_revision_id_to_revno_map(self):
406
442
        """Return the revision_id => dotted revno map.
407
443
 
410
446
        :return: A dictionary mapping revision_id => dotted revno.
411
447
            This dictionary should not be modified by the caller.
412
448
        """
413
 
        if 'evil' in debug.debug_flags:
414
 
            mutter_callsite(
415
 
                3, "get_revision_id_to_revno_map scales with ancestry.")
416
 
        with self.lock_read():
417
 
            if self._revision_id_to_revno_cache is not None:
418
 
                mapping = self._revision_id_to_revno_cache
419
 
            else:
420
 
                mapping = self._gen_revno_map()
421
 
                self._cache_revision_id_to_revno(mapping)
422
 
            # TODO: jam 20070417 Since this is being cached, should we be
423
 
            # returning a copy?
424
 
            # I would rather not, and instead just declare that users should
425
 
            # not modify the return value.
426
 
            return mapping
 
449
        if self._revision_id_to_revno_cache is not None:
 
450
            mapping = self._revision_id_to_revno_cache
 
451
        else:
 
452
            mapping = self._gen_revno_map()
 
453
            self._cache_revision_id_to_revno(mapping)
 
454
        # TODO: jam 20070417 Since this is being cached, should we be returning
 
455
        #       a copy?
 
456
        # I would rather not, and instead just declare that users should not
 
457
        # modify the return value.
 
458
        return mapping
427
459
 
428
460
    def _gen_revno_map(self):
429
461
        """Create a new mapping from revision ids to dotted revnos.
435
467
 
436
468
        :return: A dictionary mapping revision_id => dotted revno.
437
469
        """
438
 
        revision_id_to_revno = {
439
 
            rev_id: revno for rev_id, depth, revno, end_of_merge
440
 
            in self.iter_merge_sorted_revisions()}
 
470
        revision_id_to_revno = dict((rev_id, revno)
 
471
            for rev_id, depth, revno, end_of_merge
 
472
             in self.iter_merge_sorted_revisions())
441
473
        return revision_id_to_revno
442
474
 
 
475
    @needs_read_lock
443
476
    def iter_merge_sorted_revisions(self, start_revision_id=None,
444
 
                                    stop_revision_id=None,
445
 
                                    stop_rule='exclude', direction='reverse'):
 
477
            stop_revision_id=None, stop_rule='exclude', direction='reverse'):
446
478
        """Walk the revisions for a branch in merge sorted order.
447
479
 
448
480
        Merge sorted order is the output from a merge-aware,
460
492
            * 'include' - the stop revision is the last item in the result
461
493
            * 'with-merges' - include the stop revision and all of its
462
494
              merged revisions in the result
463
 
            * 'with-merges-without-common-ancestry' - filter out revisions
 
495
            * 'with-merges-without-common-ancestry' - filter out revisions 
464
496
              that are in both ancestries
465
497
        :param direction: either 'reverse' or 'forward':
466
498
 
485
517
            * end_of_merge: When True the next node (earlier in history) is
486
518
              part of a different merge.
487
519
        """
488
 
        with self.lock_read():
489
 
            # Note: depth and revno values are in the context of the branch so
490
 
            # we need the full graph to get stable numbers, regardless of the
491
 
            # start_revision_id.
492
 
            if self._merge_sorted_revisions_cache is None:
493
 
                last_revision = self.last_revision()
494
 
                known_graph = self.repository.get_known_graph_ancestry(
495
 
                    [last_revision])
496
 
                self._merge_sorted_revisions_cache = known_graph.merge_sort(
497
 
                    last_revision)
498
 
            filtered = self._filter_merge_sorted_revisions(
499
 
                self._merge_sorted_revisions_cache, start_revision_id,
500
 
                stop_revision_id, stop_rule)
501
 
            # Make sure we don't return revisions that are not part of the
502
 
            # start_revision_id ancestry.
503
 
            filtered = self._filter_start_non_ancestors(filtered)
504
 
            if direction == 'reverse':
505
 
                return filtered
506
 
            if direction == 'forward':
507
 
                return reversed(list(filtered))
508
 
            else:
509
 
                raise ValueError('invalid direction %r' % direction)
 
520
        # Note: depth and revno values are in the context of the branch so
 
521
        # we need the full graph to get stable numbers, regardless of the
 
522
        # start_revision_id.
 
523
        if self._merge_sorted_revisions_cache is None:
 
524
            last_revision = self.last_revision()
 
525
            known_graph = self.repository.get_known_graph_ancestry(
 
526
                [last_revision])
 
527
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
 
528
                last_revision)
 
529
        filtered = self._filter_merge_sorted_revisions(
 
530
            self._merge_sorted_revisions_cache, start_revision_id,
 
531
            stop_revision_id, stop_rule)
 
532
        # Make sure we don't return revisions that are not part of the
 
533
        # start_revision_id ancestry.
 
534
        filtered = self._filter_start_non_ancestors(filtered)
 
535
        if direction == 'reverse':
 
536
            return filtered
 
537
        if direction == 'forward':
 
538
            return reversed(list(filtered))
 
539
        else:
 
540
            raise ValueError('invalid direction %r' % direction)
510
541
 
511
542
    def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
512
 
                                       start_revision_id, stop_revision_id,
513
 
                                       stop_rule):
 
543
        start_revision_id, stop_revision_id, stop_rule):
514
544
        """Iterate over an inclusive range of sorted revisions."""
515
545
        rev_iter = iter(merge_sorted_revisions)
516
546
        if start_revision_id is not None:
571
601
                if rev_id == left_parent:
572
602
                    # reached the left parent after the stop_revision
573
603
                    return
574
 
                if (not reached_stop_revision_id
575
 
                        or rev_id in revision_id_whitelist):
 
604
                if (not reached_stop_revision_id or
 
605
                        rev_id in revision_id_whitelist):
576
606
                    yield (rev_id, node.merge_depth, node.revno,
577
 
                           node.end_of_merge)
 
607
                       node.end_of_merge)
578
608
                    if reached_stop_revision_id or rev_id == stop_revision_id:
579
609
                        # only do the merged revs of rev_id from now on
580
610
                        rev = self.repository.get_revision(rev_id)
590
620
        # ancestry. Given the order guaranteed by the merge sort, we will see
591
621
        # uninteresting descendants of the first parent of our tip before the
592
622
        # tip itself.
593
 
        try:
594
 
            first = next(rev_iter)
595
 
        except StopIteration:
596
 
            return
 
623
        first = rev_iter.next()
597
624
        (rev_id, merge_depth, revno, end_of_merge) = first
598
625
        yield first
599
626
        if not merge_depth:
636
663
        """Tell this branch object not to release the physical lock when this
637
664
        object is unlocked.
638
665
 
639
 
        If lock_write doesn't return a token, then this method is not
640
 
        supported.
 
666
        If lock_write doesn't return a token, then this method is not supported.
641
667
        """
642
668
        self.control_files.leave_in_place()
643
669
 
645
671
        """Tell this branch object to release the physical lock when this
646
672
        object is unlocked, even if it didn't originally acquire it.
647
673
 
648
 
        If lock_write doesn't return a token, then this method is not
649
 
        supported.
 
674
        If lock_write doesn't return a token, then this method is not supported.
650
675
        """
651
676
        self.control_files.dont_leave_in_place()
652
677
 
670
695
            raise errors.UpgradeRequired(self.user_url)
671
696
        self.get_config_stack().set('append_revisions_only', enabled)
672
697
 
673
 
    def fetch(self, from_branch, stop_revision=None, limit=None, lossy=False):
 
698
    def set_reference_info(self, file_id, tree_path, branch_location):
 
699
        """Set the branch location to use for a tree reference."""
 
700
        raise errors.UnsupportedOperation(self.set_reference_info, self)
 
701
 
 
702
    def get_reference_info(self, file_id):
 
703
        """Get the tree_path and branch_location for a tree reference."""
 
704
        raise errors.UnsupportedOperation(self.get_reference_info, self)
 
705
 
 
706
    @needs_write_lock
 
707
    def fetch(self, from_branch, last_revision=None, limit=None):
674
708
        """Copy revisions from from_branch into this branch.
675
709
 
676
710
        :param from_branch: Where to copy from.
677
 
        :param stop_revision: What revision to stop at (None for at the end
 
711
        :param last_revision: What revision to stop at (None for at the end
678
712
                              of the branch.
679
713
        :param limit: Optional rough limit of revisions to fetch
680
714
        :return: None
681
715
        """
682
 
        with self.lock_write():
683
 
            return InterBranch.get(from_branch, self).fetch(
684
 
                stop_revision, limit=limit, lossy=lossy)
 
716
        return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
685
717
 
686
718
    def get_bound_location(self):
687
719
        """Return the URL of the branch we are bound to.
709
741
        :param revprops: Optional dictionary of revision properties.
710
742
        :param revision_id: Optional revision id.
711
743
        :param lossy: Whether to discard data that can not be natively
712
 
            represented, when pushing to a foreign VCS
 
744
            represented, when pushing to a foreign VCS 
713
745
        """
714
746
 
715
747
        if config_stack is None:
716
748
            config_stack = self.get_config_stack()
717
749
 
718
 
        return self.repository.get_commit_builder(
719
 
            self, parents, config_stack, timestamp, timezone, committer,
720
 
            revprops, revision_id, lossy)
 
750
        return self.repository.get_commit_builder(self, parents, config_stack,
 
751
            timestamp, timezone, committer, revprops, revision_id,
 
752
            lossy)
721
753
 
722
754
    def get_master_branch(self, possible_transports=None):
723
755
        """Return the branch we are bound to.
726
758
        """
727
759
        return None
728
760
 
 
761
    @deprecated_method(deprecated_in((2, 5, 0)))
 
762
    def get_revision_delta(self, revno):
 
763
        """Return the delta for one revision.
 
764
 
 
765
        The delta is relative to its mainline predecessor, or the
 
766
        empty tree for revision 1.
 
767
        """
 
768
        try:
 
769
            revid = self.get_rev_id(revno)
 
770
        except errors.NoSuchRevision:
 
771
            raise errors.InvalidRevisionNumber(revno)
 
772
        return self.repository.get_revision_delta(revid)
 
773
 
729
774
    def get_stacked_on_url(self):
730
775
        """Get the URL this branch is stacked against.
731
776
 
735
780
        """
736
781
        raise NotImplementedError(self.get_stacked_on_url)
737
782
 
 
783
    def print_file(self, file, revision_id):
 
784
        """Print `file` to stdout."""
 
785
        raise NotImplementedError(self.print_file)
 
786
 
 
787
    @needs_write_lock
738
788
    def set_last_revision_info(self, revno, revision_id):
739
789
        """Set the last revision of this branch.
740
790
 
748
798
        """
749
799
        raise NotImplementedError(self.set_last_revision_info)
750
800
 
 
801
    @needs_write_lock
751
802
    def generate_revision_history(self, revision_id, last_rev=None,
752
803
                                  other_branch=None):
753
804
        """See Branch.generate_revision_history"""
754
 
        with self.lock_write():
755
 
            graph = self.repository.get_graph()
756
 
            (last_revno, last_revid) = self.last_revision_info()
757
 
            known_revision_ids = [
758
 
                (last_revid, last_revno),
759
 
                (_mod_revision.NULL_REVISION, 0),
760
 
                ]
761
 
            if last_rev is not None:
762
 
                if not graph.is_ancestor(last_rev, revision_id):
763
 
                    # our previous tip is not merged into stop_revision
764
 
                    raise errors.DivergedBranches(self, other_branch)
765
 
            revno = graph.find_distance_to_null(
766
 
                revision_id, known_revision_ids)
767
 
            self.set_last_revision_info(revno, revision_id)
 
805
        graph = self.repository.get_graph()
 
806
        (last_revno, last_revid) = self.last_revision_info()
 
807
        known_revision_ids = [
 
808
            (last_revid, last_revno),
 
809
            (_mod_revision.NULL_REVISION, 0),
 
810
            ]
 
811
        if last_rev is not None:
 
812
            if not graph.is_ancestor(last_rev, revision_id):
 
813
                # our previous tip is not merged into stop_revision
 
814
                raise errors.DivergedBranches(self, other_branch)
 
815
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
 
816
        self.set_last_revision_info(revno, revision_id)
768
817
 
 
818
    @needs_write_lock
769
819
    def set_parent(self, url):
770
820
        """See Branch.set_parent."""
771
821
        # TODO: Maybe delete old location files?
773
823
        # FIXUP this and get_parent in a future branch format bump:
774
824
        # read and rewrite the file. RBC 20060125
775
825
        if url is not None:
776
 
            if isinstance(url, str):
 
826
            if isinstance(url, unicode):
777
827
                try:
778
 
                    url.encode('ascii')
 
828
                    url = url.encode('ascii')
779
829
                except UnicodeEncodeError:
780
 
                    raise urlutils.InvalidURL(
781
 
                        url, "Urls must be 7-bit ascii, "
782
 
                        "use breezy.urlutils.escape")
 
830
                    raise errors.InvalidURL(url,
 
831
                        "Urls must be 7-bit ascii, "
 
832
                        "use brzlib.urlutils.escape")
783
833
            url = urlutils.relative_url(self.base, url)
784
 
        with self.lock_write():
785
 
            self._set_parent_location(url)
 
834
        self._set_parent_location(url)
786
835
 
 
836
    @needs_write_lock
787
837
    def set_stacked_on_url(self, url):
788
838
        """Set the URL this branch is stacked against.
789
839
 
793
843
            stacking.
794
844
        """
795
845
        if not self._format.supports_stacking():
796
 
            raise UnstackableBranchFormat(self._format, self.user_url)
797
 
        with self.lock_write():
798
 
            # XXX: Changing from one fallback repository to another does not
799
 
            # check that all the data you need is present in the new fallback.
800
 
            # Possibly it should.
801
 
            self._check_stackable_repo()
802
 
            if not url:
803
 
                try:
804
 
                    self.get_stacked_on_url()
805
 
                except (errors.NotStacked, UnstackableBranchFormat,
806
 
                        errors.UnstackableRepositoryFormat):
807
 
                    return
808
 
                self._unstack()
809
 
            else:
810
 
                self._activate_fallback_location(
811
 
                    url, possible_transports=[self.controldir.root_transport])
812
 
            # write this out after the repository is stacked to avoid setting a
813
 
            # stacked config that doesn't work.
814
 
            self._set_config_location('stacked_on_location', url)
 
846
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
847
        # XXX: Changing from one fallback repository to another does not check
 
848
        # that all the data you need is present in the new fallback.
 
849
        # Possibly it should.
 
850
        self._check_stackable_repo()
 
851
        if not url:
 
852
            try:
 
853
                old_url = self.get_stacked_on_url()
 
854
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
855
                errors.UnstackableRepositoryFormat):
 
856
                return
 
857
            self._unstack()
 
858
        else:
 
859
            self._activate_fallback_location(url,
 
860
                possible_transports=[self.bzrdir.root_transport])
 
861
        # write this out after the repository is stacked to avoid setting a
 
862
        # stacked config that doesn't work.
 
863
        self._set_config_location('stacked_on_location', url)
815
864
 
816
865
    def _unstack(self):
817
866
        """Change a branch to be unstacked, copying data as needed.
818
867
 
819
868
        Don't call this directly, use set_stacked_on_url(None).
820
869
        """
821
 
        with ui.ui_factory.nested_progress_bar() as pb:
 
870
        pb = ui.ui_factory.nested_progress_bar()
 
871
        try:
822
872
            pb.update(gettext("Unstacking"))
823
873
            # The basic approach here is to fetch the tip of the branch,
824
874
            # including all available ghosts, from the existing stacked
825
 
            # repository into a new repository object without the fallbacks.
 
875
            # repository into a new repository object without the fallbacks. 
826
876
            #
827
877
            # XXX: See <https://launchpad.net/bugs/397286> - this may not be
828
878
            # correct for CHKMap repostiories
829
879
            old_repository = self.repository
830
880
            if len(old_repository._fallback_repositories) != 1:
831
 
                raise AssertionError(
832
 
                    "can't cope with fallback repositories "
833
 
                    "of %r (fallbacks: %r)" % (
834
 
                        old_repository, old_repository._fallback_repositories))
 
881
                raise AssertionError("can't cope with fallback repositories "
 
882
                    "of %r (fallbacks: %r)" % (old_repository,
 
883
                        old_repository._fallback_repositories))
835
884
            # Open the new repository object.
836
885
            # Repositories don't offer an interface to remove fallback
837
886
            # repositories today; take the conceptually simpler option and just
841
890
            # separate SSH connection setup, but unstacking is not a
842
891
            # common operation so it's tolerable.
843
892
            new_bzrdir = controldir.ControlDir.open(
844
 
                self.controldir.root_transport.base)
 
893
                self.bzrdir.root_transport.base)
845
894
            new_repository = new_bzrdir.find_repository()
846
895
            if new_repository._fallback_repositories:
847
 
                raise AssertionError(
848
 
                    "didn't expect %r to have fallback_repositories"
 
896
                raise AssertionError("didn't expect %r to have "
 
897
                    "fallback_repositories"
849
898
                    % (self.repository,))
850
899
            # Replace self.repository with the new repository.
851
900
            # Do our best to transfer the lock state (i.e. lock-tokens and
878
927
            if old_lock_count == 0:
879
928
                raise AssertionError(
880
929
                    'old_repository should have been locked at least once.')
881
 
            for i in range(old_lock_count - 1):
 
930
            for i in range(old_lock_count-1):
882
931
                self.repository.lock_write()
883
932
            # Fetch from the old repository into the new.
884
 
            with old_repository.lock_read():
 
933
            old_repository.lock_read()
 
934
            try:
885
935
                # XXX: If you unstack a branch while it has a working tree
886
936
                # with a pending merge, the pending-merged revisions will no
887
937
                # longer be present.  You can (probably) revert and remerge.
889
939
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
890
940
                except errors.TagsNotSupported:
891
941
                    tags_to_fetch = set()
892
 
                fetch_spec = vf_search.NotInOtherForRevs(
893
 
                    self.repository, old_repository,
894
 
                    required_ids=[self.last_revision()],
 
942
                fetch_spec = vf_search.NotInOtherForRevs(self.repository,
 
943
                    old_repository, required_ids=[self.last_revision()],
895
944
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
896
945
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
 
946
            finally:
 
947
                old_repository.unlock()
 
948
        finally:
 
949
            pb.finished()
 
950
 
 
951
    def _set_tags_bytes(self, bytes):
 
952
        """Mirror method for _get_tags_bytes.
 
953
 
 
954
        :seealso: Branch._get_tags_bytes.
 
955
        """
 
956
        op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
 
957
        op.add_cleanup(self.lock_write().unlock)
 
958
        return op.run_simple(bytes)
 
959
 
 
960
    def _set_tags_bytes_locked(self, bytes):
 
961
        self._tags_bytes = bytes
 
962
        return self._transport.put_bytes('tags', bytes)
897
963
 
898
964
    def _cache_revision_history(self, rev_history):
899
965
        """Set the cached revision history to rev_history.
930
996
        self._merge_sorted_revisions_cache = None
931
997
        self._partial_revision_history_cache = []
932
998
        self._partial_revision_id_to_revno_cache = {}
 
999
        self._tags_bytes = None
933
1000
 
934
1001
    def _gen_revision_history(self):
935
1002
        """Return sequence of revision hashes on to this branch.
972
1039
        """Return last revision id, or NULL_REVISION."""
973
1040
        return self.last_revision_info()[1]
974
1041
 
 
1042
    @needs_read_lock
975
1043
    def last_revision_info(self):
976
1044
        """Return information about the last revision.
977
1045
 
978
1046
        :return: A tuple (revno, revision_id).
979
1047
        """
980
 
        with self.lock_read():
981
 
            if self._last_revision_info_cache is None:
982
 
                self._last_revision_info_cache = (
983
 
                    self._read_last_revision_info())
984
 
            return self._last_revision_info_cache
 
1048
        if self._last_revision_info_cache is None:
 
1049
            self._last_revision_info_cache = self._read_last_revision_info()
 
1050
        return self._last_revision_info_cache
985
1051
 
986
1052
    def _read_last_revision_info(self):
987
1053
        raise NotImplementedError(self._read_last_revision_info)
1017
1083
        except ValueError:
1018
1084
            raise errors.NoSuchRevision(self, revision_id)
1019
1085
 
 
1086
    @needs_read_lock
1020
1087
    def get_rev_id(self, revno, history=None):
1021
1088
        """Find the revision id of the specified revno."""
1022
 
        with self.lock_read():
1023
 
            if revno == 0:
1024
 
                return _mod_revision.NULL_REVISION
1025
 
            last_revno, last_revid = self.last_revision_info()
1026
 
            if revno == last_revno:
1027
 
                return last_revid
1028
 
            if revno <= 0 or revno > last_revno:
1029
 
                raise errors.NoSuchRevision(self, revno)
1030
 
            distance_from_last = last_revno - revno
1031
 
            if len(self._partial_revision_history_cache) <= distance_from_last:
1032
 
                self._extend_partial_history(distance_from_last)
1033
 
            return self._partial_revision_history_cache[distance_from_last]
 
1089
        if revno == 0:
 
1090
            return _mod_revision.NULL_REVISION
 
1091
        last_revno, last_revid = self.last_revision_info()
 
1092
        if revno == last_revno:
 
1093
            return last_revid
 
1094
        if revno <= 0 or revno > last_revno:
 
1095
            raise errors.NoSuchRevision(self, revno)
 
1096
        distance_from_last = last_revno - revno
 
1097
        if len(self._partial_revision_history_cache) <= distance_from_last:
 
1098
            self._extend_partial_history(distance_from_last)
 
1099
        return self._partial_revision_history_cache[distance_from_last]
1034
1100
 
1035
1101
    def pull(self, source, overwrite=False, stop_revision=None,
1036
1102
             possible_transports=None, *args, **kwargs):
1040
1106
 
1041
1107
        :returns: PullResult instance
1042
1108
        """
1043
 
        return InterBranch.get(source, self).pull(
1044
 
            overwrite=overwrite, stop_revision=stop_revision,
 
1109
        return InterBranch.get(source, self).pull(overwrite=overwrite,
 
1110
            stop_revision=stop_revision,
1045
1111
            possible_transports=possible_transports, *args, **kwargs)
1046
1112
 
1047
1113
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1048
 
             *args, **kwargs):
 
1114
            *args, **kwargs):
1049
1115
        """Mirror this branch into target.
1050
1116
 
1051
1117
        This branch is considered to be 'local', having low latency.
1052
1118
        """
1053
 
        return InterBranch.get(self, target).push(
1054
 
            overwrite, stop_revision, lossy, *args, **kwargs)
 
1119
        return InterBranch.get(self, target).push(overwrite, stop_revision,
 
1120
            lossy, *args, **kwargs)
1055
1121
 
1056
1122
    def basis_tree(self):
1057
1123
        """Return `Tree` object for last revision."""
1070
1136
        # This is an old-format absolute path to a local branch
1071
1137
        # turn it into a url
1072
1138
        if parent.startswith('/'):
1073
 
            parent = urlutils.local_path_to_url(parent)
 
1139
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
1074
1140
        try:
1075
1141
            return urlutils.join(self.base[:-1], parent)
1076
 
        except urlutils.InvalidURLJoin:
 
1142
        except errors.InvalidURLJoin, e:
1077
1143
            raise errors.InaccessibleParent(parent, self.user_url)
1078
1144
 
1079
1145
    def _get_parent_location(self):
1165
1231
        for hook in hooks:
1166
1232
            hook(params)
1167
1233
 
 
1234
    @needs_write_lock
1168
1235
    def update(self):
1169
1236
        """Synchronise this branch with the master branch if any.
1170
1237
 
1188
1255
        if revno < 1 or revno > self.revno():
1189
1256
            raise errors.InvalidRevisionNumber(revno)
1190
1257
 
1191
 
    def clone(self, to_controldir, revision_id=None, repository_policy=None):
1192
 
        """Clone this branch into to_controldir preserving all semantic values.
 
1258
    @needs_read_lock
 
1259
    def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1260
        """Clone this branch into to_bzrdir preserving all semantic values.
1193
1261
 
1194
1262
        Most API users will want 'create_clone_on_transport', which creates a
1195
1263
        new bzrdir and branch on the fly.
1197
1265
        revision_id: if not None, the revision history in the new branch will
1198
1266
                     be truncated to end with revision_id.
1199
1267
        """
1200
 
        result = to_controldir.create_branch()
1201
 
        with self.lock_read(), result.lock_write():
 
1268
        result = to_bzrdir.create_branch()
 
1269
        result.lock_write()
 
1270
        try:
1202
1271
            if repository_policy is not None:
1203
1272
                repository_policy.configure_branch(result)
1204
1273
            self.copy_content_into(result, revision_id=revision_id)
 
1274
        finally:
 
1275
            result.unlock()
1205
1276
        return result
1206
1277
 
1207
 
    def sprout(self, to_controldir, revision_id=None, repository_policy=None,
1208
 
               repository=None, lossy=False):
1209
 
        """Create a new line of development from the branch, into to_controldir.
 
1278
    @needs_read_lock
 
1279
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1280
            repository=None):
 
1281
        """Create a new line of development from the branch, into to_bzrdir.
1210
1282
 
1211
 
        to_controldir controls the branch format.
 
1283
        to_bzrdir controls the branch format.
1212
1284
 
1213
1285
        revision_id: if not None, the revision history in the new branch will
1214
1286
                     be truncated to end with revision_id.
1215
1287
        """
1216
 
        if (repository_policy is not None
1217
 
                and repository_policy.requires_stacking()):
1218
 
            to_controldir._format.require_stacking(_skip_repo=True)
1219
 
        result = to_controldir.create_branch(repository=repository)
1220
 
        if lossy:
1221
 
            raise errors.LossyPushToSameVCS(self, result)
1222
 
        with self.lock_read(), result.lock_write():
 
1288
        if (repository_policy is not None and
 
1289
            repository_policy.requires_stacking()):
 
1290
            to_bzrdir._format.require_stacking(_skip_repo=True)
 
1291
        result = to_bzrdir.create_branch(repository=repository)
 
1292
        result.lock_write()
 
1293
        try:
1223
1294
            if repository_policy is not None:
1224
1295
                repository_policy.configure_branch(result)
1225
1296
            self.copy_content_into(result, revision_id=revision_id)
1226
1297
            master_url = self.get_bound_location()
1227
1298
            if master_url is None:
1228
 
                result.set_parent(self.user_url)
 
1299
                result.set_parent(self.bzrdir.root_transport.base)
1229
1300
            else:
1230
1301
                result.set_parent(master_url)
 
1302
        finally:
 
1303
            result.unlock()
1231
1304
        return result
1232
1305
 
1233
1306
    def _synchronize_history(self, destination, revision_id):
1248
1321
        else:
1249
1322
            graph = self.repository.get_graph()
1250
1323
            try:
1251
 
                revno = graph.find_distance_to_null(
1252
 
                    revision_id, [(source_revision_id, source_revno)])
 
1324
                revno = graph.find_distance_to_null(revision_id, 
 
1325
                    [(source_revision_id, source_revno)])
1253
1326
            except errors.GhostRevisionsHaveNoRevno:
1254
1327
                # Default to 1, if we can't find anything else
1255
1328
                revno = 1
1265
1338
            revision_id=revision_id)
1266
1339
 
1267
1340
    def update_references(self, target):
1268
 
        if not self._format.supports_reference_locations:
1269
 
            return
1270
 
        return InterBranch.get(self, target).update_references()
 
1341
        if not getattr(self._format, 'supports_reference_locations', False):
 
1342
            return
 
1343
        reference_dict = self._get_all_reference_info()
 
1344
        if len(reference_dict) == 0:
 
1345
            return
 
1346
        old_base = self.base
 
1347
        new_base = target.base
 
1348
        target_reference_dict = target._get_all_reference_info()
 
1349
        for file_id, (tree_path, branch_location) in (
 
1350
            reference_dict.items()):
 
1351
            branch_location = urlutils.rebase_url(branch_location,
 
1352
                                                  old_base, new_base)
 
1353
            target_reference_dict.setdefault(
 
1354
                file_id, (tree_path, branch_location))
 
1355
        target._set_all_reference_info(target_reference_dict)
1271
1356
 
 
1357
    @needs_read_lock
1272
1358
    def check(self, refs):
1273
1359
        """Check consistency of the branch.
1274
1360
 
1282
1368
            branch._get_check_refs()
1283
1369
        :return: A BranchCheckResult.
1284
1370
        """
1285
 
        with self.lock_read():
1286
 
            result = BranchCheckResult(self)
1287
 
            last_revno, last_revision_id = self.last_revision_info()
1288
 
            actual_revno = refs[('lefthand-distance', last_revision_id)]
1289
 
            if actual_revno != last_revno:
1290
 
                result.errors.append(errors.BzrCheckError(
1291
 
                    'revno does not match len(mainline) %s != %s' % (
1292
 
                        last_revno, actual_revno)))
1293
 
            # TODO: We should probably also check that self.revision_history
1294
 
            # matches the repository for older branch formats.
1295
 
            # If looking for the code that cross-checks repository parents
1296
 
            # against the Graph.iter_lefthand_ancestry output, that is now a
1297
 
            # repository specific check.
1298
 
            return result
 
1371
        result = BranchCheckResult(self)
 
1372
        last_revno, last_revision_id = self.last_revision_info()
 
1373
        actual_revno = refs[('lefthand-distance', last_revision_id)]
 
1374
        if actual_revno != last_revno:
 
1375
            result.errors.append(errors.BzrCheckError(
 
1376
                'revno does not match len(mainline) %s != %s' % (
 
1377
                last_revno, actual_revno)))
 
1378
        # TODO: We should probably also check that self.revision_history
 
1379
        # matches the repository for older branch formats.
 
1380
        # If looking for the code that cross-checks repository parents against
 
1381
        # the Graph.iter_lefthand_ancestry output, that is now a repository
 
1382
        # specific check.
 
1383
        return result
1299
1384
 
1300
1385
    def _get_checkout_format(self, lightweight=False):
1301
1386
        """Return the most suitable metadir for a checkout of this branch.
1302
1387
        Weaves are used if this branch's repository uses weaves.
1303
1388
        """
1304
 
        format = self.repository.controldir.checkout_metadir()
 
1389
        format = self.repository.bzrdir.checkout_metadir()
1305
1390
        format.set_branch_format(self._format)
1306
1391
        return format
1307
1392
 
1308
1393
    def create_clone_on_transport(self, to_transport, revision_id=None,
1309
 
                                  stacked_on=None, create_prefix=False,
1310
 
                                  use_existing_dir=False, no_tree=None):
 
1394
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1395
        no_tree=None):
1311
1396
        """Create a clone of this branch and its bzrdir.
1312
1397
 
1313
1398
        :param to_transport: The transport to clone onto.
1320
1405
        """
1321
1406
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1322
1407
        # clone call. Or something. 20090224 RBC/spiv.
1323
 
        # XXX: Should this perhaps clone colocated branches as well,
 
1408
        # XXX: Should this perhaps clone colocated branches as well, 
1324
1409
        # rather than just the default branch? 20100319 JRV
1325
1410
        if revision_id is None:
1326
1411
            revision_id = self.last_revision()
1327
 
        dir_to = self.controldir.clone_on_transport(
1328
 
            to_transport, revision_id=revision_id, stacked_on=stacked_on,
 
1412
        dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1413
            revision_id=revision_id, stacked_on=stacked_on,
1329
1414
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1330
1415
            no_tree=no_tree)
1331
1416
        return dir_to.open_branch()
1332
1417
 
1333
1418
    def create_checkout(self, to_location, revision_id=None,
1334
1419
                        lightweight=False, accelerator_tree=None,
1335
 
                        hardlink=False, recurse_nested=True):
 
1420
                        hardlink=False):
1336
1421
        """Create a checkout of a branch.
1337
1422
 
1338
1423
        :param to_location: The url to produce the checkout at
1345
1430
            content is different.
1346
1431
        :param hardlink: If true, hard-link files from accelerator_tree,
1347
1432
            where possible.
1348
 
        :param recurse_nested: Whether to recurse into nested trees
1349
1433
        :return: The tree of the created checkout
1350
1434
        """
1351
1435
        t = transport.get_transport(to_location)
1363
1447
                pass
1364
1448
            else:
1365
1449
                raise errors.AlreadyControlDirError(t.base)
1366
 
            if (checkout.control_transport.base
1367
 
                    == self.controldir.control_transport.base):
 
1450
            if checkout.control_transport.base == self.bzrdir.control_transport.base:
1368
1451
                # When checking out to the same control directory,
1369
1452
                # always create a lightweight checkout
1370
1453
                lightweight = True
1373
1456
            from_branch = checkout.set_branch_reference(target_branch=self)
1374
1457
        else:
1375
1458
            policy = checkout.determine_repository_policy()
1376
 
            policy.acquire_repository()
 
1459
            repo = policy.acquire_repository()[0]
1377
1460
            checkout_branch = checkout.create_branch()
1378
1461
            checkout_branch.bind(self)
1379
1462
            # pull up to the specified revision_id to set the initial
1385
1468
                                           accelerator_tree=accelerator_tree,
1386
1469
                                           hardlink=hardlink)
1387
1470
        basis_tree = tree.basis_tree()
1388
 
        with basis_tree.lock_read():
1389
 
            for path in basis_tree.iter_references():
1390
 
                reference_parent = tree.reference_parent(path)
1391
 
                if reference_parent is None:
1392
 
                    warning('Branch location for %s unknown.', path)
1393
 
                    continue
1394
 
                reference_parent.create_checkout(
1395
 
                    tree.abspath(path),
1396
 
                    basis_tree.get_reference_revision(path), lightweight)
 
1471
        basis_tree.lock_read()
 
1472
        try:
 
1473
            for path, file_id in basis_tree.iter_references():
 
1474
                reference_parent = self.reference_parent(file_id, path)
 
1475
                reference_parent.create_checkout(tree.abspath(path),
 
1476
                    basis_tree.get_reference_revision(file_id, path),
 
1477
                    lightweight)
 
1478
        finally:
 
1479
            basis_tree.unlock()
1397
1480
        return tree
1398
1481
 
 
1482
    @needs_write_lock
1399
1483
    def reconcile(self, thorough=True):
1400
 
        """Make sure the data stored in this branch is consistent.
1401
 
 
1402
 
        :return: A `ReconcileResult` object.
 
1484
        """Make sure the data stored in this branch is consistent."""
 
1485
        from brzlib.reconcile import BranchReconciler
 
1486
        reconciler = BranchReconciler(self, thorough=thorough)
 
1487
        reconciler.reconcile()
 
1488
        return reconciler
 
1489
 
 
1490
    def reference_parent(self, file_id, path, possible_transports=None):
 
1491
        """Return the parent branch for a tree-reference file_id
 
1492
 
 
1493
        :param file_id: The file_id of the tree reference
 
1494
        :param path: The path of the file_id in the tree
 
1495
        :return: A branch associated with the file_id
1403
1496
        """
1404
 
        raise NotImplementedError(self.reconcile)
 
1497
        # FIXME should provide multiple branches, based on config
 
1498
        return Branch.open(self.bzrdir.root_transport.clone(path).base,
 
1499
                           possible_transports=possible_transports)
1405
1500
 
1406
1501
    def supports_tags(self):
1407
1502
        return self._format.supports_tags()
1443
1538
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1444
1539
        """
1445
1540
        heads = graph.heads([revision_a, revision_b])
1446
 
        if heads == {revision_b}:
 
1541
        if heads == set([revision_b]):
1447
1542
            return 'b_descends_from_a'
1448
 
        elif heads == {revision_a, revision_b}:
 
1543
        elif heads == set([revision_a, revision_b]):
1449
1544
            # These branches have diverged
1450
1545
            return 'diverged'
1451
 
        elif heads == {revision_a}:
 
1546
        elif heads == set([revision_a]):
1452
1547
            return 'a_descends_from_b'
1453
1548
        else:
1454
1549
            raise AssertionError("invalid heads: %r" % (heads,))
1464
1559
        """
1465
1560
        # For bzr native formats must_fetch is just the tip, and
1466
1561
        # if_present_fetch are the tags.
1467
 
        must_fetch = {self.last_revision()}
 
1562
        must_fetch = set([self.last_revision()])
1468
1563
        if_present_fetch = set()
1469
1564
        if self.get_config_stack().get('branch.fetch_tags'):
1470
1565
            try:
1475
1570
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1476
1571
        return must_fetch, if_present_fetch
1477
1572
 
1478
 
    def create_memorytree(self):
1479
 
        """Create a memory tree for this branch.
1480
 
 
1481
 
        :return: An in-memory MutableTree instance
1482
 
        """
1483
 
        return memorytree.MemoryTree.create_on_branch(self)
1484
 
 
1485
1573
 
1486
1574
class BranchFormat(controldir.ControlComponentFormat):
1487
1575
    """An encapsulation of the initialization and open routines for a format.
1588
1676
        raise NotImplementedError(self.network_name)
1589
1677
 
1590
1678
    def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
1591
 
             found_repository=None, possible_transports=None):
 
1679
            found_repository=None, possible_transports=None):
1592
1680
        """Return the branch object for controldir.
1593
1681
 
1594
1682
        :param controldir: A ControlDir that contains a branch.
1610
1698
 
1611
1699
    def supports_leaving_lock(self):
1612
1700
        """True if this format supports leaving locks in place."""
1613
 
        return False  # by default
 
1701
        return False # by default
1614
1702
 
1615
1703
    def __str__(self):
1616
1704
        return self.get_format_description().rstrip()
1627
1715
        """True if tags can reference ghost revisions."""
1628
1716
        return True
1629
1717
 
1630
 
    def supports_store_uncommitted(self):
1631
 
        """True if uncommitted changes can be stored in this branch."""
1632
 
        return True
1633
 
 
1634
 
    def stores_revno(self):
1635
 
        """True if this branch format store revision numbers."""
1636
 
        return True
 
1718
 
 
1719
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1720
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1721
    
 
1722
    While none of the built in BranchFormats are lazy registered yet,
 
1723
    brzlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1724
    use it, and the bzr-loom plugin uses it as well (see
 
1725
    brzlib.plugins.loom.formats).
 
1726
    """
 
1727
 
 
1728
    def __init__(self, format_string, module_name, member_name):
 
1729
        """Create a MetaDirBranchFormatFactory.
 
1730
 
 
1731
        :param format_string: The format string the format has.
 
1732
        :param module_name: Module to load the format class from.
 
1733
        :param member_name: Attribute name within the module for the format class.
 
1734
        """
 
1735
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1736
        self._format_string = format_string
 
1737
 
 
1738
    def get_format_string(self):
 
1739
        """See BranchFormat.get_format_string."""
 
1740
        return self._format_string
 
1741
 
 
1742
    def __call__(self):
 
1743
        """Used for network_format_registry support."""
 
1744
        return self.get_obj()()
1637
1745
 
1638
1746
 
1639
1747
class BranchHooks(Hooks):
1649
1757
        These are all empty initially, because by default nothing should get
1650
1758
        notified.
1651
1759
        """
1652
 
        Hooks.__init__(self, "breezy.branch", "Branch.hooks")
1653
 
        self.add_hook(
1654
 
            'open',
 
1760
        Hooks.__init__(self, "brzlib.branch", "Branch.hooks")
 
1761
        self.add_hook('open',
1655
1762
            "Called with the Branch object that has been opened after a "
1656
1763
            "branch is opened.", (1, 8))
1657
 
        self.add_hook(
1658
 
            'post_push',
 
1764
        self.add_hook('post_push',
1659
1765
            "Called after a push operation completes. post_push is called "
1660
 
            "with a breezy.branch.BranchPushResult object and only runs in "
1661
 
            "the bzr client.", (0, 15))
1662
 
        self.add_hook(
1663
 
            'post_pull',
 
1766
            "with a brzlib.branch.BranchPushResult object and only runs in the "
 
1767
            "bzr client.", (0, 15))
 
1768
        self.add_hook('post_pull',
1664
1769
            "Called after a pull operation completes. post_pull is called "
1665
 
            "with a breezy.branch.PullResult object and only runs in the "
 
1770
            "with a brzlib.branch.PullResult object and only runs in the "
1666
1771
            "bzr client.", (0, 15))
1667
 
        self.add_hook(
1668
 
            'pre_commit',
 
1772
        self.add_hook('pre_commit',
1669
1773
            "Called after a commit is calculated but before it is "
1670
1774
            "completed. pre_commit is called with (local, master, old_revno, "
1671
1775
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1674
1778
            "basis revision. hooks MUST NOT modify this delta. "
1675
1779
            " future_tree is an in-memory tree obtained from "
1676
1780
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1677
 
            "tree.", (0, 91))
1678
 
        self.add_hook(
1679
 
            'post_commit',
 
1781
            "tree.", (0,91))
 
1782
        self.add_hook('post_commit',
1680
1783
            "Called in the bzr client after a commit has completed. "
1681
1784
            "post_commit is called with (local, master, old_revno, old_revid, "
1682
1785
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1683
1786
            "commit to a branch.", (0, 15))
1684
 
        self.add_hook(
1685
 
            'post_uncommit',
 
1787
        self.add_hook('post_uncommit',
1686
1788
            "Called in the bzr client after an uncommit completes. "
1687
1789
            "post_uncommit is called with (local, master, old_revno, "
1688
1790
            "old_revid, new_revno, new_revid) where local is the local branch "
1689
1791
            "or None, master is the target branch, and an empty branch "
1690
1792
            "receives new_revno of 0, new_revid of None.", (0, 15))
1691
 
        self.add_hook(
1692
 
            'pre_change_branch_tip',
 
1793
        self.add_hook('pre_change_branch_tip',
1693
1794
            "Called in bzr client and server before a change to the tip of a "
1694
1795
            "branch is made. pre_change_branch_tip is called with a "
1695
 
            "breezy.branch.ChangeBranchTipParams. Note that push, pull, "
 
1796
            "brzlib.branch.ChangeBranchTipParams. Note that push, pull, "
1696
1797
            "commit, uncommit will all trigger this hook.", (1, 6))
1697
 
        self.add_hook(
1698
 
            'post_change_branch_tip',
 
1798
        self.add_hook('post_change_branch_tip',
1699
1799
            "Called in bzr client and server after a change to the tip of a "
1700
1800
            "branch is made. post_change_branch_tip is called with a "
1701
 
            "breezy.branch.ChangeBranchTipParams. Note that push, pull, "
 
1801
            "brzlib.branch.ChangeBranchTipParams. Note that push, pull, "
1702
1802
            "commit, uncommit will all trigger this hook.", (1, 4))
1703
 
        self.add_hook(
1704
 
            'transform_fallback_location',
 
1803
        self.add_hook('transform_fallback_location',
1705
1804
            "Called when a stacked branch is activating its fallback "
1706
1805
            "locations. transform_fallback_location is called with (branch, "
1707
1806
            "url), and should return a new url. Returning the same url "
1713
1812
            "multiple hooks installed for transform_fallback_location, "
1714
1813
            "all are called with the url returned from the previous hook."
1715
1814
            "The order is however undefined.", (1, 9))
1716
 
        self.add_hook(
1717
 
            'automatic_tag_name',
 
1815
        self.add_hook('automatic_tag_name',
1718
1816
            "Called to determine an automatic tag name for a revision. "
1719
1817
            "automatic_tag_name is called with (branch, revision_id) and "
1720
1818
            "should return a tag name or None if no tag name could be "
1721
1819
            "determined. The first non-None tag name returned will be used.",
1722
1820
            (2, 2))
1723
 
        self.add_hook(
1724
 
            'post_branch_init',
 
1821
        self.add_hook('post_branch_init',
1725
1822
            "Called after new branch initialization completes. "
1726
1823
            "post_branch_init is called with a "
1727
 
            "breezy.branch.BranchInitHookParams. "
 
1824
            "brzlib.branch.BranchInitHookParams. "
1728
1825
            "Note that init, branch and checkout (both heavyweight and "
1729
1826
            "lightweight) will all trigger this hook.", (2, 2))
1730
 
        self.add_hook(
1731
 
            'post_switch',
 
1827
        self.add_hook('post_switch',
1732
1828
            "Called after a checkout switches branch. "
1733
1829
            "post_switch is called with a "
1734
 
            "breezy.branch.SwitchHookParams.", (2, 2))
 
1830
            "brzlib.branch.SwitchHookParams.", (2, 2))
 
1831
 
1735
1832
 
1736
1833
 
1737
1834
# install the default hooks into the Branch class.
1805
1902
        in branch, which refer to the original branch.
1806
1903
        """
1807
1904
        self.format = format
1808
 
        self.controldir = controldir
 
1905
        self.bzrdir = controldir
1809
1906
        self.name = name
1810
1907
        self.branch = branch
1811
1908
 
1844
1941
        return self.__dict__ == other.__dict__
1845
1942
 
1846
1943
    def __repr__(self):
1847
 
        return "<%s for %s to (%s, %s)>" % (
1848
 
            self.__class__.__name__, self.control_dir, self.to_branch,
 
1944
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
 
1945
            self.control_dir, self.to_branch,
1849
1946
            self.revision_id)
1850
1947
 
1851
1948
 
 
1949
class BranchFormatMetadir(bzrdir.BzrFormat, BranchFormat):
 
1950
    """Base class for branch formats that live in meta directories.
 
1951
    """
 
1952
 
 
1953
    def __init__(self):
 
1954
        BranchFormat.__init__(self)
 
1955
        bzrdir.BzrFormat.__init__(self)
 
1956
 
 
1957
    @classmethod
 
1958
    def find_format(klass, controldir, name=None):
 
1959
        """Return the format for the branch object in controldir."""
 
1960
        try:
 
1961
            transport = controldir.get_branch_transport(None, name=name)
 
1962
        except errors.NoSuchFile:
 
1963
            raise errors.NotBranchError(path=name, bzrdir=controldir)
 
1964
        try:
 
1965
            format_string = transport.get_bytes("format")
 
1966
        except errors.NoSuchFile:
 
1967
            raise errors.NotBranchError(path=transport.base, bzrdir=controldir)
 
1968
        return klass._find_format(format_registry, 'branch', format_string)
 
1969
 
 
1970
    def _branch_class(self):
 
1971
        """What class to instantiate on open calls."""
 
1972
        raise NotImplementedError(self._branch_class)
 
1973
 
 
1974
    def _get_initial_config(self, append_revisions_only=None):
 
1975
        if append_revisions_only:
 
1976
            return "append_revisions_only = True\n"
 
1977
        else:
 
1978
            # Avoid writing anything if append_revisions_only is disabled,
 
1979
            # as that is the default.
 
1980
            return ""
 
1981
 
 
1982
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1983
                           repository=None):
 
1984
        """Initialize a branch in a control dir, with specified files
 
1985
 
 
1986
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1987
        :param utf8_files: The files to create as a list of
 
1988
            (filename, content) tuples
 
1989
        :param name: Name of colocated branch to create, if any
 
1990
        :return: a branch in this format
 
1991
        """
 
1992
        if name is None:
 
1993
            name = a_bzrdir._get_selected_branch()
 
1994
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1995
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1996
        control_files = lockable_files.LockableFiles(branch_transport,
 
1997
            'lock', lockdir.LockDir)
 
1998
        control_files.create_lock()
 
1999
        control_files.lock_write()
 
2000
        try:
 
2001
            utf8_files += [('format', self.as_string())]
 
2002
            for (filename, content) in utf8_files:
 
2003
                branch_transport.put_bytes(
 
2004
                    filename, content,
 
2005
                    mode=a_bzrdir._get_file_mode())
 
2006
        finally:
 
2007
            control_files.unlock()
 
2008
        branch = self.open(a_bzrdir, name, _found=True,
 
2009
                found_repository=repository)
 
2010
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2011
        return branch
 
2012
 
 
2013
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2014
            found_repository=None, possible_transports=None):
 
2015
        """See BranchFormat.open()."""
 
2016
        if name is None:
 
2017
            name = a_bzrdir._get_selected_branch()
 
2018
        if not _found:
 
2019
            format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
 
2020
            if format.__class__ != self.__class__:
 
2021
                raise AssertionError("wrong format %r found for %r" %
 
2022
                    (format, self))
 
2023
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2024
        try:
 
2025
            control_files = lockable_files.LockableFiles(transport, 'lock',
 
2026
                                                         lockdir.LockDir)
 
2027
            if found_repository is None:
 
2028
                found_repository = a_bzrdir.find_repository()
 
2029
            return self._branch_class()(_format=self,
 
2030
                              _control_files=control_files,
 
2031
                              name=name,
 
2032
                              a_bzrdir=a_bzrdir,
 
2033
                              _repository=found_repository,
 
2034
                              ignore_fallbacks=ignore_fallbacks,
 
2035
                              possible_transports=possible_transports)
 
2036
        except errors.NoSuchFile:
 
2037
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
2038
 
 
2039
    @property
 
2040
    def _matchingbzrdir(self):
 
2041
        ret = bzrdir.BzrDirMetaFormat1()
 
2042
        ret.set_branch_format(self)
 
2043
        return ret
 
2044
 
 
2045
    def supports_tags(self):
 
2046
        return True
 
2047
 
 
2048
    def supports_leaving_lock(self):
 
2049
        return True
 
2050
 
 
2051
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
 
2052
            basedir=None):
 
2053
        BranchFormat.check_support_status(self,
 
2054
            allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
 
2055
            basedir=basedir)
 
2056
        bzrdir.BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
 
2057
            recommend_upgrade=recommend_upgrade, basedir=basedir)
 
2058
 
 
2059
 
 
2060
class BzrBranchFormat6(BranchFormatMetadir):
 
2061
    """Branch format with last-revision and tags.
 
2062
 
 
2063
    Unlike previous formats, this has no explicit revision history. Instead,
 
2064
    this just stores the last-revision, and the left-hand history leading
 
2065
    up to there is the history.
 
2066
 
 
2067
    This format was introduced in bzr 0.15
 
2068
    and became the default in 0.91.
 
2069
    """
 
2070
 
 
2071
    def _branch_class(self):
 
2072
        return BzrBranch6
 
2073
 
 
2074
    @classmethod
 
2075
    def get_format_string(cls):
 
2076
        """See BranchFormat.get_format_string()."""
 
2077
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
 
2078
 
 
2079
    def get_format_description(self):
 
2080
        """See BranchFormat.get_format_description()."""
 
2081
        return "Branch format 6"
 
2082
 
 
2083
    def initialize(self, a_bzrdir, name=None, repository=None,
 
2084
                   append_revisions_only=None):
 
2085
        """Create a branch of this format in a_bzrdir."""
 
2086
        utf8_files = [('last-revision', '0 null:\n'),
 
2087
                      ('branch.conf',
 
2088
                          self._get_initial_config(append_revisions_only)),
 
2089
                      ('tags', ''),
 
2090
                      ]
 
2091
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2092
 
 
2093
    def make_tags(self, branch):
 
2094
        """See brzlib.branch.BranchFormat.make_tags()."""
 
2095
        return _mod_tag.BasicTags(branch)
 
2096
 
 
2097
    def supports_set_append_revisions_only(self):
 
2098
        return True
 
2099
 
 
2100
 
 
2101
class BzrBranchFormat8(BranchFormatMetadir):
 
2102
    """Metadir format supporting storing locations of subtree branches."""
 
2103
 
 
2104
    def _branch_class(self):
 
2105
        return BzrBranch8
 
2106
 
 
2107
    @classmethod
 
2108
    def get_format_string(cls):
 
2109
        """See BranchFormat.get_format_string()."""
 
2110
        return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
 
2111
 
 
2112
    def get_format_description(self):
 
2113
        """See BranchFormat.get_format_description()."""
 
2114
        return "Branch format 8"
 
2115
 
 
2116
    def initialize(self, a_bzrdir, name=None, repository=None,
 
2117
                   append_revisions_only=None):
 
2118
        """Create a branch of this format in a_bzrdir."""
 
2119
        utf8_files = [('last-revision', '0 null:\n'),
 
2120
                      ('branch.conf',
 
2121
                          self._get_initial_config(append_revisions_only)),
 
2122
                      ('tags', ''),
 
2123
                      ('references', '')
 
2124
                      ]
 
2125
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2126
 
 
2127
    def make_tags(self, branch):
 
2128
        """See brzlib.branch.BranchFormat.make_tags()."""
 
2129
        return _mod_tag.BasicTags(branch)
 
2130
 
 
2131
    def supports_set_append_revisions_only(self):
 
2132
        return True
 
2133
 
 
2134
    def supports_stacking(self):
 
2135
        return True
 
2136
 
 
2137
    supports_reference_locations = True
 
2138
 
 
2139
 
 
2140
class BzrBranchFormat7(BranchFormatMetadir):
 
2141
    """Branch format with last-revision, tags, and a stacked location pointer.
 
2142
 
 
2143
    The stacked location pointer is passed down to the repository and requires
 
2144
    a repository format with supports_external_lookups = True.
 
2145
 
 
2146
    This format was introduced in bzr 1.6.
 
2147
    """
 
2148
 
 
2149
    def initialize(self, a_bzrdir, name=None, repository=None,
 
2150
                   append_revisions_only=None):
 
2151
        """Create a branch of this format in a_bzrdir."""
 
2152
        utf8_files = [('last-revision', '0 null:\n'),
 
2153
                      ('branch.conf',
 
2154
                          self._get_initial_config(append_revisions_only)),
 
2155
                      ('tags', ''),
 
2156
                      ]
 
2157
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2158
 
 
2159
    def _branch_class(self):
 
2160
        return BzrBranch7
 
2161
 
 
2162
    @classmethod
 
2163
    def get_format_string(cls):
 
2164
        """See BranchFormat.get_format_string()."""
 
2165
        return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
 
2166
 
 
2167
    def get_format_description(self):
 
2168
        """See BranchFormat.get_format_description()."""
 
2169
        return "Branch format 7"
 
2170
 
 
2171
    def supports_set_append_revisions_only(self):
 
2172
        return True
 
2173
 
 
2174
    def supports_stacking(self):
 
2175
        return True
 
2176
 
 
2177
    def make_tags(self, branch):
 
2178
        """See brzlib.branch.BranchFormat.make_tags()."""
 
2179
        return _mod_tag.BasicTags(branch)
 
2180
 
 
2181
    supports_reference_locations = False
 
2182
 
 
2183
 
 
2184
class BranchReferenceFormat(BranchFormatMetadir):
 
2185
    """Bzr branch reference format.
 
2186
 
 
2187
    Branch references are used in implementing checkouts, they
 
2188
    act as an alias to the real branch which is at some other url.
 
2189
 
 
2190
    This format has:
 
2191
     - A location file
 
2192
     - a format string
 
2193
    """
 
2194
 
 
2195
    @classmethod
 
2196
    def get_format_string(cls):
 
2197
        """See BranchFormat.get_format_string()."""
 
2198
        return "Bazaar-NG Branch Reference Format 1\n"
 
2199
 
 
2200
    def get_format_description(self):
 
2201
        """See BranchFormat.get_format_description()."""
 
2202
        return "Checkout reference format 1"
 
2203
 
 
2204
    def get_reference(self, a_bzrdir, name=None):
 
2205
        """See BranchFormat.get_reference()."""
 
2206
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2207
        return transport.get_bytes('location')
 
2208
 
 
2209
    def set_reference(self, a_bzrdir, name, to_branch):
 
2210
        """See BranchFormat.set_reference()."""
 
2211
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2212
        location = transport.put_bytes('location', to_branch.base)
 
2213
 
 
2214
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2215
            repository=None, append_revisions_only=None):
 
2216
        """Create a branch of this format in a_bzrdir."""
 
2217
        if target_branch is None:
 
2218
            # this format does not implement branch itself, thus the implicit
 
2219
            # creation contract must see it as uninitializable
 
2220
            raise errors.UninitializableFormat(self)
 
2221
        mutter('creating branch reference in %s', a_bzrdir.user_url)
 
2222
        if a_bzrdir._format.fixed_components:
 
2223
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
 
2224
        if name is None:
 
2225
            name = a_bzrdir._get_selected_branch()
 
2226
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
2227
        branch_transport.put_bytes('location',
 
2228
            target_branch.user_url)
 
2229
        branch_transport.put_bytes('format', self.as_string())
 
2230
        branch = self.open(a_bzrdir, name, _found=True,
 
2231
            possible_transports=[target_branch.bzrdir.root_transport])
 
2232
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2233
        return branch
 
2234
 
 
2235
    def _make_reference_clone_function(format, a_branch):
 
2236
        """Create a clone() routine for a branch dynamically."""
 
2237
        def clone(to_bzrdir, revision_id=None,
 
2238
            repository_policy=None):
 
2239
            """See Branch.clone()."""
 
2240
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
2241
            # cannot obey revision_id limits when cloning a reference ...
 
2242
            # FIXME RBC 20060210 either nuke revision_id for clone, or
 
2243
            # emit some sort of warning/error to the caller ?!
 
2244
        return clone
 
2245
 
 
2246
    def open(self, a_bzrdir, name=None, _found=False, location=None,
 
2247
             possible_transports=None, ignore_fallbacks=False,
 
2248
             found_repository=None):
 
2249
        """Return the branch that the branch reference in a_bzrdir points at.
 
2250
 
 
2251
        :param a_bzrdir: A BzrDir that contains a branch.
 
2252
        :param name: Name of colocated branch to open, if any
 
2253
        :param _found: a private parameter, do not use it. It is used to
 
2254
            indicate if format probing has already be done.
 
2255
        :param ignore_fallbacks: when set, no fallback branches will be opened
 
2256
            (if there are any).  Default is to open fallbacks.
 
2257
        :param location: The location of the referenced branch.  If
 
2258
            unspecified, this will be determined from the branch reference in
 
2259
            a_bzrdir.
 
2260
        :param possible_transports: An optional reusable transports list.
 
2261
        """
 
2262
        if name is None:
 
2263
            name = a_bzrdir._get_selected_branch()
 
2264
        if not _found:
 
2265
            format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
 
2266
            if format.__class__ != self.__class__:
 
2267
                raise AssertionError("wrong format %r found for %r" %
 
2268
                    (format, self))
 
2269
        if location is None:
 
2270
            location = self.get_reference(a_bzrdir, name)
 
2271
        real_bzrdir = controldir.ControlDir.open(
 
2272
            location, possible_transports=possible_transports)
 
2273
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks,
 
2274
            possible_transports=possible_transports)
 
2275
        # this changes the behaviour of result.clone to create a new reference
 
2276
        # rather than a copy of the content of the branch.
 
2277
        # I did not use a proxy object because that needs much more extensive
 
2278
        # testing, and we are only changing one behaviour at the moment.
 
2279
        # If we decide to alter more behaviours - i.e. the implicit nickname
 
2280
        # then this should be refactored to introduce a tested proxy branch
 
2281
        # and a subclass of that for use in overriding clone() and ....
 
2282
        # - RBC 20060210
 
2283
        result.clone = self._make_reference_clone_function(result)
 
2284
        return result
 
2285
 
 
2286
 
1852
2287
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
1853
2288
    """Branch format registry."""
1854
2289
 
1855
2290
    def __init__(self, other_registry=None):
1856
2291
        super(BranchFormatRegistry, self).__init__(other_registry)
1857
2292
        self._default_format = None
1858
 
        self._default_format_key = None
 
2293
 
 
2294
    def set_default(self, format):
 
2295
        self._default_format = format
1859
2296
 
1860
2297
    def get_default(self):
1861
 
        """Return the current default format."""
1862
 
        if (self._default_format_key is not None
1863
 
                and self._default_format is None):
1864
 
            self._default_format = self.get(self._default_format_key)
1865
2298
        return self._default_format
1866
2299
 
1867
 
    def set_default(self, format):
1868
 
        """Set the default format."""
1869
 
        self._default_format = format
1870
 
        self._default_format_key = None
1871
 
 
1872
 
    def set_default_key(self, format_string):
1873
 
        """Set the default format by its format string."""
1874
 
        self._default_format_key = format_string
1875
 
        self._default_format = None
1876
 
 
1877
2300
 
1878
2301
network_format_registry = registry.FormatRegistry()
1879
2302
"""Registry of formats indexed by their network name.
1888
2311
 
1889
2312
# formats which have no format string are not discoverable
1890
2313
# and not independently creatable, so are not registered.
1891
 
format_registry.register_lazy(
1892
 
    b"Bazaar-NG branch format 5\n", "breezy.bzr.fullhistory",
1893
 
    "BzrBranchFormat5")
1894
 
format_registry.register_lazy(
1895
 
    b"Bazaar Branch Format 6 (bzr 0.15)\n",
1896
 
    "breezy.bzr.branch", "BzrBranchFormat6")
1897
 
format_registry.register_lazy(
1898
 
    b"Bazaar Branch Format 7 (needs bzr 1.6)\n",
1899
 
    "breezy.bzr.branch", "BzrBranchFormat7")
1900
 
format_registry.register_lazy(
1901
 
    b"Bazaar Branch Format 8 (needs bzr 1.15)\n",
1902
 
    "breezy.bzr.branch", "BzrBranchFormat8")
1903
 
format_registry.register_lazy(
1904
 
    b"Bazaar-NG Branch Reference Format 1\n",
1905
 
    "breezy.bzr.branch", "BranchReferenceFormat")
1906
 
 
1907
 
format_registry.set_default_key(b"Bazaar Branch Format 7 (needs bzr 1.6)\n")
 
2314
__format6 = BzrBranchFormat6()
 
2315
__format7 = BzrBranchFormat7()
 
2316
__format8 = BzrBranchFormat8()
 
2317
format_registry.register_lazy(
 
2318
    "Bazaar-NG branch format 5\n", "brzlib.branchfmt.fullhistory", "BzrBranchFormat5")
 
2319
format_registry.register(BranchReferenceFormat())
 
2320
format_registry.register(__format6)
 
2321
format_registry.register(__format7)
 
2322
format_registry.register(__format8)
 
2323
format_registry.set_default(__format7)
1908
2324
 
1909
2325
 
1910
2326
class BranchWriteLockResult(LogicalLockResult):
1911
2327
    """The result of write locking a branch.
1912
2328
 
1913
 
    :ivar token: The token obtained from the underlying branch lock, or
 
2329
    :ivar branch_token: The token obtained from the underlying branch lock, or
1914
2330
        None.
1915
2331
    :ivar unlock: A callable which will unlock the lock.
1916
2332
    """
1917
2333
 
 
2334
    def __init__(self, unlock, branch_token):
 
2335
        LogicalLockResult.__init__(self, unlock)
 
2336
        self.branch_token = branch_token
 
2337
 
1918
2338
    def __repr__(self):
1919
 
        return "BranchWriteLockResult(%r, %r)" % (self.unlock, self.token)
 
2339
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
2340
            self.unlock)
 
2341
 
 
2342
 
 
2343
class BzrBranch(Branch, _RelockDebugMixin):
 
2344
    """A branch stored in the actual filesystem.
 
2345
 
 
2346
    Note that it's "local" in the context of the filesystem; it doesn't
 
2347
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
2348
    it's writable, and can be accessed via the normal filesystem API.
 
2349
 
 
2350
    :ivar _transport: Transport for file operations on this branch's
 
2351
        control files, typically pointing to the .bzr/branch directory.
 
2352
    :ivar repository: Repository for this branch.
 
2353
    :ivar base: The url of the base directory for this branch; the one
 
2354
        containing the .bzr directory.
 
2355
    :ivar name: Optional colocated branch name as it exists in the control
 
2356
        directory.
 
2357
    """
 
2358
 
 
2359
    def __init__(self, _format=None,
 
2360
                 _control_files=None, a_bzrdir=None, name=None,
 
2361
                 _repository=None, ignore_fallbacks=False,
 
2362
                 possible_transports=None):
 
2363
        """Create new branch object at a particular location."""
 
2364
        if a_bzrdir is None:
 
2365
            raise ValueError('a_bzrdir must be supplied')
 
2366
        if name is None:
 
2367
            raise ValueError('name must be supplied')
 
2368
        self.bzrdir = a_bzrdir
 
2369
        self._user_transport = self.bzrdir.transport.clone('..')
 
2370
        if name != "":
 
2371
            self._user_transport.set_segment_parameter(
 
2372
                "branch", urlutils.escape(name))
 
2373
        self._base = self._user_transport.base
 
2374
        self.name = name
 
2375
        self._format = _format
 
2376
        if _control_files is None:
 
2377
            raise ValueError('BzrBranch _control_files is None')
 
2378
        self.control_files = _control_files
 
2379
        self._transport = _control_files._transport
 
2380
        self.repository = _repository
 
2381
        self.conf_store = None
 
2382
        Branch.__init__(self, possible_transports)
 
2383
 
 
2384
    def __str__(self):
 
2385
        return '%s(%s)' % (self.__class__.__name__, self.user_url)
 
2386
 
 
2387
    __repr__ = __str__
 
2388
 
 
2389
    def _get_base(self):
 
2390
        """Returns the directory containing the control directory."""
 
2391
        return self._base
 
2392
 
 
2393
    base = property(_get_base, doc="The URL for the root of this branch.")
 
2394
 
 
2395
    @property
 
2396
    def user_transport(self):
 
2397
        return self._user_transport
 
2398
 
 
2399
    def _get_config(self):
 
2400
        return _mod_config.TransportConfig(self._transport, 'branch.conf')
 
2401
 
 
2402
    def _get_config_store(self):
 
2403
        if self.conf_store is None:
 
2404
            self.conf_store =  _mod_config.BranchStore(self)
 
2405
        return self.conf_store
 
2406
 
 
2407
    def _uncommitted_branch(self):
 
2408
        """Return the branch that may contain uncommitted changes."""
 
2409
        master = self.get_master_branch()
 
2410
        if master is not None:
 
2411
            return master
 
2412
        else:
 
2413
            return self
 
2414
 
 
2415
    def store_uncommitted(self, creator):
 
2416
        """Store uncommitted changes from a ShelfCreator.
 
2417
 
 
2418
        :param creator: The ShelfCreator containing uncommitted changes, or
 
2419
            None to delete any stored changes.
 
2420
        :raises: ChangesAlreadyStored if the branch already has changes.
 
2421
        """
 
2422
        branch = self._uncommitted_branch()
 
2423
        if creator is None:
 
2424
            branch._transport.delete('stored-transform')
 
2425
            return
 
2426
        if branch._transport.has('stored-transform'):
 
2427
            raise errors.ChangesAlreadyStored
 
2428
        transform = StringIO()
 
2429
        creator.write_shelf(transform)
 
2430
        transform.seek(0)
 
2431
        branch._transport.put_file('stored-transform', transform)
 
2432
 
 
2433
    def get_unshelver(self, tree):
 
2434
        """Return a shelf.Unshelver for this branch and tree.
 
2435
 
 
2436
        :param tree: The tree to use to construct the Unshelver.
 
2437
        :return: an Unshelver or None if no changes are stored.
 
2438
        """
 
2439
        branch = self._uncommitted_branch()
 
2440
        try:
 
2441
            transform = branch._transport.get('stored-transform')
 
2442
        except errors.NoSuchFile:
 
2443
            return None
 
2444
        return shelf.Unshelver.from_tree_and_shelf(tree, transform)
 
2445
 
 
2446
    def is_locked(self):
 
2447
        return self.control_files.is_locked()
 
2448
 
 
2449
    def lock_write(self, token=None):
 
2450
        """Lock the branch for write operations.
 
2451
 
 
2452
        :param token: A token to permit reacquiring a previously held and
 
2453
            preserved lock.
 
2454
        :return: A BranchWriteLockResult.
 
2455
        """
 
2456
        if not self.is_locked():
 
2457
            self._note_lock('w')
 
2458
            self.repository._warn_if_deprecated(self)
 
2459
            self.repository.lock_write()
 
2460
            took_lock = True
 
2461
        else:
 
2462
            took_lock = False
 
2463
        try:
 
2464
            return BranchWriteLockResult(self.unlock,
 
2465
                self.control_files.lock_write(token=token))
 
2466
        except:
 
2467
            if took_lock:
 
2468
                self.repository.unlock()
 
2469
            raise
 
2470
 
 
2471
    def lock_read(self):
 
2472
        """Lock the branch for read operations.
 
2473
 
 
2474
        :return: A brzlib.lock.LogicalLockResult.
 
2475
        """
 
2476
        if not self.is_locked():
 
2477
            self._note_lock('r')
 
2478
            self.repository._warn_if_deprecated(self)
 
2479
            self.repository.lock_read()
 
2480
            took_lock = True
 
2481
        else:
 
2482
            took_lock = False
 
2483
        try:
 
2484
            self.control_files.lock_read()
 
2485
            return LogicalLockResult(self.unlock)
 
2486
        except:
 
2487
            if took_lock:
 
2488
                self.repository.unlock()
 
2489
            raise
 
2490
 
 
2491
    @only_raises(errors.LockNotHeld, errors.LockBroken)
 
2492
    def unlock(self):
 
2493
        if self.control_files._lock_count == 1 and self.conf_store is not None:
 
2494
            self.conf_store.save_changes()
 
2495
        try:
 
2496
            self.control_files.unlock()
 
2497
        finally:
 
2498
            if not self.control_files.is_locked():
 
2499
                self.repository.unlock()
 
2500
                # we just released the lock
 
2501
                self._clear_cached_state()
 
2502
 
 
2503
    def peek_lock_mode(self):
 
2504
        if self.control_files._lock_count == 0:
 
2505
            return None
 
2506
        else:
 
2507
            return self.control_files._lock_mode
 
2508
 
 
2509
    def get_physical_lock_status(self):
 
2510
        return self.control_files.get_physical_lock_status()
 
2511
 
 
2512
    @needs_read_lock
 
2513
    def print_file(self, file, revision_id):
 
2514
        """See Branch.print_file."""
 
2515
        return self.repository.print_file(file, revision_id)
 
2516
 
 
2517
    @needs_write_lock
 
2518
    def set_last_revision_info(self, revno, revision_id):
 
2519
        if not revision_id or not isinstance(revision_id, basestring):
 
2520
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2521
        revision_id = _mod_revision.ensure_null(revision_id)
 
2522
        old_revno, old_revid = self.last_revision_info()
 
2523
        if self.get_append_revisions_only():
 
2524
            self._check_history_violation(revision_id)
 
2525
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2526
        self._write_last_revision_info(revno, revision_id)
 
2527
        self._clear_cached_state()
 
2528
        self._last_revision_info_cache = revno, revision_id
 
2529
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2530
 
 
2531
    def basis_tree(self):
 
2532
        """See Branch.basis_tree."""
 
2533
        return self.repository.revision_tree(self.last_revision())
 
2534
 
 
2535
    def _get_parent_location(self):
 
2536
        _locs = ['parent', 'pull', 'x-pull']
 
2537
        for l in _locs:
 
2538
            try:
 
2539
                return self._transport.get_bytes(l).strip('\n')
 
2540
            except errors.NoSuchFile:
 
2541
                pass
 
2542
        return None
 
2543
 
 
2544
    def get_stacked_on_url(self):
 
2545
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2546
 
 
2547
    def set_push_location(self, location):
 
2548
        """See Branch.set_push_location."""
 
2549
        self.get_config().set_user_option(
 
2550
            'push_location', location,
 
2551
            store=_mod_config.STORE_LOCATION_NORECURSE)
 
2552
 
 
2553
    def _set_parent_location(self, url):
 
2554
        if url is None:
 
2555
            self._transport.delete('parent')
 
2556
        else:
 
2557
            self._transport.put_bytes('parent', url + '\n',
 
2558
                mode=self.bzrdir._get_file_mode())
 
2559
 
 
2560
    @needs_write_lock
 
2561
    def unbind(self):
 
2562
        """If bound, unbind"""
 
2563
        return self.set_bound_location(None)
 
2564
 
 
2565
    @needs_write_lock
 
2566
    def bind(self, other):
 
2567
        """Bind this branch to the branch other.
 
2568
 
 
2569
        This does not push or pull data between the branches, though it does
 
2570
        check for divergence to raise an error when the branches are not
 
2571
        either the same, or one a prefix of the other. That behaviour may not
 
2572
        be useful, so that check may be removed in future.
 
2573
 
 
2574
        :param other: The branch to bind to
 
2575
        :type other: Branch
 
2576
        """
 
2577
        # TODO: jam 20051230 Consider checking if the target is bound
 
2578
        #       It is debatable whether you should be able to bind to
 
2579
        #       a branch which is itself bound.
 
2580
        #       Committing is obviously forbidden,
 
2581
        #       but binding itself may not be.
 
2582
        #       Since we *have* to check at commit time, we don't
 
2583
        #       *need* to check here
 
2584
 
 
2585
        # we want to raise diverged if:
 
2586
        # last_rev is not in the other_last_rev history, AND
 
2587
        # other_last_rev is not in our history, and do it without pulling
 
2588
        # history around
 
2589
        self.set_bound_location(other.base)
 
2590
 
 
2591
    def get_bound_location(self):
 
2592
        try:
 
2593
            return self._transport.get_bytes('bound')[:-1]
 
2594
        except errors.NoSuchFile:
 
2595
            return None
 
2596
 
 
2597
    @needs_read_lock
 
2598
    def get_master_branch(self, possible_transports=None):
 
2599
        """Return the branch we are bound to.
 
2600
 
 
2601
        :return: Either a Branch, or None
 
2602
        """
 
2603
        if self._master_branch_cache is None:
 
2604
            self._master_branch_cache = self._get_master_branch(
 
2605
                possible_transports)
 
2606
        return self._master_branch_cache
 
2607
 
 
2608
    def _get_master_branch(self, possible_transports):
 
2609
        bound_loc = self.get_bound_location()
 
2610
        if not bound_loc:
 
2611
            return None
 
2612
        try:
 
2613
            return Branch.open(bound_loc,
 
2614
                               possible_transports=possible_transports)
 
2615
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2616
            raise errors.BoundBranchConnectionFailure(
 
2617
                    self, bound_loc, e)
 
2618
 
 
2619
    @needs_write_lock
 
2620
    def set_bound_location(self, location):
 
2621
        """Set the target where this branch is bound to.
 
2622
 
 
2623
        :param location: URL to the target branch
 
2624
        """
 
2625
        self._master_branch_cache = None
 
2626
        if location:
 
2627
            self._transport.put_bytes('bound', location+'\n',
 
2628
                mode=self.bzrdir._get_file_mode())
 
2629
        else:
 
2630
            try:
 
2631
                self._transport.delete('bound')
 
2632
            except errors.NoSuchFile:
 
2633
                return False
 
2634
            return True
 
2635
 
 
2636
    @needs_write_lock
 
2637
    def update(self, possible_transports=None):
 
2638
        """Synchronise this branch with the master branch if any.
 
2639
 
 
2640
        :return: None or the last_revision that was pivoted out during the
 
2641
                 update.
 
2642
        """
 
2643
        master = self.get_master_branch(possible_transports)
 
2644
        if master is not None:
 
2645
            old_tip = _mod_revision.ensure_null(self.last_revision())
 
2646
            self.pull(master, overwrite=True)
 
2647
            if self.repository.get_graph().is_ancestor(old_tip,
 
2648
                _mod_revision.ensure_null(self.last_revision())):
 
2649
                return None
 
2650
            return old_tip
 
2651
        return None
 
2652
 
 
2653
    def _read_last_revision_info(self):
 
2654
        revision_string = self._transport.get_bytes('last-revision')
 
2655
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2656
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2657
        revno = int(revno)
 
2658
        return revno, revision_id
 
2659
 
 
2660
    def _write_last_revision_info(self, revno, revision_id):
 
2661
        """Simply write out the revision id, with no checks.
 
2662
 
 
2663
        Use set_last_revision_info to perform this safely.
 
2664
 
 
2665
        Does not update the revision_history cache.
 
2666
        """
 
2667
        revision_id = _mod_revision.ensure_null(revision_id)
 
2668
        out_string = '%d %s\n' % (revno, revision_id)
 
2669
        self._transport.put_bytes('last-revision', out_string,
 
2670
            mode=self.bzrdir._get_file_mode())
 
2671
 
 
2672
    @needs_write_lock
 
2673
    def update_feature_flags(self, updated_flags):
 
2674
        """Update the feature flags for this branch.
 
2675
 
 
2676
        :param updated_flags: Dictionary mapping feature names to necessities
 
2677
            A necessity can be None to indicate the feature should be removed
 
2678
        """
 
2679
        self._format._update_feature_flags(updated_flags)
 
2680
        self.control_transport.put_bytes('format', self._format.as_string())
 
2681
 
 
2682
 
 
2683
class BzrBranch8(BzrBranch):
 
2684
    """A branch that stores tree-reference locations."""
 
2685
 
 
2686
    def _open_hook(self, possible_transports=None):
 
2687
        if self._ignore_fallbacks:
 
2688
            return
 
2689
        if possible_transports is None:
 
2690
            possible_transports = [self.bzrdir.root_transport]
 
2691
        try:
 
2692
            url = self.get_stacked_on_url()
 
2693
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
 
2694
            errors.UnstackableBranchFormat):
 
2695
            pass
 
2696
        else:
 
2697
            for hook in Branch.hooks['transform_fallback_location']:
 
2698
                url = hook(self, url)
 
2699
                if url is None:
 
2700
                    hook_name = Branch.hooks.get_hook_name(hook)
 
2701
                    raise AssertionError(
 
2702
                        "'transform_fallback_location' hook %s returned "
 
2703
                        "None, not a URL." % hook_name)
 
2704
            self._activate_fallback_location(url,
 
2705
                possible_transports=possible_transports)
 
2706
 
 
2707
    def __init__(self, *args, **kwargs):
 
2708
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
 
2709
        super(BzrBranch8, self).__init__(*args, **kwargs)
 
2710
        self._last_revision_info_cache = None
 
2711
        self._reference_info = None
 
2712
 
 
2713
    def _clear_cached_state(self):
 
2714
        super(BzrBranch8, self)._clear_cached_state()
 
2715
        self._last_revision_info_cache = None
 
2716
        self._reference_info = None
 
2717
 
 
2718
    def _check_history_violation(self, revision_id):
 
2719
        current_revid = self.last_revision()
 
2720
        last_revision = _mod_revision.ensure_null(current_revid)
 
2721
        if _mod_revision.is_null(last_revision):
 
2722
            return
 
2723
        graph = self.repository.get_graph()
 
2724
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
 
2725
            if lh_ancestor == current_revid:
 
2726
                return
 
2727
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2728
 
 
2729
    def _gen_revision_history(self):
 
2730
        """Generate the revision history from last revision
 
2731
        """
 
2732
        last_revno, last_revision = self.last_revision_info()
 
2733
        self._extend_partial_history(stop_index=last_revno-1)
 
2734
        return list(reversed(self._partial_revision_history_cache))
 
2735
 
 
2736
    @needs_write_lock
 
2737
    def _set_parent_location(self, url):
 
2738
        """Set the parent branch"""
 
2739
        self._set_config_location('parent_location', url, make_relative=True)
 
2740
 
 
2741
    @needs_read_lock
 
2742
    def _get_parent_location(self):
 
2743
        """Set the parent branch"""
 
2744
        return self._get_config_location('parent_location')
 
2745
 
 
2746
    @needs_write_lock
 
2747
    def _set_all_reference_info(self, info_dict):
 
2748
        """Replace all reference info stored in a branch.
 
2749
 
 
2750
        :param info_dict: A dict of {file_id: (tree_path, branch_location)}
 
2751
        """
 
2752
        s = StringIO()
 
2753
        writer = rio.RioWriter(s)
 
2754
        for key, (tree_path, branch_location) in info_dict.iteritems():
 
2755
            stanza = rio.Stanza(file_id=key, tree_path=tree_path,
 
2756
                                branch_location=branch_location)
 
2757
            writer.write_stanza(stanza)
 
2758
        self._transport.put_bytes('references', s.getvalue())
 
2759
        self._reference_info = info_dict
 
2760
 
 
2761
    @needs_read_lock
 
2762
    def _get_all_reference_info(self):
 
2763
        """Return all the reference info stored in a branch.
 
2764
 
 
2765
        :return: A dict of {file_id: (tree_path, branch_location)}
 
2766
        """
 
2767
        if self._reference_info is not None:
 
2768
            return self._reference_info
 
2769
        rio_file = self._transport.get('references')
 
2770
        try:
 
2771
            stanzas = rio.read_stanzas(rio_file)
 
2772
            info_dict = dict((s['file_id'], (s['tree_path'],
 
2773
                             s['branch_location'])) for s in stanzas)
 
2774
        finally:
 
2775
            rio_file.close()
 
2776
        self._reference_info = info_dict
 
2777
        return info_dict
 
2778
 
 
2779
    def set_reference_info(self, file_id, tree_path, branch_location):
 
2780
        """Set the branch location to use for a tree reference.
 
2781
 
 
2782
        :param file_id: The file-id of the tree reference.
 
2783
        :param tree_path: The path of the tree reference in the tree.
 
2784
        :param branch_location: The location of the branch to retrieve tree
 
2785
            references from.
 
2786
        """
 
2787
        info_dict = self._get_all_reference_info()
 
2788
        info_dict[file_id] = (tree_path, branch_location)
 
2789
        if None in (tree_path, branch_location):
 
2790
            if tree_path is not None:
 
2791
                raise ValueError('tree_path must be None when branch_location'
 
2792
                                 ' is None.')
 
2793
            if branch_location is not None:
 
2794
                raise ValueError('branch_location must be None when tree_path'
 
2795
                                 ' is None.')
 
2796
            del info_dict[file_id]
 
2797
        self._set_all_reference_info(info_dict)
 
2798
 
 
2799
    def get_reference_info(self, file_id):
 
2800
        """Get the tree_path and branch_location for a tree reference.
 
2801
 
 
2802
        :return: a tuple of (tree_path, branch_location)
 
2803
        """
 
2804
        return self._get_all_reference_info().get(file_id, (None, None))
 
2805
 
 
2806
    def reference_parent(self, file_id, path, possible_transports=None):
 
2807
        """Return the parent branch for a tree-reference file_id.
 
2808
 
 
2809
        :param file_id: The file_id of the tree reference
 
2810
        :param path: The path of the file_id in the tree
 
2811
        :return: A branch associated with the file_id
 
2812
        """
 
2813
        branch_location = self.get_reference_info(file_id)[1]
 
2814
        if branch_location is None:
 
2815
            return Branch.reference_parent(self, file_id, path,
 
2816
                                           possible_transports)
 
2817
        branch_location = urlutils.join(self.user_url, branch_location)
 
2818
        return Branch.open(branch_location,
 
2819
                           possible_transports=possible_transports)
 
2820
 
 
2821
    def set_push_location(self, location):
 
2822
        """See Branch.set_push_location."""
 
2823
        self._set_config_location('push_location', location)
 
2824
 
 
2825
    def set_bound_location(self, location):
 
2826
        """See Branch.set_push_location."""
 
2827
        self._master_branch_cache = None
 
2828
        result = None
 
2829
        conf = self.get_config_stack()
 
2830
        if location is None:
 
2831
            if not conf.get('bound'):
 
2832
                return False
 
2833
            else:
 
2834
                conf.set('bound', 'False')
 
2835
                return True
 
2836
        else:
 
2837
            self._set_config_location('bound_location', location,
 
2838
                                      config=conf)
 
2839
            conf.set('bound', 'True')
 
2840
        return True
 
2841
 
 
2842
    def _get_bound_location(self, bound):
 
2843
        """Return the bound location in the config file.
 
2844
 
 
2845
        Return None if the bound parameter does not match"""
 
2846
        conf = self.get_config_stack()
 
2847
        if conf.get('bound') != bound:
 
2848
            return None
 
2849
        return self._get_config_location('bound_location', config=conf)
 
2850
 
 
2851
    def get_bound_location(self):
 
2852
        """See Branch.get_bound_location."""
 
2853
        return self._get_bound_location(True)
 
2854
 
 
2855
    def get_old_bound_location(self):
 
2856
        """See Branch.get_old_bound_location"""
 
2857
        return self._get_bound_location(False)
 
2858
 
 
2859
    def get_stacked_on_url(self):
 
2860
        # you can always ask for the URL; but you might not be able to use it
 
2861
        # if the repo can't support stacking.
 
2862
        ## self._check_stackable_repo()
 
2863
        # stacked_on_location is only ever defined in branch.conf, so don't
 
2864
        # waste effort reading the whole stack of config files.
 
2865
        conf = _mod_config.BranchOnlyStack(self)
 
2866
        stacked_url = self._get_config_location('stacked_on_location',
 
2867
                                                config=conf)
 
2868
        if stacked_url is None:
 
2869
            raise errors.NotStacked(self)
 
2870
        return stacked_url.encode('utf-8')
 
2871
 
 
2872
    @needs_read_lock
 
2873
    def get_rev_id(self, revno, history=None):
 
2874
        """Find the revision id of the specified revno."""
 
2875
        if revno == 0:
 
2876
            return _mod_revision.NULL_REVISION
 
2877
 
 
2878
        last_revno, last_revision_id = self.last_revision_info()
 
2879
        if revno <= 0 or revno > last_revno:
 
2880
            raise errors.NoSuchRevision(self, revno)
 
2881
 
 
2882
        if history is not None:
 
2883
            return history[revno - 1]
 
2884
 
 
2885
        index = last_revno - revno
 
2886
        if len(self._partial_revision_history_cache) <= index:
 
2887
            self._extend_partial_history(stop_index=index)
 
2888
        if len(self._partial_revision_history_cache) > index:
 
2889
            return self._partial_revision_history_cache[index]
 
2890
        else:
 
2891
            raise errors.NoSuchRevision(self, revno)
 
2892
 
 
2893
    @needs_read_lock
 
2894
    def revision_id_to_revno(self, revision_id):
 
2895
        """Given a revision id, return its revno"""
 
2896
        if _mod_revision.is_null(revision_id):
 
2897
            return 0
 
2898
        try:
 
2899
            index = self._partial_revision_history_cache.index(revision_id)
 
2900
        except ValueError:
 
2901
            try:
 
2902
                self._extend_partial_history(stop_revision=revision_id)
 
2903
            except errors.RevisionNotPresent, e:
 
2904
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
 
2905
            index = len(self._partial_revision_history_cache) - 1
 
2906
            if index < 0:
 
2907
                raise errors.NoSuchRevision(self, revision_id)
 
2908
            if self._partial_revision_history_cache[index] != revision_id:
 
2909
                raise errors.NoSuchRevision(self, revision_id)
 
2910
        return self.revno() - index
 
2911
 
 
2912
 
 
2913
class BzrBranch7(BzrBranch8):
 
2914
    """A branch with support for a fallback repository."""
 
2915
 
 
2916
    def set_reference_info(self, file_id, tree_path, branch_location):
 
2917
        Branch.set_reference_info(self, file_id, tree_path, branch_location)
 
2918
 
 
2919
    def get_reference_info(self, file_id):
 
2920
        Branch.get_reference_info(self, file_id)
 
2921
 
 
2922
    def reference_parent(self, file_id, path, possible_transports=None):
 
2923
        return Branch.reference_parent(self, file_id, path,
 
2924
                                       possible_transports)
 
2925
 
 
2926
 
 
2927
class BzrBranch6(BzrBranch7):
 
2928
    """See BzrBranchFormat6 for the capabilities of this branch.
 
2929
 
 
2930
    This subclass of BzrBranch7 disables the new features BzrBranch7 added,
 
2931
    i.e. stacking.
 
2932
    """
 
2933
 
 
2934
    def get_stacked_on_url(self):
 
2935
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
1920
2936
 
1921
2937
 
1922
2938
######################################################################
1993
3009
        tag_updates = getattr(self, "tag_updates", None)
1994
3010
        if not is_quiet():
1995
3011
            if self.old_revid != self.new_revid:
1996
 
                if self.new_revno is not None:
1997
 
                    note(gettext('Pushed up to revision %d.'),
1998
 
                         self.new_revno)
1999
 
                else:
2000
 
                    note(gettext('Pushed up to revision id %s.'),
2001
 
                         self.new_revid.decode('utf-8'))
 
3012
                note(gettext('Pushed up to revision %d.') % self.new_revno)
2002
3013
            if tag_updates:
2003
 
                note(ngettext('%d tag updated.', '%d tags updated.',
2004
 
                              len(tag_updates)) % len(tag_updates))
 
3014
                note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
2005
3015
            if self.old_revid == self.new_revid and not tag_updates:
2006
3016
                if not tag_conflicts:
2007
3017
                    note(gettext('No new revisions or tags to push.'))
2027
3037
            if any.
2028
3038
        """
2029
3039
        note(gettext('checked branch {0} format {1}').format(
2030
 
            self.branch.user_url, self.branch._format))
 
3040
                                self.branch.user_url, self.branch._format))
2031
3041
        for error in self.errors:
2032
3042
            note(gettext('found error:%s'), error)
2033
3043
 
2034
3044
 
 
3045
class Converter5to6(object):
 
3046
    """Perform an in-place upgrade of format 5 to format 6"""
 
3047
 
 
3048
    def convert(self, branch):
 
3049
        # Data for 5 and 6 can peacefully coexist.
 
3050
        format = BzrBranchFormat6()
 
3051
        new_branch = format.open(branch.bzrdir, _found=True)
 
3052
 
 
3053
        # Copy source data into target
 
3054
        new_branch._write_last_revision_info(*branch.last_revision_info())
 
3055
        new_branch.lock_write()
 
3056
        try:
 
3057
            new_branch.set_parent(branch.get_parent())
 
3058
            new_branch.set_bound_location(branch.get_bound_location())
 
3059
            new_branch.set_push_location(branch.get_push_location())
 
3060
        finally:
 
3061
            new_branch.unlock()
 
3062
 
 
3063
        # New branch has no tags by default
 
3064
        new_branch.tags._set_tag_dict({})
 
3065
 
 
3066
        # Copying done; now update target format
 
3067
        new_branch._transport.put_bytes('format',
 
3068
            format.as_string(),
 
3069
            mode=new_branch.bzrdir._get_file_mode())
 
3070
 
 
3071
        # Clean up old files
 
3072
        new_branch._transport.delete('revision-history')
 
3073
        branch.lock_write()
 
3074
        try:
 
3075
            try:
 
3076
                branch.set_parent(None)
 
3077
            except errors.NoSuchFile:
 
3078
                pass
 
3079
            branch.set_bound_location(None)
 
3080
        finally:
 
3081
            branch.unlock()
 
3082
 
 
3083
 
 
3084
class Converter6to7(object):
 
3085
    """Perform an in-place upgrade of format 6 to format 7"""
 
3086
 
 
3087
    def convert(self, branch):
 
3088
        format = BzrBranchFormat7()
 
3089
        branch._set_config_location('stacked_on_location', '')
 
3090
        # update target format
 
3091
        branch._transport.put_bytes('format', format.as_string())
 
3092
 
 
3093
 
 
3094
class Converter7to8(object):
 
3095
    """Perform an in-place upgrade of format 7 to format 8"""
 
3096
 
 
3097
    def convert(self, branch):
 
3098
        format = BzrBranchFormat8()
 
3099
        branch._transport.put_bytes('references', '')
 
3100
        # update target format
 
3101
        branch._transport.put_bytes('format', format.as_string())
 
3102
 
 
3103
 
2035
3104
class InterBranch(InterObject):
2036
3105
    """This class represents operations taking place between two branches.
2037
3106
 
2046
3115
    @classmethod
2047
3116
    def _get_branch_formats_to_test(klass):
2048
3117
        """Return an iterable of format tuples for testing.
2049
 
 
 
3118
        
2050
3119
        :return: An iterable of (from_format, to_format) to use when testing
2051
3120
            this InterBranch class. Each InterBranch class should define this
2052
3121
            method itself.
2053
3122
        """
2054
3123
        raise NotImplementedError(klass._get_branch_formats_to_test)
2055
3124
 
 
3125
    @needs_write_lock
2056
3126
    def pull(self, overwrite=False, stop_revision=None,
2057
3127
             possible_transports=None, local=False):
2058
3128
        """Mirror source into target branch.
2063
3133
        """
2064
3134
        raise NotImplementedError(self.pull)
2065
3135
 
 
3136
    @needs_write_lock
2066
3137
    def push(self, overwrite=False, stop_revision=None, lossy=False,
2067
3138
             _override_hook_source_branch=None):
2068
3139
        """Mirror the source branch into the target branch.
2071
3142
        """
2072
3143
        raise NotImplementedError(self.push)
2073
3144
 
 
3145
    @needs_write_lock
2074
3146
    def copy_content_into(self, revision_id=None):
2075
3147
        """Copy the content of source into target
2076
3148
 
2079
3151
        """
2080
3152
        raise NotImplementedError(self.copy_content_into)
2081
3153
 
2082
 
    def fetch(self, stop_revision=None, limit=None, lossy=False):
 
3154
    @needs_write_lock
 
3155
    def fetch(self, stop_revision=None, limit=None):
2083
3156
        """Fetch revisions.
2084
3157
 
2085
3158
        :param stop_revision: Last revision to fetch
2086
3159
        :param limit: Optional rough limit of revisions to fetch
2087
 
        :return: FetchResult object
2088
3160
        """
2089
3161
        raise NotImplementedError(self.fetch)
2090
3162
 
2091
 
    def update_references(self):
2092
 
        """Import reference information from source to target.
2093
 
        """
2094
 
        raise NotImplementedError(self.update_references)
2095
 
 
2096
3163
 
2097
3164
def _fix_overwrite_type(overwrite):
2098
3165
    if isinstance(overwrite, bool):
2122
3189
            return format._custom_format
2123
3190
        return format
2124
3191
 
 
3192
    @needs_write_lock
2125
3193
    def copy_content_into(self, revision_id=None):
2126
3194
        """Copy the content of source into target
2127
3195
 
2128
3196
        revision_id: if not None, the revision history in the new branch will
2129
3197
                     be truncated to end with revision_id.
2130
3198
        """
2131
 
        with self.source.lock_read(), self.target.lock_write():
2132
 
            self.source._synchronize_history(self.target, revision_id)
2133
 
            self.update_references()
2134
 
            try:
2135
 
                parent = self.source.get_parent()
2136
 
            except errors.InaccessibleParent as e:
2137
 
                mutter('parent was not accessible to copy: %s', str(e))
2138
 
            else:
2139
 
                if parent:
2140
 
                    self.target.set_parent(parent)
2141
 
            if self.source._push_should_merge_tags():
2142
 
                self.source.tags.merge_to(self.target.tags)
 
3199
        self.source.update_references(self.target)
 
3200
        self.source._synchronize_history(self.target, revision_id)
 
3201
        try:
 
3202
            parent = self.source.get_parent()
 
3203
        except errors.InaccessibleParent, e:
 
3204
            mutter('parent was not accessible to copy: %s', e)
 
3205
        else:
 
3206
            if parent:
 
3207
                self.target.set_parent(parent)
 
3208
        if self.source._push_should_merge_tags():
 
3209
            self.source.tags.merge_to(self.target.tags)
2143
3210
 
2144
 
    def fetch(self, stop_revision=None, limit=None, lossy=False):
 
3211
    @needs_write_lock
 
3212
    def fetch(self, stop_revision=None, limit=None):
2145
3213
        if self.target.base == self.source.base:
2146
3214
            return (0, [])
2147
 
        with self.source.lock_read(), self.target.lock_write():
 
3215
        self.source.lock_read()
 
3216
        try:
2148
3217
            fetch_spec_factory = fetch.FetchSpecFactory()
2149
3218
            fetch_spec_factory.source_branch = self.source
2150
3219
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
2151
3220
            fetch_spec_factory.source_repo = self.source.repository
2152
3221
            fetch_spec_factory.target_repo = self.target.repository
2153
 
            fetch_spec_factory.target_repo_kind = (
2154
 
                fetch.TargetRepoKinds.PREEXISTING)
 
3222
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
2155
3223
            fetch_spec_factory.limit = limit
2156
3224
            fetch_spec = fetch_spec_factory.make_fetch_spec()
2157
 
            return self.target.repository.fetch(
2158
 
                self.source.repository,
2159
 
                lossy=lossy,
 
3225
            return self.target.repository.fetch(self.source.repository,
2160
3226
                fetch_spec=fetch_spec)
 
3227
        finally:
 
3228
            self.source.unlock()
2161
3229
 
 
3230
    @needs_write_lock
2162
3231
    def _update_revisions(self, stop_revision=None, overwrite=False,
2163
 
                          graph=None):
2164
 
        with self.source.lock_read(), self.target.lock_write():
2165
 
            other_revno, other_last_revision = self.source.last_revision_info()
2166
 
            stop_revno = None  # unknown
2167
 
            if stop_revision is None:
2168
 
                stop_revision = other_last_revision
2169
 
                if _mod_revision.is_null(stop_revision):
2170
 
                    # if there are no commits, we're done.
2171
 
                    return
2172
 
                stop_revno = other_revno
 
3232
            graph=None):
 
3233
        other_revno, other_last_revision = self.source.last_revision_info()
 
3234
        stop_revno = None # unknown
 
3235
        if stop_revision is None:
 
3236
            stop_revision = other_last_revision
 
3237
            if _mod_revision.is_null(stop_revision):
 
3238
                # if there are no commits, we're done.
 
3239
                return
 
3240
            stop_revno = other_revno
2173
3241
 
2174
 
            # what's the current last revision, before we fetch [and change it
2175
 
            # possibly]
2176
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
2177
 
            # we fetch here so that we don't process data twice in the common
2178
 
            # case of having something to pull, and so that the check for
2179
 
            # already merged can operate on the just fetched graph, which will
2180
 
            # be cached in memory.
2181
 
            self.fetch(stop_revision=stop_revision)
2182
 
            # Check to see if one is an ancestor of the other
2183
 
            if not overwrite:
2184
 
                if graph is None:
2185
 
                    graph = self.target.repository.get_graph()
2186
 
                if self.target._check_if_descendant_or_diverged(
2187
 
                        stop_revision, last_rev, graph, self.source):
2188
 
                    # stop_revision is a descendant of last_rev, but we aren't
2189
 
                    # overwriting, so we're done.
2190
 
                    return
2191
 
            if stop_revno is None:
2192
 
                if graph is None:
2193
 
                    graph = self.target.repository.get_graph()
2194
 
                this_revno, this_last_revision = \
 
3242
        # what's the current last revision, before we fetch [and change it
 
3243
        # possibly]
 
3244
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3245
        # we fetch here so that we don't process data twice in the common
 
3246
        # case of having something to pull, and so that the check for
 
3247
        # already merged can operate on the just fetched graph, which will
 
3248
        # be cached in memory.
 
3249
        self.fetch(stop_revision=stop_revision)
 
3250
        # Check to see if one is an ancestor of the other
 
3251
        if not overwrite:
 
3252
            if graph is None:
 
3253
                graph = self.target.repository.get_graph()
 
3254
            if self.target._check_if_descendant_or_diverged(
 
3255
                    stop_revision, last_rev, graph, self.source):
 
3256
                # stop_revision is a descendant of last_rev, but we aren't
 
3257
                # overwriting, so we're done.
 
3258
                return
 
3259
        if stop_revno is None:
 
3260
            if graph is None:
 
3261
                graph = self.target.repository.get_graph()
 
3262
            this_revno, this_last_revision = \
2195
3263
                    self.target.last_revision_info()
2196
 
                stop_revno = graph.find_distance_to_null(
2197
 
                    stop_revision, [(other_last_revision, other_revno),
2198
 
                                    (this_last_revision, this_revno)])
2199
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
3264
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3265
                            [(other_last_revision, other_revno),
 
3266
                             (this_last_revision, this_revno)])
 
3267
        self.target.set_last_revision_info(stop_revno, stop_revision)
2200
3268
 
 
3269
    @needs_write_lock
2201
3270
    def pull(self, overwrite=False, stop_revision=None,
2202
3271
             possible_transports=None, run_hooks=True,
2203
3272
             _override_hook_target=None, local=False):
2207
3276
            is being called because it's the master of the primary branch,
2208
3277
            so it should not run its hooks.
2209
3278
        """
2210
 
        with contextlib.ExitStack() as exit_stack:
2211
 
            exit_stack.enter_context(self.target.lock_write())
2212
 
            bound_location = self.target.get_bound_location()
2213
 
            if local and not bound_location:
2214
 
                raise errors.LocalRequiresBoundBranch()
2215
 
            master_branch = None
2216
 
            source_is_master = False
2217
 
            if bound_location:
2218
 
                # bound_location comes from a config file, some care has to be
2219
 
                # taken to relate it to source.user_url
2220
 
                normalized = urlutils.normalize_url(bound_location)
2221
 
                try:
2222
 
                    relpath = self.source.user_transport.relpath(normalized)
2223
 
                    source_is_master = (relpath == '')
2224
 
                except (errors.PathNotChild, urlutils.InvalidURL):
2225
 
                    source_is_master = False
2226
 
            if not local and bound_location and not source_is_master:
2227
 
                # not pulling from master, so we need to update master.
2228
 
                master_branch = self.target.get_master_branch(
2229
 
                    possible_transports)
2230
 
                exit_stack.enter_context(master_branch.lock_write())
 
3279
        bound_location = self.target.get_bound_location()
 
3280
        if local and not bound_location:
 
3281
            raise errors.LocalRequiresBoundBranch()
 
3282
        master_branch = None
 
3283
        source_is_master = False
 
3284
        if bound_location:
 
3285
            # bound_location comes from a config file, some care has to be
 
3286
            # taken to relate it to source.user_url
 
3287
            normalized = urlutils.normalize_url(bound_location)
 
3288
            try:
 
3289
                relpath = self.source.user_transport.relpath(normalized)
 
3290
                source_is_master = (relpath == '')
 
3291
            except (errors.PathNotChild, errors.InvalidURL):
 
3292
                source_is_master = False
 
3293
        if not local and bound_location and not source_is_master:
 
3294
            # not pulling from master, so we need to update master.
 
3295
            master_branch = self.target.get_master_branch(possible_transports)
 
3296
            master_branch.lock_write()
 
3297
        try:
2231
3298
            if master_branch:
2232
3299
                # pull from source into master.
2233
 
                master_branch.pull(
2234
 
                    self.source, overwrite, stop_revision, run_hooks=False)
2235
 
            return self._pull(
2236
 
                overwrite, stop_revision, _hook_master=master_branch,
 
3300
                master_branch.pull(self.source, overwrite, stop_revision,
 
3301
                    run_hooks=False)
 
3302
            return self._pull(overwrite,
 
3303
                stop_revision, _hook_master=master_branch,
2237
3304
                run_hooks=run_hooks,
2238
3305
                _override_hook_target=_override_hook_target,
2239
3306
                merge_tags_to_master=not source_is_master)
 
3307
        finally:
 
3308
            if master_branch:
 
3309
                master_branch.unlock()
2240
3310
 
2241
3311
    def push(self, overwrite=False, stop_revision=None, lossy=False,
2242
3312
             _override_hook_source_branch=None):
2254
3324
        # TODO: Public option to disable running hooks - should be trivial but
2255
3325
        # needs tests.
2256
3326
 
2257
 
        def _run_hooks():
2258
 
            if _override_hook_source_branch:
2259
 
                result.source_branch = _override_hook_source_branch
2260
 
            for hook in Branch.hooks['post_push']:
2261
 
                hook(result)
2262
 
 
2263
 
        with self.source.lock_read(), self.target.lock_write():
2264
 
            bound_location = self.target.get_bound_location()
2265
 
            if bound_location and self.target.base != bound_location:
2266
 
                # there is a master branch.
2267
 
                #
2268
 
                # XXX: Why the second check?  Is it even supported for a branch
2269
 
                # to be bound to itself? -- mbp 20070507
2270
 
                master_branch = self.target.get_master_branch()
2271
 
                with master_branch.lock_write():
2272
 
                    # push into the master from the source branch.
2273
 
                    master_inter = InterBranch.get(self.source, master_branch)
2274
 
                    master_inter._basic_push(overwrite, stop_revision)
2275
 
                    # and push into the target branch from the source. Note
2276
 
                    # that we push from the source branch again, because it's
2277
 
                    # considered the highest bandwidth repository.
2278
 
                    result = self._basic_push(overwrite, stop_revision)
2279
 
                    result.master_branch = master_branch
2280
 
                    result.local_branch = self.target
2281
 
                    _run_hooks()
2282
 
            else:
2283
 
                master_branch = None
2284
 
                # no master branch
2285
 
                result = self._basic_push(overwrite, stop_revision)
2286
 
                # TODO: Why set master_branch and local_branch if there's no
2287
 
                # binding?  Maybe cleaner to just leave them unset? -- mbp
2288
 
                # 20070504
2289
 
                result.master_branch = self.target
2290
 
                result.local_branch = None
2291
 
                _run_hooks()
2292
 
            return result
 
3327
        op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
 
3328
        op.add_cleanup(self.source.lock_read().unlock)
 
3329
        op.add_cleanup(self.target.lock_write().unlock)
 
3330
        return op.run(overwrite, stop_revision,
 
3331
            _override_hook_source_branch=_override_hook_source_branch)
2293
3332
 
2294
3333
    def _basic_push(self, overwrite, stop_revision):
2295
3334
        """Basic implementation of push without bound branches or hooks.
2300
3339
        result.source_branch = self.source
2301
3340
        result.target_branch = self.target
2302
3341
        result.old_revno, result.old_revid = self.target.last_revision_info()
 
3342
        self.source.update_references(self.target)
2303
3343
        overwrite = _fix_overwrite_type(overwrite)
2304
3344
        if result.old_revid != stop_revision:
2305
3345
            # We assume that during 'push' this repository is closer than
2306
3346
            # the target.
2307
3347
            graph = self.source.repository.get_graph(self.target.repository)
2308
 
            self._update_revisions(
2309
 
                stop_revision, overwrite=("history" in overwrite), graph=graph)
 
3348
            self._update_revisions(stop_revision,
 
3349
                overwrite=("history" in overwrite),
 
3350
                graph=graph)
2310
3351
        if self.source._push_should_merge_tags():
2311
3352
            result.tag_updates, result.tag_conflicts = (
2312
3353
                self.source.tags.merge_to(
2313
 
                    self.target.tags, "tags" in overwrite))
2314
 
        self.update_references()
 
3354
                self.target.tags, "tags" in overwrite))
2315
3355
        result.new_revno, result.new_revid = self.target.last_revision_info()
2316
3356
        return result
2317
3357
 
 
3358
    def _push_with_bound_branches(self, operation, overwrite, stop_revision,
 
3359
            _override_hook_source_branch=None):
 
3360
        """Push from source into target, and into target's master if any.
 
3361
        """
 
3362
        def _run_hooks():
 
3363
            if _override_hook_source_branch:
 
3364
                result.source_branch = _override_hook_source_branch
 
3365
            for hook in Branch.hooks['post_push']:
 
3366
                hook(result)
 
3367
 
 
3368
        bound_location = self.target.get_bound_location()
 
3369
        if bound_location and self.target.base != bound_location:
 
3370
            # there is a master branch.
 
3371
            #
 
3372
            # XXX: Why the second check?  Is it even supported for a branch to
 
3373
            # be bound to itself? -- mbp 20070507
 
3374
            master_branch = self.target.get_master_branch()
 
3375
            master_branch.lock_write()
 
3376
            operation.add_cleanup(master_branch.unlock)
 
3377
            # push into the master from the source branch.
 
3378
            master_inter = InterBranch.get(self.source, master_branch)
 
3379
            master_inter._basic_push(overwrite, stop_revision)
 
3380
            # and push into the target branch from the source. Note that
 
3381
            # we push from the source branch again, because it's considered
 
3382
            # the highest bandwidth repository.
 
3383
            result = self._basic_push(overwrite, stop_revision)
 
3384
            result.master_branch = master_branch
 
3385
            result.local_branch = self.target
 
3386
        else:
 
3387
            master_branch = None
 
3388
            # no master branch
 
3389
            result = self._basic_push(overwrite, stop_revision)
 
3390
            # TODO: Why set master_branch and local_branch if there's no
 
3391
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
3392
            # 20070504
 
3393
            result.master_branch = self.target
 
3394
            result.local_branch = None
 
3395
        _run_hooks()
 
3396
        return result
 
3397
 
2318
3398
    def _pull(self, overwrite=False, stop_revision=None,
2319
 
              possible_transports=None, _hook_master=None, run_hooks=True,
2320
 
              _override_hook_target=None, local=False,
2321
 
              merge_tags_to_master=True):
 
3399
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3400
             _override_hook_target=None, local=False,
 
3401
             merge_tags_to_master=True):
2322
3402
        """See Branch.pull.
2323
3403
 
2324
3404
        This function is the core worker, used by GenericInterBranch.pull to
2344
3424
            result.target_branch = self.target
2345
3425
        else:
2346
3426
            result.target_branch = _override_hook_target
2347
 
        with self.source.lock_read():
 
3427
        self.source.lock_read()
 
3428
        try:
2348
3429
            # We assume that during 'pull' the target repository is closer than
2349
3430
            # the source one.
 
3431
            self.source.update_references(self.target)
2350
3432
            graph = self.target.repository.get_graph(self.source.repository)
2351
 
            # TODO: Branch formats should have a flag that indicates
 
3433
            # TODO: Branch formats should have a flag that indicates 
2352
3434
            # that revno's are expensive, and pull() should honor that flag.
2353
3435
            # -- JRV20090506
2354
3436
            result.old_revno, result.old_revid = \
2355
3437
                self.target.last_revision_info()
2356
3438
            overwrite = _fix_overwrite_type(overwrite)
2357
 
            self._update_revisions(
2358
 
                stop_revision, overwrite=("history" in overwrite), graph=graph)
2359
 
            # TODO: The old revid should be specified when merging tags,
2360
 
            # so a tags implementation that versions tags can only
 
3439
            self._update_revisions(stop_revision,
 
3440
                overwrite=("history" in overwrite),
 
3441
                graph=graph)
 
3442
            # TODO: The old revid should be specified when merging tags, 
 
3443
            # so a tags implementation that versions tags can only 
2361
3444
            # pull in the most recent changes. -- JRV20090506
2362
3445
            result.tag_updates, result.tag_conflicts = (
2363
 
                self.source.tags.merge_to(
2364
 
                    self.target.tags, "tags" in overwrite,
 
3446
                self.source.tags.merge_to(self.target.tags,
 
3447
                    "tags" in overwrite,
2365
3448
                    ignore_master=not merge_tags_to_master))
2366
 
            self.update_references()
2367
 
            result.new_revno, result.new_revid = (
2368
 
                self.target.last_revision_info())
 
3449
            result.new_revno, result.new_revid = self.target.last_revision_info()
2369
3450
            if _hook_master:
2370
3451
                result.master_branch = _hook_master
2371
3452
                result.local_branch = result.target_branch
2375
3456
            if run_hooks:
2376
3457
                for hook in Branch.hooks['post_pull']:
2377
3458
                    hook(result)
2378
 
            return result
2379
 
 
2380
 
    def update_references(self):
2381
 
        if not getattr(self.source._format, 'supports_reference_locations', False):
2382
 
            return
2383
 
        reference_dict = self.source._get_all_reference_info()
2384
 
        if len(reference_dict) == 0:
2385
 
            return
2386
 
        old_base = self.source.base
2387
 
        new_base = self.target.base
2388
 
        target_reference_dict = self.target._get_all_reference_info()
2389
 
        for tree_path, (branch_location, file_id) in reference_dict.items():
2390
 
            try:
2391
 
                branch_location = urlutils.rebase_url(branch_location,
2392
 
                                                      old_base, new_base)
2393
 
            except urlutils.InvalidRebaseURLs:
2394
 
                # Fall back to absolute URL
2395
 
                branch_location = urlutils.join(old_base, branch_location)
2396
 
            target_reference_dict.setdefault(
2397
 
                tree_path, (branch_location, file_id))
2398
 
        self.target._set_all_reference_info(target_reference_dict)
 
3459
        finally:
 
3460
            self.source.unlock()
 
3461
        return result
2399
3462
 
2400
3463
 
2401
3464
InterBranch.register_optimiser(GenericInterBranch)