/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 breezy/branch.py

  • Committer: Breezy landing bot
  • Author(s): Colin Watson
  • Date: 2020-11-16 21:47:08 UTC
  • mfrom: (7521.1.1 remove-lp-workaround)
  • Revision ID: breezy.the.bot@gmail.com-20201116214708-jos209mgxi41oy15
Remove breezy.git workaround for bazaar.launchpad.net.

Merged from https://code.launchpad.net/~cjwatson/brz/remove-lp-workaround/+merge/393710

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 __future__ import absolute_import
18
 
 
19
 
import bzrlib.bzrdir
20
 
 
21
 
from cStringIO import StringIO
22
 
 
23
 
from bzrlib.lazy_import import lazy_import
 
17
from .lazy_import import lazy_import
24
18
lazy_import(globals(), """
 
19
import contextlib
25
20
import itertools
26
 
from bzrlib import (
27
 
    bzrdir,
28
 
    controldir,
29
 
    cache_utf8,
30
 
    cleanup,
 
21
from breezy import (
31
22
    config as _mod_config,
32
23
    debug,
33
 
    errors,
34
 
    fetch,
35
 
    graph as _mod_graph,
36
 
    lockdir,
37
 
    lockable_files,
38
 
    remote,
 
24
    memorytree,
39
25
    repository,
40
26
    revision as _mod_revision,
41
 
    rio,
42
 
    shelf,
43
27
    tag as _mod_tag,
44
28
    transport,
45
29
    ui,
46
30
    urlutils,
 
31
    )
 
32
from breezy.bzr import (
 
33
    fetch,
 
34
    remote,
47
35
    vf_search,
48
36
    )
49
 
from bzrlib.i18n import gettext, ngettext
 
37
from breezy.i18n import gettext, ngettext
50
38
""")
51
39
 
52
 
# Explicitly import bzrlib.bzrdir so that the BzrProber
53
 
# is guaranteed to be registered.
54
 
import bzrlib.bzrdir
55
 
 
56
 
from bzrlib import (
57
 
    bzrdir,
 
40
from . import (
58
41
    controldir,
59
 
    )
60
 
from bzrlib.decorators import (
61
 
    needs_read_lock,
62
 
    needs_write_lock,
63
 
    only_raises,
64
 
    )
65
 
from bzrlib.hooks import Hooks
66
 
from bzrlib.inter import InterObject
67
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
68
 
from bzrlib import registry
69
 
from bzrlib.symbol_versioning import (
70
 
    deprecated_in,
71
 
    deprecated_method,
72
 
    )
73
 
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
 
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
74
60
 
75
61
 
76
62
class Branch(controldir.ControlComponent):
93
79
 
94
80
    @property
95
81
    def user_transport(self):
96
 
        return self.bzrdir.user_transport
 
82
        return self.controldir.user_transport
97
83
 
98
84
    def __init__(self, possible_transports=None):
99
85
        self.tags = self._format.make_tags(self)
101
87
        self._revision_id_to_revno_cache = None
102
88
        self._partial_revision_id_to_revno_cache = {}
103
89
        self._partial_revision_history_cache = []
104
 
        self._tags_bytes = None
105
90
        self._last_revision_info_cache = None
106
91
        self._master_branch_cache = None
107
92
        self._merge_sorted_revisions_cache = None
118
103
        for existing_fallback_repo in self.repository._fallback_repositories:
119
104
            if existing_fallback_repo.user_url == url:
120
105
                # This fallback is already configured.  This probably only
121
 
                # happens because ControlDir.sprout is a horrible mess.  To avoid
122
 
                # confusing _unstack we don't add this a second time.
 
106
                # happens because ControlDir.sprout is a horrible mess.  To
 
107
                # avoid confusing _unstack we don't add this a second time.
123
108
                mutter('duplicate activation of fallback %r on %r', url, self)
124
109
                return
125
110
        repo = self._get_fallback_repository(url, possible_transports)
143
128
 
144
129
    def _check_stackable_repo(self):
145
130
        if not self.repository._format.supports_external_lookups:
146
 
            raise errors.UnstackableRepositoryFormat(self.repository._format,
147
 
                self.repository.base)
 
131
            raise errors.UnstackableRepositoryFormat(
 
132
                self.repository._format, self.repository.base)
148
133
 
149
134
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
150
135
        """Extend the partial history to include a given index
164
149
        repository._iter_for_revno(
165
150
            self.repository, self._partial_revision_history_cache,
166
151
            stop_index=stop_index, stop_revision=stop_revision)
167
 
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
 
152
        if self._partial_revision_history_cache[-1] == \
 
153
                _mod_revision.NULL_REVISION:
168
154
            self._partial_revision_history_cache.pop()
169
155
 
170
156
    def _get_check_refs(self):
171
157
        """Get the references needed for check().
172
158
 
173
 
        See bzrlib.check.
 
159
        See breezy.check.
174
160
        """
175
161
        revid = self.last_revision()
176
162
        return [('revision-existence', revid), ('lefthand-distance', revid)]
182
168
        For instance, if the branch is at URL/.bzr/branch,
183
169
        Branch.open(URL) -> a Branch instance.
184
170
        """
185
 
        control = controldir.ControlDir.open(base,
186
 
            possible_transports=possible_transports, _unsupported=_unsupported)
187
 
        return control.open_branch(unsupported=_unsupported,
 
171
        control = controldir.ControlDir.open(
 
172
            base, possible_transports=possible_transports,
 
173
            _unsupported=_unsupported)
 
174
        return control.open_branch(
 
175
            unsupported=_unsupported,
188
176
            possible_transports=possible_transports)
189
177
 
190
178
    @staticmethod
191
179
    def open_from_transport(transport, name=None, _unsupported=False,
192
 
            possible_transports=None):
 
180
                            possible_transports=None):
193
181
        """Open the branch rooted at transport"""
194
 
        control = controldir.ControlDir.open_from_transport(transport, _unsupported)
195
 
        return control.open_branch(name=name, unsupported=_unsupported,
 
182
        control = controldir.ControlDir.open_from_transport(
 
183
            transport, _unsupported)
 
184
        return control.open_branch(
 
185
            name=name, unsupported=_unsupported,
196
186
            possible_transports=possible_transports)
197
187
 
198
188
    @staticmethod
203
193
 
204
194
        Basically we keep looking up until we find the control directory or
205
195
        run into the root.  If there isn't one, raises NotBranchError.
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.
 
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.
209
200
        """
210
 
        control, relpath = controldir.ControlDir.open_containing(url,
211
 
                                                         possible_transports)
 
201
        control, relpath = controldir.ControlDir.open_containing(
 
202
            url, possible_transports)
212
203
        branch = control.open_branch(possible_transports=possible_transports)
213
204
        return (branch, relpath)
214
205
 
221
212
        return self.supports_tags() and self.tags.get_tag_dict()
222
213
 
223
214
    def get_config(self):
224
 
        """Get a bzrlib.config.BranchConfig for this Branch.
 
215
        """Get a breezy.config.BranchConfig for this Branch.
225
216
 
226
217
        This can then be used to get and set configuration options for the
227
218
        branch.
228
219
 
229
 
        :return: A bzrlib.config.BranchConfig.
 
220
        :return: A breezy.config.BranchConfig.
230
221
        """
231
222
        return _mod_config.BranchConfig(self)
232
223
 
233
224
    def get_config_stack(self):
234
 
        """Get a bzrlib.config.BranchStack for this Branch.
 
225
        """Get a breezy.config.BranchStack for this Branch.
235
226
 
236
227
        This can then be used to get and set configuration options for the
237
228
        branch.
238
229
 
239
 
        :return: A bzrlib.config.BranchStack.
 
230
        :return: A breezy.config.BranchStack.
240
231
        """
241
232
        return _mod_config.BranchStack(self)
242
233
 
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
 
 
255
234
    def store_uncommitted(self, creator):
256
235
        """Store uncommitted changes from a ShelfCreator.
257
236
 
275
254
        a_branch = Branch.open(url, possible_transports=possible_transports)
276
255
        return a_branch.repository
277
256
 
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
 
 
295
257
    def _get_nick(self, local=False, possible_transports=None):
296
258
        config = self.get_config()
297
259
        # explicit overrides master, but don't look for master if local is True
303
265
                if master is not None:
304
266
                    # return the master branch value
305
267
                    return master.nick
306
 
            except errors.RecursiveBind, e:
 
268
            except errors.RecursiveBind as e:
307
269
                raise e
308
 
            except errors.BzrError, e:
 
270
            except errors.BzrError as e:
309
271
                # Silently fall back to local implicit nick if the master is
310
272
                # unavailable
311
273
                mutter("Could not connect to bound branch, "
312
 
                    "falling back to local nick.\n " + str(e))
 
274
                       "falling back to local nick.\n " + str(e))
313
275
        return config.get_nickname()
314
276
 
315
277
    def _set_nick(self, nick):
338
300
        new_history = []
339
301
        check_not_reserved_id = _mod_revision.check_not_reserved_id
340
302
        # Do not include ghosts or graph origin in revision_history
341
 
        while (current_rev_id in parents_map and
342
 
               len(parents_map[current_rev_id]) > 0):
 
303
        while (current_rev_id in parents_map
 
304
               and len(parents_map[current_rev_id]) > 0):
343
305
            check_not_reserved_id(current_rev_id)
344
306
            new_history.append(current_rev_id)
345
307
            current_rev_id = parents_map[current_rev_id][0]
359
321
    def lock_read(self):
360
322
        """Lock the branch for read operations.
361
323
 
362
 
        :return: A bzrlib.lock.LogicalLockResult.
 
324
        :return: A breezy.lock.LogicalLockResult.
363
325
        """
364
326
        raise NotImplementedError(self.lock_read)
365
327
 
373
335
    def get_physical_lock_status(self):
374
336
        raise NotImplementedError(self.get_physical_lock_status)
375
337
 
376
 
    @needs_read_lock
377
338
    def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
378
339
        """Return the revision_id for a dotted revno.
379
340
 
385
346
        :return: the revision_id
386
347
        :raises errors.NoSuchRevision: if the revno doesn't exist
387
348
        """
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
 
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
392
354
 
393
355
    def _do_dotted_revno_to_revision_id(self, revno):
394
356
        """Worker function for dotted_revno_to_revision_id.
397
359
        provide a more efficient implementation.
398
360
        """
399
361
        if len(revno) == 1:
400
 
            return self.get_rev_id(revno[0])
 
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)
401
366
        revision_id_to_revno = self.get_revision_id_to_revno_map()
402
367
        revision_ids = [revision_id for revision_id, this_revno
403
 
                        in revision_id_to_revno.iteritems()
 
368
                        in revision_id_to_revno.items()
404
369
                        if revno == this_revno]
405
370
        if len(revision_ids) == 1:
406
371
            return revision_ids[0]
408
373
            revno_str = '.'.join(map(str, revno))
409
374
            raise errors.NoSuchRevision(self, revno_str)
410
375
 
411
 
    @needs_read_lock
412
376
    def revision_id_to_dotted_revno(self, revision_id):
413
377
        """Given a revision id, return its dotted revno.
414
378
 
415
379
        :return: a tuple like (1,) or (400,1,3).
416
380
        """
417
 
        return self._do_revision_id_to_dotted_revno(revision_id)
 
381
        with self.lock_read():
 
382
            return self._do_revision_id_to_dotted_revno(revision_id)
418
383
 
419
384
    def _do_revision_id_to_dotted_revno(self, revision_id):
420
385
        """Worker function for revision_id_to_revno."""
437
402
                raise errors.NoSuchRevision(self, revision_id)
438
403
        return result
439
404
 
440
 
    @needs_read_lock
441
405
    def get_revision_id_to_revno_map(self):
442
406
        """Return the revision_id => dotted revno map.
443
407
 
446
410
        :return: A dictionary mapping revision_id => dotted revno.
447
411
            This dictionary should not be modified by the caller.
448
412
        """
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
 
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
459
427
 
460
428
    def _gen_revno_map(self):
461
429
        """Create a new mapping from revision ids to dotted revnos.
467
435
 
468
436
        :return: A dictionary mapping revision_id => dotted revno.
469
437
        """
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())
 
438
        revision_id_to_revno = {
 
439
            rev_id: revno for rev_id, depth, revno, end_of_merge
 
440
            in self.iter_merge_sorted_revisions()}
473
441
        return revision_id_to_revno
474
442
 
475
 
    @needs_read_lock
476
443
    def iter_merge_sorted_revisions(self, start_revision_id=None,
477
 
            stop_revision_id=None, stop_rule='exclude', direction='reverse'):
 
444
                                    stop_revision_id=None,
 
445
                                    stop_rule='exclude', direction='reverse'):
478
446
        """Walk the revisions for a branch in merge sorted order.
479
447
 
480
448
        Merge sorted order is the output from a merge-aware,
492
460
            * 'include' - the stop revision is the last item in the result
493
461
            * 'with-merges' - include the stop revision and all of its
494
462
              merged revisions in the result
495
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
 
463
            * 'with-merges-without-common-ancestry' - filter out revisions
496
464
              that are in both ancestries
497
465
        :param direction: either 'reverse' or 'forward':
498
466
 
517
485
            * end_of_merge: When True the next node (earlier in history) is
518
486
              part of a different merge.
519
487
        """
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)
 
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)
541
510
 
542
511
    def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
543
 
        start_revision_id, stop_revision_id, stop_rule):
 
512
                                       start_revision_id, stop_revision_id,
 
513
                                       stop_rule):
544
514
        """Iterate over an inclusive range of sorted revisions."""
545
515
        rev_iter = iter(merge_sorted_revisions)
546
516
        if start_revision_id is not None:
601
571
                if rev_id == left_parent:
602
572
                    # reached the left parent after the stop_revision
603
573
                    return
604
 
                if (not reached_stop_revision_id or
605
 
                        rev_id in revision_id_whitelist):
 
574
                if (not reached_stop_revision_id
 
575
                        or rev_id in revision_id_whitelist):
606
576
                    yield (rev_id, node.merge_depth, node.revno,
607
 
                       node.end_of_merge)
 
577
                           node.end_of_merge)
608
578
                    if reached_stop_revision_id or rev_id == stop_revision_id:
609
579
                        # only do the merged revs of rev_id from now on
610
580
                        rev = self.repository.get_revision(rev_id)
620
590
        # ancestry. Given the order guaranteed by the merge sort, we will see
621
591
        # uninteresting descendants of the first parent of our tip before the
622
592
        # tip itself.
623
 
        first = rev_iter.next()
 
593
        try:
 
594
            first = next(rev_iter)
 
595
        except StopIteration:
 
596
            return
624
597
        (rev_id, merge_depth, revno, end_of_merge) = first
625
598
        yield first
626
599
        if not merge_depth:
663
636
        """Tell this branch object not to release the physical lock when this
664
637
        object is unlocked.
665
638
 
666
 
        If lock_write doesn't return a token, then this method is not supported.
 
639
        If lock_write doesn't return a token, then this method is not
 
640
        supported.
667
641
        """
668
642
        self.control_files.leave_in_place()
669
643
 
671
645
        """Tell this branch object to release the physical lock when this
672
646
        object is unlocked, even if it didn't originally acquire it.
673
647
 
674
 
        If lock_write doesn't return a token, then this method is not supported.
 
648
        If lock_write doesn't return a token, then this method is not
 
649
        supported.
675
650
        """
676
651
        self.control_files.dont_leave_in_place()
677
652
 
695
670
            raise errors.UpgradeRequired(self.user_url)
696
671
        self.get_config_stack().set('append_revisions_only', enabled)
697
672
 
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):
 
673
    def fetch(self, from_branch, stop_revision=None, limit=None, lossy=False):
708
674
        """Copy revisions from from_branch into this branch.
709
675
 
710
676
        :param from_branch: Where to copy from.
711
 
        :param last_revision: What revision to stop at (None for at the end
 
677
        :param stop_revision: What revision to stop at (None for at the end
712
678
                              of the branch.
713
679
        :param limit: Optional rough limit of revisions to fetch
714
680
        :return: None
715
681
        """
716
 
        return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
 
682
        with self.lock_write():
 
683
            return InterBranch.get(from_branch, self).fetch(
 
684
                stop_revision, limit=limit, lossy=lossy)
717
685
 
718
686
    def get_bound_location(self):
719
687
        """Return the URL of the branch we are bound to.
741
709
        :param revprops: Optional dictionary of revision properties.
742
710
        :param revision_id: Optional revision id.
743
711
        :param lossy: Whether to discard data that can not be natively
744
 
            represented, when pushing to a foreign VCS 
 
712
            represented, when pushing to a foreign VCS
745
713
        """
746
714
 
747
715
        if config_stack is None:
748
716
            config_stack = self.get_config_stack()
749
717
 
750
 
        return self.repository.get_commit_builder(self, parents, config_stack,
751
 
            timestamp, timezone, committer, revprops, revision_id,
752
 
            lossy)
 
718
        return self.repository.get_commit_builder(
 
719
            self, parents, config_stack, timestamp, timezone, committer,
 
720
            revprops, revision_id, lossy)
753
721
 
754
722
    def get_master_branch(self, possible_transports=None):
755
723
        """Return the branch we are bound to.
758
726
        """
759
727
        return None
760
728
 
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
 
 
774
729
    def get_stacked_on_url(self):
775
730
        """Get the URL this branch is stacked against.
776
731
 
780
735
        """
781
736
        raise NotImplementedError(self.get_stacked_on_url)
782
737
 
783
 
    def print_file(self, file, revision_id):
784
 
        """Print `file` to stdout."""
785
 
        raise NotImplementedError(self.print_file)
786
 
 
787
 
    @needs_write_lock
788
738
    def set_last_revision_info(self, revno, revision_id):
789
739
        """Set the last revision of this branch.
790
740
 
798
748
        """
799
749
        raise NotImplementedError(self.set_last_revision_info)
800
750
 
801
 
    @needs_write_lock
802
751
    def generate_revision_history(self, revision_id, last_rev=None,
803
752
                                  other_branch=None):
804
753
        """See Branch.generate_revision_history"""
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)
 
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)
817
768
 
818
 
    @needs_write_lock
819
769
    def set_parent(self, url):
820
770
        """See Branch.set_parent."""
821
771
        # TODO: Maybe delete old location files?
823
773
        # FIXUP this and get_parent in a future branch format bump:
824
774
        # read and rewrite the file. RBC 20060125
825
775
        if url is not None:
826
 
            if isinstance(url, unicode):
 
776
            if isinstance(url, str):
827
777
                try:
828
 
                    url = url.encode('ascii')
 
778
                    url.encode('ascii')
829
779
                except UnicodeEncodeError:
830
 
                    raise errors.InvalidURL(url,
831
 
                        "Urls must be 7-bit ascii, "
832
 
                        "use bzrlib.urlutils.escape")
 
780
                    raise urlutils.InvalidURL(
 
781
                        url, "Urls must be 7-bit ascii, "
 
782
                        "use breezy.urlutils.escape")
833
783
            url = urlutils.relative_url(self.base, url)
834
 
        self._set_parent_location(url)
 
784
        with self.lock_write():
 
785
            self._set_parent_location(url)
835
786
 
836
 
    @needs_write_lock
837
787
    def set_stacked_on_url(self, url):
838
788
        """Set the URL this branch is stacked against.
839
789
 
843
793
            stacking.
844
794
        """
845
795
        if not self._format.supports_stacking():
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)
 
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)
864
815
 
865
816
    def _unstack(self):
866
817
        """Change a branch to be unstacked, copying data as needed.
867
818
 
868
819
        Don't call this directly, use set_stacked_on_url(None).
869
820
        """
870
 
        pb = ui.ui_factory.nested_progress_bar()
871
 
        try:
 
821
        with ui.ui_factory.nested_progress_bar() as pb:
872
822
            pb.update(gettext("Unstacking"))
873
823
            # The basic approach here is to fetch the tip of the branch,
874
824
            # including all available ghosts, from the existing stacked
875
 
            # repository into a new repository object without the fallbacks. 
 
825
            # repository into a new repository object without the fallbacks.
876
826
            #
877
827
            # XXX: See <https://launchpad.net/bugs/397286> - this may not be
878
828
            # correct for CHKMap repostiories
879
829
            old_repository = self.repository
880
830
            if len(old_repository._fallback_repositories) != 1:
881
 
                raise AssertionError("can't cope with fallback repositories "
882
 
                    "of %r (fallbacks: %r)" % (old_repository,
883
 
                        old_repository._fallback_repositories))
 
831
                raise AssertionError(
 
832
                    "can't cope with fallback repositories "
 
833
                    "of %r (fallbacks: %r)" % (
 
834
                        old_repository, old_repository._fallback_repositories))
884
835
            # Open the new repository object.
885
836
            # Repositories don't offer an interface to remove fallback
886
837
            # repositories today; take the conceptually simpler option and just
890
841
            # separate SSH connection setup, but unstacking is not a
891
842
            # common operation so it's tolerable.
892
843
            new_bzrdir = controldir.ControlDir.open(
893
 
                self.bzrdir.root_transport.base)
 
844
                self.controldir.root_transport.base)
894
845
            new_repository = new_bzrdir.find_repository()
895
846
            if new_repository._fallback_repositories:
896
 
                raise AssertionError("didn't expect %r to have "
897
 
                    "fallback_repositories"
 
847
                raise AssertionError(
 
848
                    "didn't expect %r to have fallback_repositories"
898
849
                    % (self.repository,))
899
850
            # Replace self.repository with the new repository.
900
851
            # Do our best to transfer the lock state (i.e. lock-tokens and
927
878
            if old_lock_count == 0:
928
879
                raise AssertionError(
929
880
                    'old_repository should have been locked at least once.')
930
 
            for i in range(old_lock_count-1):
 
881
            for i in range(old_lock_count - 1):
931
882
                self.repository.lock_write()
932
883
            # Fetch from the old repository into the new.
933
 
            old_repository.lock_read()
934
 
            try:
 
884
            with old_repository.lock_read():
935
885
                # XXX: If you unstack a branch while it has a working tree
936
886
                # with a pending merge, the pending-merged revisions will no
937
887
                # longer be present.  You can (probably) revert and remerge.
939
889
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
940
890
                except errors.TagsNotSupported:
941
891
                    tags_to_fetch = set()
942
 
                fetch_spec = vf_search.NotInOtherForRevs(self.repository,
943
 
                    old_repository, required_ids=[self.last_revision()],
 
892
                fetch_spec = vf_search.NotInOtherForRevs(
 
893
                    self.repository, old_repository,
 
894
                    required_ids=[self.last_revision()],
944
895
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
945
896
                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)
963
897
 
964
898
    def _cache_revision_history(self, rev_history):
965
899
        """Set the cached revision history to rev_history.
996
930
        self._merge_sorted_revisions_cache = None
997
931
        self._partial_revision_history_cache = []
998
932
        self._partial_revision_id_to_revno_cache = {}
999
 
        self._tags_bytes = None
1000
933
 
1001
934
    def _gen_revision_history(self):
1002
935
        """Return sequence of revision hashes on to this branch.
1039
972
        """Return last revision id, or NULL_REVISION."""
1040
973
        return self.last_revision_info()[1]
1041
974
 
1042
 
    @needs_read_lock
1043
975
    def last_revision_info(self):
1044
976
        """Return information about the last revision.
1045
977
 
1046
978
        :return: A tuple (revno, revision_id).
1047
979
        """
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
 
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
1051
985
 
1052
986
    def _read_last_revision_info(self):
1053
987
        raise NotImplementedError(self._read_last_revision_info)
1083
1017
        except ValueError:
1084
1018
            raise errors.NoSuchRevision(self, revision_id)
1085
1019
 
1086
 
    @needs_read_lock
1087
1020
    def get_rev_id(self, revno, history=None):
1088
1021
        """Find the revision id of the specified revno."""
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]
 
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]
1100
1034
 
1101
1035
    def pull(self, source, overwrite=False, stop_revision=None,
1102
1036
             possible_transports=None, *args, **kwargs):
1106
1040
 
1107
1041
        :returns: PullResult instance
1108
1042
        """
1109
 
        return InterBranch.get(source, self).pull(overwrite=overwrite,
1110
 
            stop_revision=stop_revision,
 
1043
        return InterBranch.get(source, self).pull(
 
1044
            overwrite=overwrite, stop_revision=stop_revision,
1111
1045
            possible_transports=possible_transports, *args, **kwargs)
1112
1046
 
1113
1047
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1114
 
            *args, **kwargs):
 
1048
             *args, **kwargs):
1115
1049
        """Mirror this branch into target.
1116
1050
 
1117
1051
        This branch is considered to be 'local', having low latency.
1118
1052
        """
1119
 
        return InterBranch.get(self, target).push(overwrite, stop_revision,
1120
 
            lossy, *args, **kwargs)
 
1053
        return InterBranch.get(self, target).push(
 
1054
            overwrite, stop_revision, lossy, *args, **kwargs)
1121
1055
 
1122
1056
    def basis_tree(self):
1123
1057
        """Return `Tree` object for last revision."""
1136
1070
        # This is an old-format absolute path to a local branch
1137
1071
        # turn it into a url
1138
1072
        if parent.startswith('/'):
1139
 
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
 
1073
            parent = urlutils.local_path_to_url(parent)
1140
1074
        try:
1141
1075
            return urlutils.join(self.base[:-1], parent)
1142
 
        except errors.InvalidURLJoin, e:
 
1076
        except urlutils.InvalidURLJoin:
1143
1077
            raise errors.InaccessibleParent(parent, self.user_url)
1144
1078
 
1145
1079
    def _get_parent_location(self):
1231
1165
        for hook in hooks:
1232
1166
            hook(params)
1233
1167
 
1234
 
    @needs_write_lock
1235
1168
    def update(self):
1236
1169
        """Synchronise this branch with the master branch if any.
1237
1170
 
1255
1188
        if revno < 1 or revno > self.revno():
1256
1189
            raise errors.InvalidRevisionNumber(revno)
1257
1190
 
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.
 
1191
    def clone(self, to_controldir, revision_id=None, name=None,
 
1192
              repository_policy=None, tag_selector=None):
 
1193
        """Clone this branch into to_controldir preserving all semantic values.
1261
1194
 
1262
1195
        Most API users will want 'create_clone_on_transport', which creates a
1263
1196
        new bzrdir and branch on the fly.
1265
1198
        revision_id: if not None, the revision history in the new branch will
1266
1199
                     be truncated to end with revision_id.
1267
1200
        """
1268
 
        result = to_bzrdir.create_branch()
1269
 
        result.lock_write()
1270
 
        try:
 
1201
        result = to_controldir.create_branch(name=name)
 
1202
        with self.lock_read(), result.lock_write():
1271
1203
            if repository_policy is not None:
1272
1204
                repository_policy.configure_branch(result)
1273
 
            self.copy_content_into(result, revision_id=revision_id)
1274
 
        finally:
1275
 
            result.unlock()
 
1205
            self.copy_content_into(
 
1206
                result, revision_id=revision_id, tag_selector=tag_selector)
1276
1207
        return result
1277
1208
 
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.
 
1209
    def sprout(self, to_controldir, revision_id=None, repository_policy=None,
 
1210
               repository=None, lossy=False, tag_selector=None):
 
1211
        """Create a new line of development from the branch, into to_controldir.
1282
1212
 
1283
 
        to_bzrdir controls the branch format.
 
1213
        to_controldir controls the branch format.
1284
1214
 
1285
1215
        revision_id: if not None, the revision history in the new branch will
1286
1216
                     be truncated to end with revision_id.
1287
1217
        """
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:
 
1218
        if (repository_policy is not None
 
1219
                and repository_policy.requires_stacking()):
 
1220
            to_controldir._format.require_stacking(_skip_repo=True)
 
1221
        result = to_controldir.create_branch(repository=repository)
 
1222
        if lossy:
 
1223
            raise errors.LossyPushToSameVCS(self, result)
 
1224
        with self.lock_read(), result.lock_write():
1294
1225
            if repository_policy is not None:
1295
1226
                repository_policy.configure_branch(result)
1296
 
            self.copy_content_into(result, revision_id=revision_id)
 
1227
            self.copy_content_into(
 
1228
                result, revision_id=revision_id, tag_selector=tag_selector)
1297
1229
            master_url = self.get_bound_location()
1298
1230
            if master_url is None:
1299
 
                result.set_parent(self.bzrdir.root_transport.base)
 
1231
                result.set_parent(self.user_url)
1300
1232
            else:
1301
1233
                result.set_parent(master_url)
1302
 
        finally:
1303
 
            result.unlock()
1304
1234
        return result
1305
1235
 
1306
1236
    def _synchronize_history(self, destination, revision_id):
1321
1251
        else:
1322
1252
            graph = self.repository.get_graph()
1323
1253
            try:
1324
 
                revno = graph.find_distance_to_null(revision_id, 
1325
 
                    [(source_revision_id, source_revno)])
 
1254
                revno = graph.find_distance_to_null(
 
1255
                    revision_id, [(source_revision_id, source_revno)])
1326
1256
            except errors.GhostRevisionsHaveNoRevno:
1327
1257
                # Default to 1, if we can't find anything else
1328
1258
                revno = 1
1329
1259
        destination.set_last_revision_info(revno, revision_id)
1330
1260
 
1331
 
    def copy_content_into(self, destination, revision_id=None):
 
1261
    def copy_content_into(self, destination, revision_id=None, tag_selector=None):
1332
1262
        """Copy the content of self into destination.
1333
1263
 
1334
1264
        revision_id: if not None, the revision history in the new branch will
1335
1265
                     be truncated to end with revision_id.
 
1266
        tag_selector: Optional callback that receives a tag name
 
1267
            and should return a boolean to indicate whether a tag should be copied
1336
1268
        """
1337
1269
        return InterBranch.get(self, destination).copy_content_into(
1338
 
            revision_id=revision_id)
 
1270
            revision_id=revision_id, tag_selector=tag_selector)
1339
1271
 
1340
1272
    def update_references(self, target):
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)
 
1273
        if not self._format.supports_reference_locations:
 
1274
            return
 
1275
        return InterBranch.get(self, target).update_references()
1356
1276
 
1357
 
    @needs_read_lock
1358
1277
    def check(self, refs):
1359
1278
        """Check consistency of the branch.
1360
1279
 
1368
1287
            branch._get_check_refs()
1369
1288
        :return: A BranchCheckResult.
1370
1289
        """
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
 
1290
        with self.lock_read():
 
1291
            result = BranchCheckResult(self)
 
1292
            last_revno, last_revision_id = self.last_revision_info()
 
1293
            actual_revno = refs[('lefthand-distance', last_revision_id)]
 
1294
            if actual_revno != last_revno:
 
1295
                result.errors.append(errors.BzrCheckError(
 
1296
                    'revno does not match len(mainline) %s != %s' % (
 
1297
                        last_revno, actual_revno)))
 
1298
            # TODO: We should probably also check that self.revision_history
 
1299
            # matches the repository for older branch formats.
 
1300
            # If looking for the code that cross-checks repository parents
 
1301
            # against the Graph.iter_lefthand_ancestry output, that is now a
 
1302
            # repository specific check.
 
1303
            return result
1384
1304
 
1385
1305
    def _get_checkout_format(self, lightweight=False):
1386
1306
        """Return the most suitable metadir for a checkout of this branch.
1387
1307
        Weaves are used if this branch's repository uses weaves.
1388
1308
        """
1389
 
        format = self.repository.bzrdir.checkout_metadir()
 
1309
        format = self.repository.controldir.checkout_metadir()
1390
1310
        format.set_branch_format(self._format)
1391
1311
        return format
1392
1312
 
1393
1313
    def create_clone_on_transport(self, to_transport, revision_id=None,
1394
 
        stacked_on=None, create_prefix=False, use_existing_dir=False,
1395
 
        no_tree=None):
 
1314
                                  stacked_on=None, create_prefix=False,
 
1315
                                  use_existing_dir=False, no_tree=None,
 
1316
                                  tag_selector=None):
1396
1317
        """Create a clone of this branch and its bzrdir.
1397
1318
 
1398
1319
        :param to_transport: The transport to clone onto.
1405
1326
        """
1406
1327
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1407
1328
        # clone call. Or something. 20090224 RBC/spiv.
1408
 
        # XXX: Should this perhaps clone colocated branches as well, 
 
1329
        # XXX: Should this perhaps clone colocated branches as well,
1409
1330
        # rather than just the default branch? 20100319 JRV
1410
1331
        if revision_id is None:
1411
1332
            revision_id = self.last_revision()
1412
 
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1413
 
            revision_id=revision_id, stacked_on=stacked_on,
 
1333
        dir_to = self.controldir.clone_on_transport(
 
1334
            to_transport, revision_id=revision_id, stacked_on=stacked_on,
1414
1335
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1415
 
            no_tree=no_tree)
 
1336
            no_tree=no_tree, tag_selector=tag_selector)
1416
1337
        return dir_to.open_branch()
1417
1338
 
1418
1339
    def create_checkout(self, to_location, revision_id=None,
1419
1340
                        lightweight=False, accelerator_tree=None,
1420
 
                        hardlink=False):
 
1341
                        hardlink=False, recurse_nested=True):
1421
1342
        """Create a checkout of a branch.
1422
1343
 
1423
1344
        :param to_location: The url to produce the checkout at
1430
1351
            content is different.
1431
1352
        :param hardlink: If true, hard-link files from accelerator_tree,
1432
1353
            where possible.
 
1354
        :param recurse_nested: Whether to recurse into nested trees
1433
1355
        :return: The tree of the created checkout
1434
1356
        """
1435
1357
        t = transport.get_transport(to_location)
1447
1369
                pass
1448
1370
            else:
1449
1371
                raise errors.AlreadyControlDirError(t.base)
1450
 
            if checkout.control_transport.base == self.bzrdir.control_transport.base:
 
1372
            if (checkout.control_transport.base
 
1373
                    == self.controldir.control_transport.base):
1451
1374
                # When checking out to the same control directory,
1452
1375
                # always create a lightweight checkout
1453
1376
                lightweight = True
1456
1379
            from_branch = checkout.set_branch_reference(target_branch=self)
1457
1380
        else:
1458
1381
            policy = checkout.determine_repository_policy()
1459
 
            repo = policy.acquire_repository()[0]
 
1382
            policy.acquire_repository()
1460
1383
            checkout_branch = checkout.create_branch()
1461
1384
            checkout_branch.bind(self)
1462
1385
            # pull up to the specified revision_id to set the initial
1468
1391
                                           accelerator_tree=accelerator_tree,
1469
1392
                                           hardlink=hardlink)
1470
1393
        basis_tree = tree.basis_tree()
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()
 
1394
        with basis_tree.lock_read():
 
1395
            for path in basis_tree.iter_references():
 
1396
                reference_parent = tree.reference_parent(path)
 
1397
                if reference_parent is None:
 
1398
                    warning('Branch location for %s unknown.', path)
 
1399
                    continue
 
1400
                reference_parent.create_checkout(
 
1401
                    tree.abspath(path),
 
1402
                    basis_tree.get_reference_revision(path), lightweight)
1480
1403
        return tree
1481
1404
 
1482
 
    @needs_write_lock
1483
1405
    def reconcile(self, thorough=True):
1484
 
        """Make sure the data stored in this branch is consistent."""
1485
 
        from bzrlib.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
 
1406
        """Make sure the data stored in this branch is consistent.
 
1407
 
 
1408
        :return: A `ReconcileResult` object.
1496
1409
        """
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)
 
1410
        raise NotImplementedError(self.reconcile)
1500
1411
 
1501
1412
    def supports_tags(self):
1502
1413
        return self._format.supports_tags()
1538
1449
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1539
1450
        """
1540
1451
        heads = graph.heads([revision_a, revision_b])
1541
 
        if heads == set([revision_b]):
 
1452
        if heads == {revision_b}:
1542
1453
            return 'b_descends_from_a'
1543
 
        elif heads == set([revision_a, revision_b]):
 
1454
        elif heads == {revision_a, revision_b}:
1544
1455
            # These branches have diverged
1545
1456
            return 'diverged'
1546
 
        elif heads == set([revision_a]):
 
1457
        elif heads == {revision_a}:
1547
1458
            return 'a_descends_from_b'
1548
1459
        else:
1549
1460
            raise AssertionError("invalid heads: %r" % (heads,))
1559
1470
        """
1560
1471
        # For bzr native formats must_fetch is just the tip, and
1561
1472
        # if_present_fetch are the tags.
1562
 
        must_fetch = set([self.last_revision()])
 
1473
        must_fetch = {self.last_revision()}
1563
1474
        if_present_fetch = set()
1564
1475
        if self.get_config_stack().get('branch.fetch_tags'):
1565
1476
            try:
1570
1481
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1571
1482
        return must_fetch, if_present_fetch
1572
1483
 
 
1484
    def create_memorytree(self):
 
1485
        """Create a memory tree for this branch.
 
1486
 
 
1487
        :return: An in-memory MutableTree instance
 
1488
        """
 
1489
        return memorytree.MemoryTree.create_on_branch(self)
 
1490
 
1573
1491
 
1574
1492
class BranchFormat(controldir.ControlComponentFormat):
1575
1493
    """An encapsulation of the initialization and open routines for a format.
1676
1594
        raise NotImplementedError(self.network_name)
1677
1595
 
1678
1596
    def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
1679
 
            found_repository=None, possible_transports=None):
 
1597
             found_repository=None, possible_transports=None):
1680
1598
        """Return the branch object for controldir.
1681
1599
 
1682
1600
        :param controldir: A ControlDir that contains a branch.
1698
1616
 
1699
1617
    def supports_leaving_lock(self):
1700
1618
        """True if this format supports leaving locks in place."""
1701
 
        return False # by default
 
1619
        return False  # by default
1702
1620
 
1703
1621
    def __str__(self):
1704
1622
        return self.get_format_description().rstrip()
1715
1633
        """True if tags can reference ghost revisions."""
1716
1634
        return True
1717
1635
 
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
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1724
 
    use it, and the bzr-loom plugin uses it as well (see
1725
 
    bzrlib.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()()
 
1636
    def supports_store_uncommitted(self):
 
1637
        """True if uncommitted changes can be stored in this branch."""
 
1638
        return True
 
1639
 
 
1640
    def stores_revno(self):
 
1641
        """True if this branch format store revision numbers."""
 
1642
        return True
1745
1643
 
1746
1644
 
1747
1645
class BranchHooks(Hooks):
1757
1655
        These are all empty initially, because by default nothing should get
1758
1656
        notified.
1759
1657
        """
1760
 
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1761
 
        self.add_hook('open',
 
1658
        Hooks.__init__(self, "breezy.branch", "Branch.hooks")
 
1659
        self.add_hook(
 
1660
            'open',
1762
1661
            "Called with the Branch object that has been opened after a "
1763
1662
            "branch is opened.", (1, 8))
1764
 
        self.add_hook('post_push',
 
1663
        self.add_hook(
 
1664
            'post_push',
1765
1665
            "Called after a push operation completes. post_push is called "
1766
 
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1767
 
            "bzr client.", (0, 15))
1768
 
        self.add_hook('post_pull',
 
1666
            "with a breezy.branch.BranchPushResult object and only runs in "
 
1667
            "the bzr client.", (0, 15))
 
1668
        self.add_hook(
 
1669
            'post_pull',
1769
1670
            "Called after a pull operation completes. post_pull is called "
1770
 
            "with a bzrlib.branch.PullResult object and only runs in the "
 
1671
            "with a breezy.branch.PullResult object and only runs in the "
1771
1672
            "bzr client.", (0, 15))
1772
 
        self.add_hook('pre_commit',
 
1673
        self.add_hook(
 
1674
            'pre_commit',
1773
1675
            "Called after a commit is calculated but before it is "
1774
1676
            "completed. pre_commit is called with (local, master, old_revno, "
1775
1677
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1778
1680
            "basis revision. hooks MUST NOT modify this delta. "
1779
1681
            " future_tree is an in-memory tree obtained from "
1780
1682
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1781
 
            "tree.", (0,91))
1782
 
        self.add_hook('post_commit',
 
1683
            "tree.", (0, 91))
 
1684
        self.add_hook(
 
1685
            'post_commit',
1783
1686
            "Called in the bzr client after a commit has completed. "
1784
1687
            "post_commit is called with (local, master, old_revno, old_revid, "
1785
1688
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1786
1689
            "commit to a branch.", (0, 15))
1787
 
        self.add_hook('post_uncommit',
 
1690
        self.add_hook(
 
1691
            'post_uncommit',
1788
1692
            "Called in the bzr client after an uncommit completes. "
1789
1693
            "post_uncommit is called with (local, master, old_revno, "
1790
1694
            "old_revid, new_revno, new_revid) where local is the local branch "
1791
1695
            "or None, master is the target branch, and an empty branch "
1792
1696
            "receives new_revno of 0, new_revid of None.", (0, 15))
1793
 
        self.add_hook('pre_change_branch_tip',
 
1697
        self.add_hook(
 
1698
            'pre_change_branch_tip',
1794
1699
            "Called in bzr client and server before a change to the tip of a "
1795
1700
            "branch is made. pre_change_branch_tip is called with a "
1796
 
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
 
1701
            "breezy.branch.ChangeBranchTipParams. Note that push, pull, "
1797
1702
            "commit, uncommit will all trigger this hook.", (1, 6))
1798
 
        self.add_hook('post_change_branch_tip',
 
1703
        self.add_hook(
 
1704
            'post_change_branch_tip',
1799
1705
            "Called in bzr client and server after a change to the tip of a "
1800
1706
            "branch is made. post_change_branch_tip is called with a "
1801
 
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
 
1707
            "breezy.branch.ChangeBranchTipParams. Note that push, pull, "
1802
1708
            "commit, uncommit will all trigger this hook.", (1, 4))
1803
 
        self.add_hook('transform_fallback_location',
 
1709
        self.add_hook(
 
1710
            'transform_fallback_location',
1804
1711
            "Called when a stacked branch is activating its fallback "
1805
1712
            "locations. transform_fallback_location is called with (branch, "
1806
1713
            "url), and should return a new url. Returning the same url "
1812
1719
            "multiple hooks installed for transform_fallback_location, "
1813
1720
            "all are called with the url returned from the previous hook."
1814
1721
            "The order is however undefined.", (1, 9))
1815
 
        self.add_hook('automatic_tag_name',
 
1722
        self.add_hook(
 
1723
            'automatic_tag_name',
1816
1724
            "Called to determine an automatic tag name for a revision. "
1817
1725
            "automatic_tag_name is called with (branch, revision_id) and "
1818
1726
            "should return a tag name or None if no tag name could be "
1819
1727
            "determined. The first non-None tag name returned will be used.",
1820
1728
            (2, 2))
1821
 
        self.add_hook('post_branch_init',
 
1729
        self.add_hook(
 
1730
            'post_branch_init',
1822
1731
            "Called after new branch initialization completes. "
1823
1732
            "post_branch_init is called with a "
1824
 
            "bzrlib.branch.BranchInitHookParams. "
 
1733
            "breezy.branch.BranchInitHookParams. "
1825
1734
            "Note that init, branch and checkout (both heavyweight and "
1826
1735
            "lightweight) will all trigger this hook.", (2, 2))
1827
 
        self.add_hook('post_switch',
 
1736
        self.add_hook(
 
1737
            'post_switch',
1828
1738
            "Called after a checkout switches branch. "
1829
1739
            "post_switch is called with a "
1830
 
            "bzrlib.branch.SwitchHookParams.", (2, 2))
1831
 
 
 
1740
            "breezy.branch.SwitchHookParams.", (2, 2))
1832
1741
 
1833
1742
 
1834
1743
# install the default hooks into the Branch class.
1902
1811
        in branch, which refer to the original branch.
1903
1812
        """
1904
1813
        self.format = format
1905
 
        self.bzrdir = controldir
 
1814
        self.controldir = controldir
1906
1815
        self.name = name
1907
1816
        self.branch = branch
1908
1817
 
1941
1850
        return self.__dict__ == other.__dict__
1942
1851
 
1943
1852
    def __repr__(self):
1944
 
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1945
 
            self.control_dir, self.to_branch,
 
1853
        return "<%s for %s to (%s, %s)>" % (
 
1854
            self.__class__.__name__, self.control_dir, self.to_branch,
1946
1855
            self.revision_id)
1947
1856
 
1948
1857
 
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 bzrlib.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 bzrlib.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 bzrlib.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
 
 
2287
1858
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2288
1859
    """Branch format registry."""
2289
1860
 
2290
1861
    def __init__(self, other_registry=None):
2291
1862
        super(BranchFormatRegistry, self).__init__(other_registry)
2292
1863
        self._default_format = None
 
1864
        self._default_format_key = None
 
1865
 
 
1866
    def get_default(self):
 
1867
        """Return the current default format."""
 
1868
        if (self._default_format_key is not None
 
1869
                and self._default_format is None):
 
1870
            self._default_format = self.get(self._default_format_key)
 
1871
        return self._default_format
2293
1872
 
2294
1873
    def set_default(self, format):
 
1874
        """Set the default format."""
2295
1875
        self._default_format = format
 
1876
        self._default_format_key = None
2296
1877
 
2297
 
    def get_default(self):
2298
 
        return self._default_format
 
1878
    def set_default_key(self, format_string):
 
1879
        """Set the default format by its format string."""
 
1880
        self._default_format_key = format_string
 
1881
        self._default_format = None
2299
1882
 
2300
1883
 
2301
1884
network_format_registry = registry.FormatRegistry()
2311
1894
 
2312
1895
# formats which have no format string are not discoverable
2313
1896
# and not independently creatable, so are not registered.
2314
 
__format6 = BzrBranchFormat6()
2315
 
__format7 = BzrBranchFormat7()
2316
 
__format8 = BzrBranchFormat8()
2317
 
format_registry.register_lazy(
2318
 
    "Bazaar-NG branch format 5\n", "bzrlib.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)
 
1897
format_registry.register_lazy(
 
1898
    b"Bazaar-NG branch format 5\n", "breezy.bzr.fullhistory",
 
1899
    "BzrBranchFormat5")
 
1900
format_registry.register_lazy(
 
1901
    b"Bazaar Branch Format 6 (bzr 0.15)\n",
 
1902
    "breezy.bzr.branch", "BzrBranchFormat6")
 
1903
format_registry.register_lazy(
 
1904
    b"Bazaar Branch Format 7 (needs bzr 1.6)\n",
 
1905
    "breezy.bzr.branch", "BzrBranchFormat7")
 
1906
format_registry.register_lazy(
 
1907
    b"Bazaar Branch Format 8 (needs bzr 1.15)\n",
 
1908
    "breezy.bzr.branch", "BzrBranchFormat8")
 
1909
format_registry.register_lazy(
 
1910
    b"Bazaar-NG Branch Reference Format 1\n",
 
1911
    "breezy.bzr.branch", "BranchReferenceFormat")
 
1912
 
 
1913
format_registry.set_default_key(b"Bazaar Branch Format 7 (needs bzr 1.6)\n")
2324
1914
 
2325
1915
 
2326
1916
class BranchWriteLockResult(LogicalLockResult):
2327
1917
    """The result of write locking a branch.
2328
1918
 
2329
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
 
1919
    :ivar token: The token obtained from the underlying branch lock, or
2330
1920
        None.
2331
1921
    :ivar unlock: A callable which will unlock the lock.
2332
1922
    """
2333
1923
 
2334
 
    def __init__(self, unlock, branch_token):
2335
 
        LogicalLockResult.__init__(self, unlock)
2336
 
        self.branch_token = branch_token
2337
 
 
2338
1924
    def __repr__(self):
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 bzrlib.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)
 
1925
        return "BranchWriteLockResult(%r, %r)" % (self.unlock, self.token)
2936
1926
 
2937
1927
 
2938
1928
######################################################################
3009
1999
        tag_updates = getattr(self, "tag_updates", None)
3010
2000
        if not is_quiet():
3011
2001
            if self.old_revid != self.new_revid:
3012
 
                note(gettext('Pushed up to revision %d.') % self.new_revno)
 
2002
                if self.new_revno is not None:
 
2003
                    note(gettext('Pushed up to revision %d.'),
 
2004
                         self.new_revno)
 
2005
                else:
 
2006
                    note(gettext('Pushed up to revision id %s.'),
 
2007
                         self.new_revid.decode('utf-8'))
3013
2008
            if tag_updates:
3014
 
                note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
 
2009
                note(ngettext('%d tag updated.', '%d tags updated.',
 
2010
                              len(tag_updates)) % len(tag_updates))
3015
2011
            if self.old_revid == self.new_revid and not tag_updates:
3016
2012
                if not tag_conflicts:
3017
2013
                    note(gettext('No new revisions or tags to push.'))
3037
2033
            if any.
3038
2034
        """
3039
2035
        note(gettext('checked branch {0} format {1}').format(
3040
 
                                self.branch.user_url, self.branch._format))
 
2036
            self.branch.user_url, self.branch._format))
3041
2037
        for error in self.errors:
3042
2038
            note(gettext('found error:%s'), error)
3043
2039
 
3044
2040
 
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
 
 
3104
2041
class InterBranch(InterObject):
3105
2042
    """This class represents operations taking place between two branches.
3106
2043
 
3115
2052
    @classmethod
3116
2053
    def _get_branch_formats_to_test(klass):
3117
2054
        """Return an iterable of format tuples for testing.
3118
 
        
 
2055
 
3119
2056
        :return: An iterable of (from_format, to_format) to use when testing
3120
2057
            this InterBranch class. Each InterBranch class should define this
3121
2058
            method itself.
3122
2059
        """
3123
2060
        raise NotImplementedError(klass._get_branch_formats_to_test)
3124
2061
 
3125
 
    @needs_write_lock
3126
2062
    def pull(self, overwrite=False, stop_revision=None,
3127
 
             possible_transports=None, local=False):
 
2063
             possible_transports=None, local=False, tag_selector=None):
3128
2064
        """Mirror source into target branch.
3129
2065
 
3130
2066
        The target branch is considered to be 'local', having low latency.
3133
2069
        """
3134
2070
        raise NotImplementedError(self.pull)
3135
2071
 
3136
 
    @needs_write_lock
3137
2072
    def push(self, overwrite=False, stop_revision=None, lossy=False,
3138
 
             _override_hook_source_branch=None):
 
2073
             _override_hook_source_branch=None, tag_selector=None):
3139
2074
        """Mirror the source branch into the target branch.
3140
2075
 
3141
2076
        The source branch is considered to be 'local', having low latency.
3142
2077
        """
3143
2078
        raise NotImplementedError(self.push)
3144
2079
 
3145
 
    @needs_write_lock
3146
 
    def copy_content_into(self, revision_id=None):
 
2080
    def copy_content_into(self, revision_id=None, tag_selector=None):
3147
2081
        """Copy the content of source into target
3148
2082
 
3149
 
        revision_id: if not None, the revision history in the new branch will
3150
 
                     be truncated to end with revision_id.
 
2083
        :param revision_id:
 
2084
            if not None, the revision history in the new branch will
 
2085
            be truncated to end with revision_id.
 
2086
        :param tag_selector: Optional callback that can decide
 
2087
            to copy or not copy tags.
3151
2088
        """
3152
2089
        raise NotImplementedError(self.copy_content_into)
3153
2090
 
3154
 
    @needs_write_lock
3155
 
    def fetch(self, stop_revision=None, limit=None):
 
2091
    def fetch(self, stop_revision=None, limit=None, lossy=False):
3156
2092
        """Fetch revisions.
3157
2093
 
3158
2094
        :param stop_revision: Last revision to fetch
3159
2095
        :param limit: Optional rough limit of revisions to fetch
 
2096
        :return: FetchResult object
3160
2097
        """
3161
2098
        raise NotImplementedError(self.fetch)
3162
2099
 
 
2100
    def update_references(self):
 
2101
        """Import reference information from source to target.
 
2102
        """
 
2103
        raise NotImplementedError(self.update_references)
 
2104
 
3163
2105
 
3164
2106
def _fix_overwrite_type(overwrite):
3165
2107
    if isinstance(overwrite, bool):
3189
2131
            return format._custom_format
3190
2132
        return format
3191
2133
 
3192
 
    @needs_write_lock
3193
 
    def copy_content_into(self, revision_id=None):
 
2134
    def copy_content_into(self, revision_id=None, tag_selector=None):
3194
2135
        """Copy the content of source into target
3195
2136
 
3196
2137
        revision_id: if not None, the revision history in the new branch will
3197
2138
                     be truncated to end with revision_id.
3198
2139
        """
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)
 
2140
        with self.source.lock_read(), self.target.lock_write():
 
2141
            self.source._synchronize_history(self.target, revision_id)
 
2142
            self.update_references()
 
2143
            try:
 
2144
                parent = self.source.get_parent()
 
2145
            except errors.InaccessibleParent as e:
 
2146
                mutter('parent was not accessible to copy: %s', str(e))
 
2147
            else:
 
2148
                if parent:
 
2149
                    self.target.set_parent(parent)
 
2150
            if self.source._push_should_merge_tags():
 
2151
                self.source.tags.merge_to(self.target.tags, selector=tag_selector)
3210
2152
 
3211
 
    @needs_write_lock
3212
 
    def fetch(self, stop_revision=None, limit=None):
 
2153
    def fetch(self, stop_revision=None, limit=None, lossy=False):
3213
2154
        if self.target.base == self.source.base:
3214
2155
            return (0, [])
3215
 
        self.source.lock_read()
3216
 
        try:
 
2156
        with self.source.lock_read(), self.target.lock_write():
3217
2157
            fetch_spec_factory = fetch.FetchSpecFactory()
3218
2158
            fetch_spec_factory.source_branch = self.source
3219
2159
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3220
2160
            fetch_spec_factory.source_repo = self.source.repository
3221
2161
            fetch_spec_factory.target_repo = self.target.repository
3222
 
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
2162
            fetch_spec_factory.target_repo_kind = (
 
2163
                fetch.TargetRepoKinds.PREEXISTING)
3223
2164
            fetch_spec_factory.limit = limit
3224
2165
            fetch_spec = fetch_spec_factory.make_fetch_spec()
3225
 
            return self.target.repository.fetch(self.source.repository,
 
2166
            return self.target.repository.fetch(
 
2167
                self.source.repository,
 
2168
                lossy=lossy,
3226
2169
                fetch_spec=fetch_spec)
3227
 
        finally:
3228
 
            self.source.unlock()
3229
2170
 
3230
 
    @needs_write_lock
3231
2171
    def _update_revisions(self, stop_revision=None, overwrite=False,
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
 
2172
                          graph=None):
 
2173
        with self.source.lock_read(), self.target.lock_write():
 
2174
            other_revno, other_last_revision = self.source.last_revision_info()
 
2175
            stop_revno = None  # unknown
 
2176
            if stop_revision is None:
 
2177
                stop_revision = other_last_revision
 
2178
                if _mod_revision.is_null(stop_revision):
 
2179
                    # if there are no commits, we're done.
 
2180
                    return
 
2181
                stop_revno = other_revno
3241
2182
 
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 = \
 
2183
            # what's the current last revision, before we fetch [and change it
 
2184
            # possibly]
 
2185
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
2186
            # we fetch here so that we don't process data twice in the common
 
2187
            # case of having something to pull, and so that the check for
 
2188
            # already merged can operate on the just fetched graph, which will
 
2189
            # be cached in memory.
 
2190
            self.fetch(stop_revision=stop_revision)
 
2191
            # Check to see if one is an ancestor of the other
 
2192
            if not overwrite:
 
2193
                if graph is None:
 
2194
                    graph = self.target.repository.get_graph()
 
2195
                if self.target._check_if_descendant_or_diverged(
 
2196
                        stop_revision, last_rev, graph, self.source):
 
2197
                    # stop_revision is a descendant of last_rev, but we aren't
 
2198
                    # overwriting, so we're done.
 
2199
                    return
 
2200
            if stop_revno is None:
 
2201
                if graph is None:
 
2202
                    graph = self.target.repository.get_graph()
 
2203
                this_revno, this_last_revision = \
3263
2204
                    self.target.last_revision_info()
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)
 
2205
                stop_revno = graph.find_distance_to_null(
 
2206
                    stop_revision, [(other_last_revision, other_revno),
 
2207
                                    (this_last_revision, this_revno)])
 
2208
            self.target.set_last_revision_info(stop_revno, stop_revision)
3268
2209
 
3269
 
    @needs_write_lock
3270
2210
    def pull(self, overwrite=False, stop_revision=None,
3271
2211
             possible_transports=None, run_hooks=True,
3272
 
             _override_hook_target=None, local=False):
 
2212
             _override_hook_target=None, local=False,
 
2213
             tag_selector=None):
3273
2214
        """Pull from source into self, updating my master if any.
3274
2215
 
3275
2216
        :param run_hooks: Private parameter - if false, this branch
3276
2217
            is being called because it's the master of the primary branch,
3277
2218
            so it should not run its hooks.
3278
2219
        """
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:
 
2220
        with contextlib.ExitStack() as exit_stack:
 
2221
            exit_stack.enter_context(self.target.lock_write())
 
2222
            bound_location = self.target.get_bound_location()
 
2223
            if local and not bound_location:
 
2224
                raise errors.LocalRequiresBoundBranch()
 
2225
            master_branch = None
 
2226
            source_is_master = False
 
2227
            if bound_location:
 
2228
                # bound_location comes from a config file, some care has to be
 
2229
                # taken to relate it to source.user_url
 
2230
                normalized = urlutils.normalize_url(bound_location)
 
2231
                try:
 
2232
                    relpath = self.source.user_transport.relpath(normalized)
 
2233
                    source_is_master = (relpath == '')
 
2234
                except (errors.PathNotChild, urlutils.InvalidURL):
 
2235
                    source_is_master = False
 
2236
            if not local and bound_location and not source_is_master:
 
2237
                # not pulling from master, so we need to update master.
 
2238
                master_branch = self.target.get_master_branch(
 
2239
                    possible_transports)
 
2240
                exit_stack.enter_context(master_branch.lock_write())
3298
2241
            if master_branch:
3299
2242
                # pull from source into master.
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,
 
2243
                master_branch.pull(
 
2244
                    self.source, overwrite, stop_revision, run_hooks=False,
 
2245
                    tag_selector=tag_selector)
 
2246
            return self._pull(
 
2247
                overwrite, stop_revision, _hook_master=master_branch,
3304
2248
                run_hooks=run_hooks,
3305
2249
                _override_hook_target=_override_hook_target,
3306
 
                merge_tags_to_master=not source_is_master)
3307
 
        finally:
3308
 
            if master_branch:
3309
 
                master_branch.unlock()
 
2250
                merge_tags_to_master=not source_is_master,
 
2251
                tag_selector=tag_selector)
3310
2252
 
3311
2253
    def push(self, overwrite=False, stop_revision=None, lossy=False,
3312
 
             _override_hook_source_branch=None):
 
2254
             _override_hook_source_branch=None, tag_selector=None):
3313
2255
        """See InterBranch.push.
3314
2256
 
3315
2257
        This is the basic concrete implementation of push()
3324
2266
        # TODO: Public option to disable running hooks - should be trivial but
3325
2267
        # needs tests.
3326
2268
 
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)
3332
 
 
3333
 
    def _basic_push(self, overwrite, stop_revision):
 
2269
        def _run_hooks():
 
2270
            if _override_hook_source_branch:
 
2271
                result.source_branch = _override_hook_source_branch
 
2272
            for hook in Branch.hooks['post_push']:
 
2273
                hook(result)
 
2274
 
 
2275
        with self.source.lock_read(), self.target.lock_write():
 
2276
            bound_location = self.target.get_bound_location()
 
2277
            if bound_location and self.target.base != bound_location:
 
2278
                # there is a master branch.
 
2279
                #
 
2280
                # XXX: Why the second check?  Is it even supported for a branch
 
2281
                # to be bound to itself? -- mbp 20070507
 
2282
                master_branch = self.target.get_master_branch()
 
2283
                with master_branch.lock_write():
 
2284
                    # push into the master from the source branch.
 
2285
                    master_inter = InterBranch.get(self.source, master_branch)
 
2286
                    master_inter._basic_push(
 
2287
                        overwrite, stop_revision, tag_selector=tag_selector)
 
2288
                    # and push into the target branch from the source. Note
 
2289
                    # that we push from the source branch again, because it's
 
2290
                    # considered the highest bandwidth repository.
 
2291
                    result = self._basic_push(
 
2292
                        overwrite, stop_revision, tag_selector=tag_selector)
 
2293
                    result.master_branch = master_branch
 
2294
                    result.local_branch = self.target
 
2295
                    _run_hooks()
 
2296
            else:
 
2297
                master_branch = None
 
2298
                # no master branch
 
2299
                result = self._basic_push(
 
2300
                    overwrite, stop_revision, tag_selector=tag_selector)
 
2301
                # TODO: Why set master_branch and local_branch if there's no
 
2302
                # binding?  Maybe cleaner to just leave them unset? -- mbp
 
2303
                # 20070504
 
2304
                result.master_branch = self.target
 
2305
                result.local_branch = None
 
2306
                _run_hooks()
 
2307
            return result
 
2308
 
 
2309
    def _basic_push(self, overwrite, stop_revision, tag_selector=None):
3334
2310
        """Basic implementation of push without bound branches or hooks.
3335
2311
 
3336
2312
        Must be called with source read locked and target write locked.
3339
2315
        result.source_branch = self.source
3340
2316
        result.target_branch = self.target
3341
2317
        result.old_revno, result.old_revid = self.target.last_revision_info()
3342
 
        self.source.update_references(self.target)
3343
2318
        overwrite = _fix_overwrite_type(overwrite)
3344
2319
        if result.old_revid != stop_revision:
3345
2320
            # We assume that during 'push' this repository is closer than
3346
2321
            # the target.
3347
2322
            graph = self.source.repository.get_graph(self.target.repository)
3348
 
            self._update_revisions(stop_revision,
3349
 
                overwrite=("history" in overwrite),
3350
 
                graph=graph)
 
2323
            self._update_revisions(
 
2324
                stop_revision, overwrite=("history" in overwrite), graph=graph)
3351
2325
        if self.source._push_should_merge_tags():
3352
2326
            result.tag_updates, result.tag_conflicts = (
3353
2327
                self.source.tags.merge_to(
3354
 
                self.target.tags, "tags" in overwrite))
 
2328
                    self.target.tags, "tags" in overwrite, selector=tag_selector))
 
2329
        self.update_references()
3355
2330
        result.new_revno, result.new_revid = self.target.last_revision_info()
3356
2331
        return result
3357
2332
 
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
 
 
3398
2333
    def _pull(self, overwrite=False, stop_revision=None,
3399
 
             possible_transports=None, _hook_master=None, run_hooks=True,
3400
 
             _override_hook_target=None, local=False,
3401
 
             merge_tags_to_master=True):
 
2334
              possible_transports=None, _hook_master=None, run_hooks=True,
 
2335
              _override_hook_target=None, local=False,
 
2336
              merge_tags_to_master=True, tag_selector=None):
3402
2337
        """See Branch.pull.
3403
2338
 
3404
2339
        This function is the core worker, used by GenericInterBranch.pull to
3424
2359
            result.target_branch = self.target
3425
2360
        else:
3426
2361
            result.target_branch = _override_hook_target
3427
 
        self.source.lock_read()
3428
 
        try:
 
2362
        with self.source.lock_read():
3429
2363
            # We assume that during 'pull' the target repository is closer than
3430
2364
            # the source one.
3431
 
            self.source.update_references(self.target)
3432
2365
            graph = self.target.repository.get_graph(self.source.repository)
3433
 
            # TODO: Branch formats should have a flag that indicates 
 
2366
            # TODO: Branch formats should have a flag that indicates
3434
2367
            # that revno's are expensive, and pull() should honor that flag.
3435
2368
            # -- JRV20090506
3436
2369
            result.old_revno, result.old_revid = \
3437
2370
                self.target.last_revision_info()
3438
2371
            overwrite = _fix_overwrite_type(overwrite)
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 
 
2372
            self._update_revisions(
 
2373
                stop_revision, overwrite=("history" in overwrite), graph=graph)
 
2374
            # TODO: The old revid should be specified when merging tags,
 
2375
            # so a tags implementation that versions tags can only
3444
2376
            # pull in the most recent changes. -- JRV20090506
3445
2377
            result.tag_updates, result.tag_conflicts = (
3446
 
                self.source.tags.merge_to(self.target.tags,
3447
 
                    "tags" in overwrite,
3448
 
                    ignore_master=not merge_tags_to_master))
3449
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
2378
                self.source.tags.merge_to(
 
2379
                    self.target.tags, "tags" in overwrite,
 
2380
                    ignore_master=not merge_tags_to_master,
 
2381
                    selector=tag_selector))
 
2382
            self.update_references()
 
2383
            result.new_revno, result.new_revid = (
 
2384
                self.target.last_revision_info())
3450
2385
            if _hook_master:
3451
2386
                result.master_branch = _hook_master
3452
2387
                result.local_branch = result.target_branch
3456
2391
            if run_hooks:
3457
2392
                for hook in Branch.hooks['post_pull']:
3458
2393
                    hook(result)
3459
 
        finally:
3460
 
            self.source.unlock()
3461
 
        return result
 
2394
            return result
 
2395
 
 
2396
    def update_references(self):
 
2397
        if not getattr(self.source._format, 'supports_reference_locations', False):
 
2398
            return
 
2399
        reference_dict = self.source._get_all_reference_info()
 
2400
        if len(reference_dict) == 0:
 
2401
            return
 
2402
        old_base = self.source.base
 
2403
        new_base = self.target.base
 
2404
        target_reference_dict = self.target._get_all_reference_info()
 
2405
        for tree_path, (branch_location, file_id) in reference_dict.items():
 
2406
            try:
 
2407
                branch_location = urlutils.rebase_url(branch_location,
 
2408
                                                      old_base, new_base)
 
2409
            except urlutils.InvalidRebaseURLs:
 
2410
                # Fall back to absolute URL
 
2411
                branch_location = urlutils.join(old_base, branch_location)
 
2412
            target_reference_dict.setdefault(
 
2413
                tree_path, (branch_location, file_id))
 
2414
        self.target._set_all_reference_info(target_reference_dict)
3462
2415
 
3463
2416
 
3464
2417
InterBranch.register_optimiser(GenericInterBranch)