/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2009-03-13 07:54:48 UTC
  • mfrom: (4144 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4189.
  • Revision ID: mbp@sourcefrog.net-20090313075448-jlz1t7baz7gzipqn
merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
30
30
        lockable_files,
31
31
        repository,
32
32
        revision as _mod_revision,
 
33
        symbol_versioning,
33
34
        transport,
34
35
        tsort,
35
36
        ui,
44
45
""")
45
46
 
46
47
from bzrlib.decorators import needs_read_lock, needs_write_lock
47
 
from bzrlib.hooks import Hooks
 
48
from bzrlib.hooks import HookPoint, Hooks
 
49
from bzrlib.inter import InterObject
 
50
from bzrlib import registry
48
51
from bzrlib.symbol_versioning import (
49
52
    deprecated_in,
50
53
    deprecated_method,
81
84
    # - RBC 20060112
82
85
    base = None
83
86
 
84
 
    # override this to set the strategy for storing tags
85
 
    def _make_tags(self):
86
 
        return DisabledTags(self)
87
 
 
88
87
    def __init__(self, *ignored, **ignored_too):
89
 
        self.tags = self._make_tags()
 
88
        self.tags = self._format.make_tags(self)
90
89
        self._revision_history_cache = None
91
90
        self._revision_id_to_revno_cache = None
 
91
        self._partial_revision_id_to_revno_cache = {}
92
92
        self._last_revision_info_cache = None
 
93
        self._merge_sorted_revisions_cache = None
93
94
        self._open_hook()
94
95
        hooks = Branch.hooks['open']
95
96
        for hook in hooks:
132
133
    @staticmethod
133
134
    def open_containing(url, possible_transports=None):
134
135
        """Open an existing branch which contains url.
135
 
        
 
136
 
136
137
        This probes for a branch at url, and searches upwards from there.
137
138
 
138
139
        Basically we keep looking up until we find the control directory or
139
140
        run into the root.  If there isn't one, raises NotBranchError.
140
 
        If there is one and it is either an unrecognised format or an unsupported 
 
141
        If there is one and it is either an unrecognised format or an unsupported
141
142
        format, UnknownFormatError or UnsupportedFormatError are raised.
142
143
        If there is one, it is returned, along with the unused portion of url.
143
144
        """
145
146
                                                         possible_transports)
146
147
        return control.open_branch(), relpath
147
148
 
 
149
    def _push_should_merge_tags(self):
 
150
        """Should _basic_push merge this branch's tags into the target?
 
151
 
 
152
        The default implementation returns False if this branch has no tags,
 
153
        and True the rest of the time.  Subclasses may override this.
 
154
        """
 
155
        return self.supports_tags() and self.tags.get_tag_dict()
 
156
 
148
157
    def get_config(self):
149
158
        return BranchConfig(self)
150
159
 
 
160
    def _get_tags_bytes(self):
 
161
        """Get the bytes of a serialised tags dict.
 
162
 
 
163
        Note that not all branches support tags, nor do all use the same tags
 
164
        logic: this method is specific to BasicTags. Other tag implementations
 
165
        may use the same method name and behave differently, safely, because
 
166
        of the double-dispatch via
 
167
        format.make_tags->tags_instance->get_tags_dict.
 
168
 
 
169
        :return: The bytes of the tags file.
 
170
        :seealso: Branch._set_tags_bytes.
 
171
        """
 
172
        return self._transport.get_bytes('tags')
 
173
 
151
174
    def _get_nick(self, local=False, possible_transports=None):
152
175
        config = self.get_config()
153
176
        # explicit overrides master, but don't look for master if local is True
172
195
    def is_locked(self):
173
196
        raise NotImplementedError(self.is_locked)
174
197
 
 
198
    def _lefthand_history(self, revision_id, last_rev=None,
 
199
                          other_branch=None):
 
200
        if 'evil' in debug.debug_flags:
 
201
            mutter_callsite(4, "_lefthand_history scales with history.")
 
202
        # stop_revision must be a descendant of last_revision
 
203
        graph = self.repository.get_graph()
 
204
        if last_rev is not None:
 
205
            if not graph.is_ancestor(last_rev, revision_id):
 
206
                # our previous tip is not merged into stop_revision
 
207
                raise errors.DivergedBranches(self, other_branch)
 
208
        # make a new revision history from the graph
 
209
        parents_map = graph.get_parent_map([revision_id])
 
210
        if revision_id not in parents_map:
 
211
            raise errors.NoSuchRevision(self, revision_id)
 
212
        current_rev_id = revision_id
 
213
        new_history = []
 
214
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
215
        # Do not include ghosts or graph origin in revision_history
 
216
        while (current_rev_id in parents_map and
 
217
               len(parents_map[current_rev_id]) > 0):
 
218
            check_not_reserved_id(current_rev_id)
 
219
            new_history.append(current_rev_id)
 
220
            current_rev_id = parents_map[current_rev_id][0]
 
221
            parents_map = graph.get_parent_map([current_rev_id])
 
222
        new_history.reverse()
 
223
        return new_history
 
224
 
175
225
    def lock_write(self):
176
226
        raise NotImplementedError(self.lock_write)
177
227
 
189
239
        raise NotImplementedError(self.get_physical_lock_status)
190
240
 
191
241
    @needs_read_lock
 
242
    def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
 
243
        """Return the revision_id for a dotted revno.
 
244
 
 
245
        :param revno: a tuple like (1,) or (1,1,2)
 
246
        :param _cache_reverse: a private parameter enabling storage
 
247
           of the reverse mapping in a top level cache. (This should
 
248
           only be done in selective circumstances as we want to
 
249
           avoid having the mapping cached multiple times.)
 
250
        :return: the revision_id
 
251
        :raises errors.NoSuchRevision: if the revno doesn't exist
 
252
        """
 
253
        rev_id = self._do_dotted_revno_to_revision_id(revno)
 
254
        if _cache_reverse:
 
255
            self._partial_revision_id_to_revno_cache[rev_id] = revno
 
256
        return rev_id
 
257
 
 
258
    def _do_dotted_revno_to_revision_id(self, revno):
 
259
        """Worker function for dotted_revno_to_revision_id.
 
260
 
 
261
        Subclasses should override this if they wish to
 
262
        provide a more efficient implementation.
 
263
        """
 
264
        if len(revno) == 1:
 
265
            return self.get_rev_id(revno[0])
 
266
        revision_id_to_revno = self.get_revision_id_to_revno_map()
 
267
        revision_ids = [revision_id for revision_id, this_revno
 
268
                        in revision_id_to_revno.iteritems()
 
269
                        if revno == this_revno]
 
270
        if len(revision_ids) == 1:
 
271
            return revision_ids[0]
 
272
        else:
 
273
            revno_str = '.'.join(map(str, revno))
 
274
            raise errors.NoSuchRevision(self, revno_str)
 
275
 
 
276
    @needs_read_lock
 
277
    def revision_id_to_dotted_revno(self, revision_id):
 
278
        """Given a revision id, return its dotted revno.
 
279
 
 
280
        :return: a tuple like (1,) or (400,1,3).
 
281
        """
 
282
        return self._do_revision_id_to_dotted_revno(revision_id)
 
283
 
 
284
    def _do_revision_id_to_dotted_revno(self, revision_id):
 
285
        """Worker function for revision_id_to_revno."""
 
286
        # Try the caches if they are loaded
 
287
        result = self._partial_revision_id_to_revno_cache.get(revision_id)
 
288
        if result is not None:
 
289
            return result
 
290
        if self._revision_id_to_revno_cache:
 
291
            result = self._revision_id_to_revno_cache.get(revision_id)
 
292
            if result is None:
 
293
                raise errors.NoSuchRevision(self, revision_id)
 
294
        # Try the mainline as it's optimised
 
295
        try:
 
296
            revno = self.revision_id_to_revno(revision_id)
 
297
            return (revno,)
 
298
        except errors.NoSuchRevision:
 
299
            # We need to load and use the full revno map after all
 
300
            result = self.get_revision_id_to_revno_map().get(revision_id)
 
301
            if result is None:
 
302
                raise errors.NoSuchRevision(self, revision_id)
 
303
        return result
 
304
 
 
305
    @needs_read_lock
192
306
    def get_revision_id_to_revno_map(self):
193
307
        """Return the revision_id => dotted revno map.
194
308
 
218
332
 
219
333
        :return: A dictionary mapping revision_id => dotted revno.
220
334
        """
221
 
        last_revision = self.last_revision()
222
 
        revision_graph = repository._old_get_graph(self.repository,
223
 
            last_revision)
224
 
        merge_sorted_revisions = tsort.merge_sort(
225
 
            revision_graph,
226
 
            last_revision,
227
 
            None,
228
 
            generate_revno=True)
229
335
        revision_id_to_revno = dict((rev_id, revno)
230
 
                                    for seq_num, rev_id, depth, revno, end_of_merge
231
 
                                     in merge_sorted_revisions)
 
336
            for rev_id, depth, revno, end_of_merge
 
337
             in self.iter_merge_sorted_revisions())
232
338
        return revision_id_to_revno
233
339
 
 
340
    @needs_read_lock
 
341
    def iter_merge_sorted_revisions(self, start_revision_id=None,
 
342
            stop_revision_id=None, stop_rule='exclude', direction='reverse'):
 
343
        """Walk the revisions for a branch in merge sorted order.
 
344
 
 
345
        Merge sorted order is the output from a merge-aware,
 
346
        topological sort, i.e. all parents come before their
 
347
        children going forward; the opposite for reverse.
 
348
 
 
349
        :param start_revision_id: the revision_id to begin walking from.
 
350
            If None, the branch tip is used.
 
351
        :param stop_revision_id: the revision_id to terminate the walk
 
352
            after. If None, the rest of history is included.
 
353
        :param stop_rule: if stop_revision_id is not None, the precise rule
 
354
            to use for termination:
 
355
            * 'exclude' - leave the stop revision out of the result (default)
 
356
            * 'include' - the stop revision is the last item in the result
 
357
            * 'with-merges' - include the stop revision and all of its
 
358
              merged revisions in the result
 
359
        :param direction: either 'reverse' or 'forward':
 
360
            * reverse means return the start_revision_id first, i.e.
 
361
              start at the most recent revision and go backwards in history
 
362
            * forward returns tuples in the opposite order to reverse.
 
363
              Note in particular that forward does *not* do any intelligent
 
364
              ordering w.r.t. depth as some clients of this API may like.
 
365
              (If required, that ought to be done at higher layers.)
 
366
 
 
367
        :return: an iterator over (revision_id, depth, revno, end_of_merge)
 
368
            tuples where:
 
369
 
 
370
            * revision_id: the unique id of the revision
 
371
            * depth: How many levels of merging deep this node has been
 
372
              found.
 
373
            * revno_sequence: This field provides a sequence of
 
374
              revision numbers for all revisions. The format is:
 
375
              (REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
 
376
              branch that the revno is on. From left to right the REVNO numbers
 
377
              are the sequence numbers within that branch of the revision.
 
378
            * end_of_merge: When True the next node (earlier in history) is
 
379
              part of a different merge.
 
380
        """
 
381
        # Note: depth and revno values are in the context of the branch so
 
382
        # we need the full graph to get stable numbers, regardless of the
 
383
        # start_revision_id.
 
384
        if self._merge_sorted_revisions_cache is None:
 
385
            last_revision = self.last_revision()
 
386
            graph = self.repository.get_graph()
 
387
            parent_map = dict(((key, value) for key, value in
 
388
                     graph.iter_ancestry([last_revision]) if value is not None))
 
389
            revision_graph = repository._strip_NULL_ghosts(parent_map)
 
390
            revs = tsort.merge_sort(revision_graph, last_revision, None,
 
391
                generate_revno=True)
 
392
            # Drop the sequence # before caching
 
393
            self._merge_sorted_revisions_cache = [r[1:] for r in revs]
 
394
 
 
395
        filtered = self._filter_merge_sorted_revisions(
 
396
            self._merge_sorted_revisions_cache, start_revision_id,
 
397
            stop_revision_id, stop_rule)
 
398
        if direction == 'reverse':
 
399
            return filtered
 
400
        if direction == 'forward':
 
401
            return reversed(list(filtered))
 
402
        else:
 
403
            raise ValueError('invalid direction %r' % direction)
 
404
 
 
405
    def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
 
406
        start_revision_id, stop_revision_id, stop_rule):
 
407
        """Iterate over an inclusive range of sorted revisions."""
 
408
        rev_iter = iter(merge_sorted_revisions)
 
409
        if start_revision_id is not None:
 
410
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
411
                if rev_id != start_revision_id:
 
412
                    continue
 
413
                else:
 
414
                    # The decision to include the start or not
 
415
                    # depends on the stop_rule if a stop is provided
 
416
                    rev_iter = chain(
 
417
                        iter([(rev_id, depth, revno, end_of_merge)]),
 
418
                        rev_iter)
 
419
                    break
 
420
        if stop_revision_id is None:
 
421
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
422
                yield rev_id, depth, revno, end_of_merge
 
423
        elif stop_rule == 'exclude':
 
424
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
425
                if rev_id == stop_revision_id:
 
426
                    return
 
427
                yield rev_id, depth, revno, end_of_merge
 
428
        elif stop_rule == 'include':
 
429
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
430
                yield rev_id, depth, revno, end_of_merge
 
431
                if rev_id == stop_revision_id:
 
432
                    return
 
433
        elif stop_rule == 'with-merges':
 
434
            stop_rev = self.repository.get_revision(stop_revision_id)
 
435
            if stop_rev.parent_ids:
 
436
                left_parent = stop_rev.parent_ids[0]
 
437
            else:
 
438
                left_parent = _mod_revision.NULL_REVISION
 
439
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
440
                if rev_id == left_parent:
 
441
                    return
 
442
                yield rev_id, depth, revno, end_of_merge
 
443
        else:
 
444
            raise ValueError('invalid stop_rule %r' % stop_rule)
 
445
 
234
446
    def leave_lock_in_place(self):
235
447
        """Tell this branch object not to release the physical lock when this
236
448
        object is unlocked.
237
 
        
 
449
 
238
450
        If lock_write doesn't return a token, then this method is not supported.
239
451
        """
240
452
        self.control_files.leave_in_place()
263
475
        :param last_revision: What revision to stop at (None for at the end
264
476
                              of the branch.
265
477
        :param pb: An optional progress bar to use.
266
 
 
267
 
        Returns the copied revision count and the failed revisions in a tuple:
268
 
        (copied, failures).
 
478
        :return: None
269
479
        """
270
480
        if self.base == from_branch.base:
271
481
            return (0, [])
272
 
        if pb is None:
273
 
            nested_pb = ui.ui_factory.nested_progress_bar()
274
 
            pb = nested_pb
275
 
        else:
276
 
            nested_pb = None
277
 
 
 
482
        if pb is not None:
 
483
            symbol_versioning.warn(
 
484
                symbol_versioning.deprecated_in((1, 14, 0))
 
485
                % "pb parameter to fetch()")
278
486
        from_branch.lock_read()
279
487
        try:
280
488
            if last_revision is None:
281
 
                pb.update('get source history')
282
489
                last_revision = from_branch.last_revision()
283
490
                last_revision = _mod_revision.ensure_null(last_revision)
284
491
            return self.repository.fetch(from_branch.repository,
285
492
                                         revision_id=last_revision,
286
 
                                         pb=nested_pb)
 
493
                                         pb=pb)
287
494
        finally:
288
 
            if nested_pb is not None:
289
 
                nested_pb.finished()
290
495
            from_branch.unlock()
291
496
 
292
497
    def get_bound_location(self):
296
501
        branch.
297
502
        """
298
503
        return None
299
 
    
 
504
 
300
505
    def get_old_bound_location(self):
301
506
        """Return the URL of the branch we used to be bound to
302
507
        """
303
508
        raise errors.UpgradeRequired(self.base)
304
509
 
305
 
    def get_commit_builder(self, parents, config=None, timestamp=None, 
306
 
                           timezone=None, committer=None, revprops=None, 
 
510
    def get_commit_builder(self, parents, config=None, timestamp=None,
 
511
                           timezone=None, committer=None, revprops=None,
307
512
                           revision_id=None):
308
513
        """Obtain a CommitBuilder for this branch.
309
 
        
 
514
 
310
515
        :param parents: Revision ids of the parents of the new revision.
311
516
        :param config: Optional configuration to use.
312
517
        :param timestamp: Optional timestamp recorded for commit.
318
523
 
319
524
        if config is None:
320
525
            config = self.get_config()
321
 
        
 
526
 
322
527
        return self.repository.get_commit_builder(self, parents, config,
323
528
            timestamp, timezone, committer, revprops, revision_id)
324
529
 
325
530
    def get_master_branch(self, possible_transports=None):
326
531
        """Return the branch we are bound to.
327
 
        
 
532
 
328
533
        :return: Either a Branch, or None
329
534
        """
330
535
        return None
366
571
        """
367
572
        raise NotImplementedError(self.set_stacked_on_url)
368
573
 
 
574
    def _set_tags_bytes(self, bytes):
 
575
        """Mirror method for _get_tags_bytes.
 
576
 
 
577
        :seealso: Branch._get_tags_bytes.
 
578
        """
 
579
        return _run_with_write_locked_target(self, self._transport.put_bytes,
 
580
            'tags', bytes)
 
581
 
369
582
    def _cache_revision_history(self, rev_history):
370
583
        """Set the cached revision history to rev_history.
371
584
 
397
610
        self._revision_history_cache = None
398
611
        self._revision_id_to_revno_cache = None
399
612
        self._last_revision_info_cache = None
 
613
        self._merge_sorted_revisions_cache = None
400
614
 
401
615
    def _gen_revision_history(self):
402
616
        """Return sequence of revision hashes on to this branch.
403
 
        
 
617
 
404
618
        Unlike revision_history, this method always regenerates or rereads the
405
619
        revision history, i.e. it does not cache the result, so repeated calls
406
620
        may be expensive.
407
621
 
408
622
        Concrete subclasses should override this instead of revision_history so
409
623
        that subclasses do not need to deal with caching logic.
410
 
        
 
624
 
411
625
        This API is semi-public; it only for use by subclasses, all other code
412
626
        should consider it to be private.
413
627
        """
416
630
    @needs_read_lock
417
631
    def revision_history(self):
418
632
        """Return sequence of revision ids on this branch.
419
 
        
 
633
 
420
634
        This method will cache the revision history for as long as it is safe to
421
635
        do so.
422
636
        """
470
684
    @deprecated_method(deprecated_in((1, 6, 0)))
471
685
    def missing_revisions(self, other, stop_revision=None):
472
686
        """Return a list of new revisions that would perfectly fit.
473
 
        
 
687
 
474
688
        If self and other have not diverged, return a list of the revisions
475
689
        present in other, but missing from self.
476
690
        """
503
717
            information. This can be None.
504
718
        :return: None
505
719
        """
506
 
        other.lock_read()
507
 
        try:
508
 
            other_revno, other_last_revision = other.last_revision_info()
509
 
            stop_revno = None # unknown
510
 
            if stop_revision is None:
511
 
                stop_revision = other_last_revision
512
 
                if _mod_revision.is_null(stop_revision):
513
 
                    # if there are no commits, we're done.
514
 
                    return
515
 
                stop_revno = other_revno
516
 
 
517
 
            # what's the current last revision, before we fetch [and change it
518
 
            # possibly]
519
 
            last_rev = _mod_revision.ensure_null(self.last_revision())
520
 
            # we fetch here so that we don't process data twice in the common
521
 
            # case of having something to pull, and so that the check for 
522
 
            # already merged can operate on the just fetched graph, which will
523
 
            # be cached in memory.
524
 
            self.fetch(other, stop_revision)
525
 
            # Check to see if one is an ancestor of the other
526
 
            if not overwrite:
527
 
                if graph is None:
528
 
                    graph = self.repository.get_graph()
529
 
                if self._check_if_descendant_or_diverged(
530
 
                        stop_revision, last_rev, graph, other):
531
 
                    # stop_revision is a descendant of last_rev, but we aren't
532
 
                    # overwriting, so we're done.
533
 
                    return
534
 
            if stop_revno is None:
535
 
                if graph is None:
536
 
                    graph = self.repository.get_graph()
537
 
                this_revno, this_last_revision = self.last_revision_info()
538
 
                stop_revno = graph.find_distance_to_null(stop_revision,
539
 
                                [(other_last_revision, other_revno),
540
 
                                 (this_last_revision, this_revno)])
541
 
            self.set_last_revision_info(stop_revno, stop_revision)
542
 
        finally:
543
 
            other.unlock()
 
720
        return InterBranch.get(other, self).update_revisions(stop_revision,
 
721
            overwrite, graph)
 
722
 
 
723
    def import_last_revision_info(self, source_repo, revno, revid):
 
724
        """Set the last revision info, importing from another repo if necessary.
 
725
 
 
726
        This is used by the bound branch code to upload a revision to
 
727
        the master branch first before updating the tip of the local branch.
 
728
 
 
729
        :param source_repo: Source repository to optionally fetch from
 
730
        :param revno: Revision number of the new tip
 
731
        :param revid: Revision id of the new tip
 
732
        """
 
733
        if not self.repository.has_same_location(source_repo):
 
734
            self.repository.fetch(source_repo, revision_id=revid)
 
735
        self.set_last_revision_info(revno, revid)
544
736
 
545
737
    def revision_id_to_revno(self, revision_id):
546
738
        """Given a revision id, return its revno"""
586
778
    def get_parent(self):
587
779
        """Return the parent location of the branch.
588
780
 
589
 
        This is the default location for push/pull/missing.  The usual
 
781
        This is the default location for pull/missing.  The usual
590
782
        pattern is that the user can override it by specifying a
591
783
        location.
592
784
        """
593
 
        raise NotImplementedError(self.get_parent)
 
785
        parent = self._get_parent_location()
 
786
        if parent is None:
 
787
            return parent
 
788
        # This is an old-format absolute path to a local branch
 
789
        # turn it into a url
 
790
        if parent.startswith('/'):
 
791
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
 
792
        try:
 
793
            return urlutils.join(self.base[:-1], parent)
 
794
        except errors.InvalidURLJoin, e:
 
795
            raise errors.InaccessibleParent(parent, self.base)
 
796
 
 
797
    def _get_parent_location(self):
 
798
        raise NotImplementedError(self._get_parent_location)
594
799
 
595
800
    def _set_config_location(self, name, url, config=None,
596
801
                             make_relative=False):
654
859
        """Set a new push location for this branch."""
655
860
        raise NotImplementedError(self.set_push_location)
656
861
 
 
862
    def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
 
863
        """Run the post_change_branch_tip hooks."""
 
864
        hooks = Branch.hooks['post_change_branch_tip']
 
865
        if not hooks:
 
866
            return
 
867
        new_revno, new_revid = self.last_revision_info()
 
868
        params = ChangeBranchTipParams(
 
869
            self, old_revno, new_revno, old_revid, new_revid)
 
870
        for hook in hooks:
 
871
            hook(params)
 
872
 
 
873
    def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
 
874
        """Run the pre_change_branch_tip hooks."""
 
875
        hooks = Branch.hooks['pre_change_branch_tip']
 
876
        if not hooks:
 
877
            return
 
878
        old_revno, old_revid = self.last_revision_info()
 
879
        params = ChangeBranchTipParams(
 
880
            self, old_revno, new_revno, old_revid, new_revid)
 
881
        for hook in hooks:
 
882
            try:
 
883
                hook(params)
 
884
            except errors.TipChangeRejected:
 
885
                raise
 
886
            except Exception:
 
887
                exc_info = sys.exc_info()
 
888
                hook_name = Branch.hooks.get_hook_name(hook)
 
889
                raise errors.HookFailed(
 
890
                    'pre_change_branch_tip', hook_name, exc_info)
 
891
 
657
892
    def set_parent(self, url):
658
893
        raise NotImplementedError(self.set_parent)
659
894
 
660
895
    @needs_write_lock
661
896
    def update(self):
662
 
        """Synchronise this branch with the master branch if any. 
 
897
        """Synchronise this branch with the master branch if any.
663
898
 
664
899
        :return: None or the last_revision pivoted out during the update.
665
900
        """
672
907
        """
673
908
        if revno != 0:
674
909
            self.check_real_revno(revno)
675
 
            
 
910
 
676
911
    def check_real_revno(self, revno):
677
912
        """\
678
913
        Check whether a revno corresponds to a real revision.
682
917
            raise errors.InvalidRevisionNumber(revno)
683
918
 
684
919
    @needs_read_lock
685
 
    def clone(self, to_bzrdir, revision_id=None):
 
920
    def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
686
921
        """Clone this branch into to_bzrdir preserving all semantic values.
687
 
        
 
922
 
 
923
        Most API users will want 'create_clone_on_transport', which creates a
 
924
        new bzrdir and branch on the fly.
 
925
 
688
926
        revision_id: if not None, the revision history in the new branch will
689
927
                     be truncated to end with revision_id.
690
928
        """
691
929
        result = to_bzrdir.create_branch()
 
930
        if repository_policy is not None:
 
931
            repository_policy.configure_branch(result)
692
932
        self.copy_content_into(result, revision_id=revision_id)
693
933
        return  result
694
934
 
695
935
    @needs_read_lock
696
 
    def sprout(self, to_bzrdir, revision_id=None):
 
936
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
697
937
        """Create a new line of development from the branch, into to_bzrdir.
698
938
 
699
939
        to_bzrdir controls the branch format.
702
942
                     be truncated to end with revision_id.
703
943
        """
704
944
        result = to_bzrdir.create_branch()
 
945
        if repository_policy is not None:
 
946
            repository_policy.configure_branch(result)
705
947
        self.copy_content_into(result, revision_id=revision_id)
706
948
        result.set_parent(self.bzrdir.root_transport.base)
707
949
        return result
734
976
            revno = len(list(self.repository.iter_reverse_revision_history(
735
977
                                                                revision_id)))
736
978
        destination.set_last_revision_info(revno, revision_id)
737
 
    
 
979
 
738
980
    @needs_read_lock
739
981
    def copy_content_into(self, destination, revision_id=None):
740
982
        """Copy the content of self into destination.
750
992
        else:
751
993
            if parent:
752
994
                destination.set_parent(parent)
753
 
        self.tags.merge_to(destination.tags)
 
995
        if self._push_should_merge_tags():
 
996
            self.tags.merge_to(destination.tags)
754
997
 
755
998
    @needs_read_lock
756
999
    def check(self):
757
1000
        """Check consistency of the branch.
758
1001
 
759
1002
        In particular this checks that revisions given in the revision-history
760
 
        do actually match up in the revision graph, and that they're all 
 
1003
        do actually match up in the revision graph, and that they're all
761
1004
        present in the repository.
762
 
        
 
1005
 
763
1006
        Callers will typically also want to check the repository.
764
1007
 
765
1008
        :return: A BranchCheckResult.
804
1047
            format.set_branch_format(self._format)
805
1048
        return format
806
1049
 
 
1050
    def create_clone_on_transport(self, to_transport, revision_id=None,
 
1051
        stacked_on=None):
 
1052
        """Create a clone of this branch and its bzrdir.
 
1053
 
 
1054
        :param to_transport: The transport to clone onto.
 
1055
        :param revision_id: The revision id to use as tip in the new branch.
 
1056
            If None the tip is obtained from this branch.
 
1057
        :param stacked_on: An optional URL to stack the clone on.
 
1058
        """
 
1059
        # XXX: Fix the bzrdir API to allow getting the branch back from the
 
1060
        # clone call. Or something. 20090224 RBC/spiv.
 
1061
        dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1062
            revision_id=revision_id, stacked_on=stacked_on)
 
1063
        return dir_to.open_branch()
 
1064
 
807
1065
    def create_checkout(self, to_location, revision_id=None,
808
1066
                        lightweight=False, accelerator_tree=None,
809
1067
                        hardlink=False):
810
1068
        """Create a checkout of a branch.
811
 
        
 
1069
 
812
1070
        :param to_location: The url to produce the checkout at
813
1071
        :param revision_id: The revision to check out
814
1072
        :param lightweight: If True, produce a lightweight checkout, otherwise,
833
1091
                to_location, force_new_tree=False, format=format)
834
1092
            checkout = checkout_branch.bzrdir
835
1093
            checkout_branch.bind(self)
836
 
            # pull up to the specified revision_id to set the initial 
 
1094
            # pull up to the specified revision_id to set the initial
837
1095
            # branch tip correctly, and seed it with history.
838
1096
            checkout_branch.pull(self, stop_revision=revision_id)
839
1097
            from_branch=None
878
1136
        """Ensure that revision_b is a descendant of revision_a.
879
1137
 
880
1138
        This is a helper function for update_revisions.
881
 
        
 
1139
 
882
1140
        :raises: DivergedBranches if revision_b has diverged from revision_a.
883
1141
        :returns: True if revision_b is a descendant of revision_a.
884
1142
        """
894
1152
 
895
1153
    def _revision_relations(self, revision_a, revision_b, graph):
896
1154
        """Determine the relationship between two revisions.
897
 
        
 
1155
 
898
1156
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
899
1157
        """
900
1158
        heads = graph.heads([revision_a, revision_b])
917
1175
     * a format string,
918
1176
     * an open routine.
919
1177
 
920
 
    Formats are placed in an dict by their format string for reference 
 
1178
    Formats are placed in an dict by their format string for reference
921
1179
    during branch opening. Its not required that these be instances, they
922
 
    can be classes themselves with class methods - it simply depends on 
 
1180
    can be classes themselves with class methods - it simply depends on
923
1181
    whether state is needed for a given format or not.
924
1182
 
925
1183
    Once a format is deprecated, just deprecate the initialize and open
926
 
    methods on the format class. Do not deprecate the object, as the 
 
1184
    methods on the format class. Do not deprecate the object, as the
927
1185
    object will be created every time regardless.
928
1186
    """
929
1187
 
1031
1289
        """Is this format supported?
1032
1290
 
1033
1291
        Supported formats can be initialized and opened.
1034
 
        Unsupported formats may not support initialization or committing or 
 
1292
        Unsupported formats may not support initialization or committing or
1035
1293
        some other features depending on the reason for not being supported.
1036
1294
        """
1037
1295
        return True
1038
1296
 
 
1297
    def make_tags(self, branch):
 
1298
        """Create a tags object for branch.
 
1299
 
 
1300
        This method is on BranchFormat, because BranchFormats are reflected
 
1301
        over the wire via network_name(), whereas full Branch instances require
 
1302
        multiple VFS method calls to operate at all.
 
1303
 
 
1304
        The default implementation returns a disabled-tags instance.
 
1305
 
 
1306
        Note that it is normal for branch to be a RemoteBranch when using tags
 
1307
        on a RemoteBranch.
 
1308
        """
 
1309
        return DisabledTags(branch)
 
1310
 
 
1311
    def network_name(self):
 
1312
        """A simple byte string uniquely identifying this format for RPC calls.
 
1313
 
 
1314
        MetaDir branch formats use their disk format string to identify the
 
1315
        repository over the wire. All in one formats such as bzr < 0.8, and
 
1316
        foreign formats like svn/git and hg should use some marker which is
 
1317
        unique and immutable.
 
1318
        """
 
1319
        raise NotImplementedError(self.network_name)
 
1320
 
1039
1321
    def open(self, a_bzrdir, _found=False):
1040
1322
        """Return the branch object for a_bzrdir
1041
1323
 
1046
1328
 
1047
1329
    @classmethod
1048
1330
    def register_format(klass, format):
 
1331
        """Register a metadir format."""
1049
1332
        klass._formats[format.get_format_string()] = format
 
1333
        # Metadir formats have a network name of their format string, and get
 
1334
        # registered as class factories.
 
1335
        network_format_registry.register(format.get_format_string(), format.__class__)
1050
1336
 
1051
1337
    @classmethod
1052
1338
    def set_default_format(klass, format):
1061
1347
        del klass._formats[format.get_format_string()]
1062
1348
 
1063
1349
    def __str__(self):
1064
 
        return self.get_format_string().rstrip()
 
1350
        return self.get_format_description().rstrip()
1065
1351
 
1066
1352
    def supports_tags(self):
1067
1353
        """True if this format supports tags stored in the branch"""
1070
1356
 
1071
1357
class BranchHooks(Hooks):
1072
1358
    """A dictionary mapping hook name to a list of callables for branch hooks.
1073
 
    
 
1359
 
1074
1360
    e.g. ['set_rh'] Is the list of items to be called when the
1075
1361
    set_revision_history function is invoked.
1076
1362
    """
1082
1368
        notified.
1083
1369
        """
1084
1370
        Hooks.__init__(self)
1085
 
        # Introduced in 0.15:
1086
 
        # invoked whenever the revision history has been set
1087
 
        # with set_revision_history. The api signature is
1088
 
        # (branch, revision_history), and the branch will
1089
 
        # be write-locked.
1090
 
        self['set_rh'] = []
1091
 
        # Invoked after a branch is opened. The api signature is (branch).
1092
 
        self['open'] = []
1093
 
        # invoked after a push operation completes.
1094
 
        # the api signature is
1095
 
        # (push_result)
1096
 
        # containing the members
1097
 
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
1098
 
        # where local is the local target branch or None, master is the target 
1099
 
        # master branch, and the rest should be self explanatory. The source
1100
 
        # is read locked and the target branches write locked. Source will
1101
 
        # be the local low-latency branch.
1102
 
        self['post_push'] = []
1103
 
        # invoked after a pull operation completes.
1104
 
        # the api signature is
1105
 
        # (pull_result)
1106
 
        # containing the members
1107
 
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
1108
 
        # where local is the local branch or None, master is the target 
1109
 
        # master branch, and the rest should be self explanatory. The source
1110
 
        # is read locked and the target branches write locked. The local
1111
 
        # branch is the low-latency branch.
1112
 
        self['post_pull'] = []
1113
 
        # invoked before a commit operation takes place.
1114
 
        # the api signature is
1115
 
        # (local, master, old_revno, old_revid, future_revno, future_revid,
1116
 
        #  tree_delta, future_tree).
1117
 
        # old_revid is NULL_REVISION for the first commit to a branch
1118
 
        # tree_delta is a TreeDelta object describing changes from the basis
1119
 
        # revision, hooks MUST NOT modify this delta
1120
 
        # future_tree is an in-memory tree obtained from
1121
 
        # CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
1122
 
        self['pre_commit'] = []
1123
 
        # invoked after a commit operation completes.
1124
 
        # the api signature is 
1125
 
        # (local, master, old_revno, old_revid, new_revno, new_revid)
1126
 
        # old_revid is NULL_REVISION for the first commit to a branch.
1127
 
        self['post_commit'] = []
1128
 
        # invoked after a uncommit operation completes.
1129
 
        # the api signature is
1130
 
        # (local, master, old_revno, old_revid, new_revno, new_revid) where
1131
 
        # local is the local branch or None, master is the target branch,
1132
 
        # and an empty branch recieves new_revno of 0, new_revid of None.
1133
 
        self['post_uncommit'] = []
1134
 
        # Introduced in 1.6
1135
 
        # Invoked before the tip of a branch changes.
1136
 
        # the api signature is
1137
 
        # (params) where params is a ChangeBranchTipParams with the members
1138
 
        # (branch, old_revno, new_revno, old_revid, new_revid)
1139
 
        self['pre_change_branch_tip'] = []
1140
 
        # Introduced in 1.4
1141
 
        # Invoked after the tip of a branch changes.
1142
 
        # the api signature is
1143
 
        # (params) where params is a ChangeBranchTipParams with the members
1144
 
        # (branch, old_revno, new_revno, old_revid, new_revid)
1145
 
        self['post_change_branch_tip'] = []
1146
 
        # Introduced in 1.9
1147
 
        # Invoked when a stacked branch activates its fallback locations and
1148
 
        # allows the transformation of the url of said location.
1149
 
        # the api signature is
1150
 
        # (branch, url) where branch is the branch having its fallback
1151
 
        # location activated and url is the url for the fallback location.
1152
 
        # The hook should return a url.
1153
 
        self['transform_fallback_location'] = []
 
1371
        self.create_hook(HookPoint('set_rh',
 
1372
            "Invoked whenever the revision history has been set via "
 
1373
            "set_revision_history. The api signature is (branch, "
 
1374
            "revision_history), and the branch will be write-locked. "
 
1375
            "The set_rh hook can be expensive for bzr to trigger, a better "
 
1376
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
 
1377
        self.create_hook(HookPoint('open',
 
1378
            "Called with the Branch object that has been opened after a "
 
1379
            "branch is opened.", (1, 8), None))
 
1380
        self.create_hook(HookPoint('post_push',
 
1381
            "Called after a push operation completes. post_push is called "
 
1382
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
 
1383
            "bzr client.", (0, 15), None))
 
1384
        self.create_hook(HookPoint('post_pull',
 
1385
            "Called after a pull operation completes. post_pull is called "
 
1386
            "with a bzrlib.branch.PullResult object and only runs in the "
 
1387
            "bzr client.", (0, 15), None))
 
1388
        self.create_hook(HookPoint('pre_commit',
 
1389
            "Called after a commit is calculated but before it is is "
 
1390
            "completed. pre_commit is called with (local, master, old_revno, "
 
1391
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
 
1392
            "). old_revid is NULL_REVISION for the first commit to a branch, "
 
1393
            "tree_delta is a TreeDelta object describing changes from the "
 
1394
            "basis revision. hooks MUST NOT modify this delta. "
 
1395
            " future_tree is an in-memory tree obtained from "
 
1396
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
 
1397
            "tree.", (0,91), None))
 
1398
        self.create_hook(HookPoint('post_commit',
 
1399
            "Called in the bzr client after a commit has completed. "
 
1400
            "post_commit is called with (local, master, old_revno, old_revid, "
 
1401
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
 
1402
            "commit to a branch.", (0, 15), None))
 
1403
        self.create_hook(HookPoint('post_uncommit',
 
1404
            "Called in the bzr client after an uncommit completes. "
 
1405
            "post_uncommit is called with (local, master, old_revno, "
 
1406
            "old_revid, new_revno, new_revid) where local is the local branch "
 
1407
            "or None, master is the target branch, and an empty branch "
 
1408
            "recieves new_revno of 0, new_revid of None.", (0, 15), None))
 
1409
        self.create_hook(HookPoint('pre_change_branch_tip',
 
1410
            "Called in bzr client and server before a change to the tip of a "
 
1411
            "branch is made. pre_change_branch_tip is called with a "
 
1412
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
 
1413
            "commit, uncommit will all trigger this hook.", (1, 6), None))
 
1414
        self.create_hook(HookPoint('post_change_branch_tip',
 
1415
            "Called in bzr client and server after a change to the tip of a "
 
1416
            "branch is made. post_change_branch_tip is called with a "
 
1417
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
 
1418
            "commit, uncommit will all trigger this hook.", (1, 4), None))
 
1419
        self.create_hook(HookPoint('transform_fallback_location',
 
1420
            "Called when a stacked branch is activating its fallback "
 
1421
            "locations. transform_fallback_location is called with (branch, "
 
1422
            "url), and should return a new url. Returning the same url "
 
1423
            "allows it to be used as-is, returning a different one can be "
 
1424
            "used to cause the branch to stack on a closer copy of that "
 
1425
            "fallback_location. Note that the branch cannot have history "
 
1426
            "accessing methods called on it during this hook because the "
 
1427
            "fallback locations have not been activated. When there are "
 
1428
            "multiple hooks installed for transform_fallback_location, "
 
1429
            "all are called with the url returned from the previous hook."
 
1430
            "The order is however undefined.", (1, 9), None))
1154
1431
 
1155
1432
 
1156
1433
# install the default hooks into the Branch class.
1188
1465
 
1189
1466
    def __eq__(self, other):
1190
1467
        return self.__dict__ == other.__dict__
1191
 
    
 
1468
 
1192
1469
    def __repr__(self):
1193
1470
        return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1194
 
            self.__class__.__name__, self.branch, 
 
1471
            self.__class__.__name__, self.branch,
1195
1472
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1196
1473
 
1197
1474
 
1219
1496
        super(BzrBranchFormat4, self).__init__()
1220
1497
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1221
1498
 
 
1499
    def network_name(self):
 
1500
        """The network name for this format is the control dirs disk label."""
 
1501
        return self._matchingbzrdir.get_format_string()
 
1502
 
1222
1503
    def open(self, a_bzrdir, _found=False):
1223
1504
        """Return the branch object for a_bzrdir
1224
1505
 
1244
1525
        """What class to instantiate on open calls."""
1245
1526
        raise NotImplementedError(self._branch_class)
1246
1527
 
 
1528
    def network_name(self):
 
1529
        """A simple byte string uniquely identifying this format for RPC calls.
 
1530
 
 
1531
        Metadir branch formats use their format string.
 
1532
        """
 
1533
        return self.get_format_string()
 
1534
 
1247
1535
    def open(self, a_bzrdir, _found=False):
1248
1536
        """Return the branch object for a_bzrdir.
1249
1537
 
1298
1586
    def get_format_description(self):
1299
1587
        """See BranchFormat.get_format_description()."""
1300
1588
        return "Branch format 5"
1301
 
        
 
1589
 
1302
1590
    def initialize(self, a_bzrdir):
1303
1591
        """Create a branch of this format in a_bzrdir."""
1304
1592
        utf8_files = [('revision-history', ''),
1340
1628
                      ]
1341
1629
        return self._initialize_helper(a_bzrdir, utf8_files)
1342
1630
 
 
1631
    def make_tags(self, branch):
 
1632
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
1633
        return BasicTags(branch)
 
1634
 
 
1635
 
1343
1636
 
1344
1637
class BzrBranchFormat7(BranchFormatMetadir):
1345
1638
    """Branch format with last-revision, tags, and a stacked location pointer.
1374
1667
        self._matchingbzrdir.repository_format = \
1375
1668
            RepositoryFormatKnitPack5RichRoot()
1376
1669
 
 
1670
    def make_tags(self, branch):
 
1671
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
1672
        return BasicTags(branch)
 
1673
 
1377
1674
    def supports_stacking(self):
1378
1675
        return True
1379
1676
 
1429
1726
 
1430
1727
    def _make_reference_clone_function(format, a_branch):
1431
1728
        """Create a clone() routine for a branch dynamically."""
1432
 
        def clone(to_bzrdir, revision_id=None):
 
1729
        def clone(to_bzrdir, revision_id=None,
 
1730
            repository_policy=None):
1433
1731
            """See Branch.clone()."""
1434
1732
            return format.initialize(to_bzrdir, a_branch)
1435
1733
            # cannot obey revision_id limits when cloning a reference ...
1466
1764
        return result
1467
1765
 
1468
1766
 
 
1767
network_format_registry = registry.FormatRegistry()
 
1768
"""Registry of formats indexed by their network name.
 
1769
 
 
1770
The network name for a branch format is an identifier that can be used when
 
1771
referring to formats with smart server operations. See
 
1772
BranchFormat.network_name() for more detail.
 
1773
"""
 
1774
 
 
1775
 
1469
1776
# formats which have no format string are not discoverable
1470
1777
# and not independently creatable, so are not registered.
1471
1778
__format5 = BzrBranchFormat5()
1477
1784
BranchFormat.register_format(__format7)
1478
1785
BranchFormat.set_default_format(__format6)
1479
1786
_legacy_formats = [BzrBranchFormat4(),
1480
 
                   ]
 
1787
    ]
 
1788
network_format_registry.register(
 
1789
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
 
1790
 
1481
1791
 
1482
1792
class BzrBranch(Branch):
1483
1793
    """A branch stored in the actual filesystem.
1486
1796
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
1487
1797
    it's writable, and can be accessed via the normal filesystem API.
1488
1798
 
1489
 
    :ivar _transport: Transport for file operations on this branch's 
 
1799
    :ivar _transport: Transport for file operations on this branch's
1490
1800
        control files, typically pointing to the .bzr/branch directory.
1491
1801
    :ivar repository: Repository for this branch.
1492
 
    :ivar base: The url of the base directory for this branch; the one 
 
1802
    :ivar base: The url of the base directory for this branch; the one
1493
1803
        containing the .bzr directory.
1494
1804
    """
1495
 
    
 
1805
 
1496
1806
    def __init__(self, _format=None,
1497
1807
                 _control_files=None, a_bzrdir=None, _repository=None):
1498
1808
        """Create new branch object at a particular location."""
1552
1862
        if not self.control_files.is_locked():
1553
1863
            # we just released the lock
1554
1864
            self._clear_cached_state()
1555
 
        
 
1865
 
1556
1866
    def peek_lock_mode(self):
1557
1867
        if self.control_files._lock_count == 0:
1558
1868
            return None
1630
1940
                new_history = rev.get_history(self.repository)[1:]
1631
1941
        destination.set_revision_history(new_history)
1632
1942
 
1633
 
    def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1634
 
        """Run the pre_change_branch_tip hooks."""
1635
 
        hooks = Branch.hooks['pre_change_branch_tip']
1636
 
        if not hooks:
1637
 
            return
1638
 
        old_revno, old_revid = self.last_revision_info()
1639
 
        params = ChangeBranchTipParams(
1640
 
            self, old_revno, new_revno, old_revid, new_revid)
1641
 
        for hook in hooks:
1642
 
            try:
1643
 
                hook(params)
1644
 
            except errors.TipChangeRejected:
1645
 
                raise
1646
 
            except Exception:
1647
 
                exc_info = sys.exc_info()
1648
 
                hook_name = Branch.hooks.get_hook_name(hook)
1649
 
                raise errors.HookFailed(
1650
 
                    'pre_change_branch_tip', hook_name, exc_info)
1651
 
 
1652
 
    def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1653
 
        """Run the post_change_branch_tip hooks."""
1654
 
        hooks = Branch.hooks['post_change_branch_tip']
1655
 
        if not hooks:
1656
 
            return
1657
 
        new_revno, new_revid = self.last_revision_info()
1658
 
        params = ChangeBranchTipParams(
1659
 
            self, old_revno, new_revno, old_revid, new_revid)
1660
 
        for hook in hooks:
1661
 
            hook(params)
1662
 
 
1663
1943
    @needs_write_lock
1664
1944
    def set_last_revision_info(self, revno, revision_id):
1665
1945
        """Set the last revision of this branch.
1668
1948
        for this revision id.
1669
1949
 
1670
1950
        It may be possible to set the branch last revision to an id not
1671
 
        present in the repository.  However, branches can also be 
 
1951
        present in the repository.  However, branches can also be
1672
1952
        configured to check constraints on history, in which case this may not
1673
1953
        be permitted.
1674
1954
        """
1688
1968
            history.pop()
1689
1969
        return history
1690
1970
 
1691
 
    def _lefthand_history(self, revision_id, last_rev=None,
1692
 
                          other_branch=None):
1693
 
        if 'evil' in debug.debug_flags:
1694
 
            mutter_callsite(4, "_lefthand_history scales with history.")
1695
 
        # stop_revision must be a descendant of last_revision
1696
 
        graph = self.repository.get_graph()
1697
 
        if last_rev is not None:
1698
 
            if not graph.is_ancestor(last_rev, revision_id):
1699
 
                # our previous tip is not merged into stop_revision
1700
 
                raise errors.DivergedBranches(self, other_branch)
1701
 
        # make a new revision history from the graph
1702
 
        parents_map = graph.get_parent_map([revision_id])
1703
 
        if revision_id not in parents_map:
1704
 
            raise errors.NoSuchRevision(self, revision_id)
1705
 
        current_rev_id = revision_id
1706
 
        new_history = []
1707
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
1708
 
        # Do not include ghosts or graph origin in revision_history
1709
 
        while (current_rev_id in parents_map and
1710
 
               len(parents_map[current_rev_id]) > 0):
1711
 
            check_not_reserved_id(current_rev_id)
1712
 
            new_history.append(current_rev_id)
1713
 
            current_rev_id = parents_map[current_rev_id][0]
1714
 
            parents_map = graph.get_parent_map([current_rev_id])
1715
 
        new_history.reverse()
1716
 
        return new_history
1717
 
 
1718
1971
    @needs_write_lock
1719
1972
    def generate_revision_history(self, revision_id, last_rev=None,
1720
1973
        other_branch=None):
1739
1992
             _override_hook_target=None):
1740
1993
        """See Branch.pull.
1741
1994
 
1742
 
        :param _hook_master: Private parameter - set the branch to 
 
1995
        :param _hook_master: Private parameter - set the branch to
1743
1996
            be supplied as the master to pull hooks.
1744
1997
        :param run_hooks: Private parameter - if false, this branch
1745
1998
            is being called because it's the master of the primary branch,
1793
2046
        This is the basic concrete implementation of push()
1794
2047
 
1795
2048
        :param _override_hook_source_branch: If specified, run
1796
 
        the hooks passing this Branch as the source, rather than self.  
 
2049
        the hooks passing this Branch as the source, rather than self.
1797
2050
        This is for use of RemoteBranch, where push is delegated to the
1798
 
        underlying vfs-based Branch. 
 
2051
        underlying vfs-based Branch.
1799
2052
        """
1800
2053
        # TODO: Public option to disable running hooks - should be trivial but
1801
2054
        # needs tests.
1808
2061
            stop_revision,
1809
2062
            _override_hook_source_branch=None):
1810
2063
        """Push from self into target, and into target's master if any.
1811
 
        
1812
 
        This is on the base BzrBranch class even though it doesn't support 
 
2064
 
 
2065
        This is on the base BzrBranch class even though it doesn't support
1813
2066
        bound branches because the *target* might be bound.
1814
2067
        """
1815
2068
        def _run_hooks():
1855
2108
 
1856
2109
        Must be called with self read locked and target write locked.
1857
2110
        """
1858
 
        result = PushResult()
 
2111
        result = BranchPushResult()
1859
2112
        result.source_branch = self
1860
2113
        result.target_branch = target
1861
2114
        result.old_revno, result.old_revid = target.last_revision_info()
1870
2123
        result.new_revno, result.new_revid = target.last_revision_info()
1871
2124
        return result
1872
2125
 
1873
 
    def _push_should_merge_tags(self):
1874
 
        """Should _basic_push merge this branch's tags into the target?
1875
 
        
1876
 
        The default implementation returns False if this branch has no tags,
1877
 
        and True the rest of the time.  Subclasses may override this.
1878
 
        """
1879
 
        return self.tags.supports_tags() and self.tags.get_tag_dict()
1880
 
 
1881
 
    def get_parent(self):
1882
 
        """See Branch.get_parent."""
1883
 
        parent = self._get_parent_location()
1884
 
        if parent is None:
1885
 
            return parent
1886
 
        # This is an old-format absolute path to a local branch
1887
 
        # turn it into a url
1888
 
        if parent.startswith('/'):
1889
 
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
1890
 
        try:
1891
 
            return urlutils.join(self.base[:-1], parent)
1892
 
        except errors.InvalidURLJoin, e:
1893
 
            raise errors.InaccessibleParent(parent, self.base)
1894
 
 
1895
2126
    def get_stacked_on_url(self):
1896
2127
        raise errors.UnstackableBranchFormat(self._format, self.base)
1897
2128
 
1941
2172
             run_hooks=True, possible_transports=None,
1942
2173
             _override_hook_target=None):
1943
2174
        """Pull from source into self, updating my master if any.
1944
 
        
 
2175
 
1945
2176
        :param run_hooks: Private parameter - if false, this branch
1946
2177
            is being called because it's the master of the primary branch,
1947
2178
            so it should not run its hooks.
1974
2205
    @needs_read_lock
1975
2206
    def get_master_branch(self, possible_transports=None):
1976
2207
        """Return the branch we are bound to.
1977
 
        
 
2208
 
1978
2209
        :return: Either a Branch, or None
1979
2210
 
1980
2211
        This could memoise the branch, but if thats done
2016
2247
        check for divergence to raise an error when the branches are not
2017
2248
        either the same, or one a prefix of the other. That behaviour may not
2018
2249
        be useful, so that check may be removed in future.
2019
 
        
 
2250
 
2020
2251
        :param other: The branch to bind to
2021
2252
        :type other: Branch
2022
2253
        """
2041
2272
 
2042
2273
    @needs_write_lock
2043
2274
    def update(self, possible_transports=None):
2044
 
        """Synchronise this branch with the master branch if any. 
 
2275
        """Synchronise this branch with the master branch if any.
2045
2276
 
2046
2277
        :return: None or the last_revision that was pivoted out during the
2047
2278
                 update.
2138
2369
 
2139
2370
    def _synchronize_history(self, destination, revision_id):
2140
2371
        """Synchronize last revision and revision history between branches.
2141
 
        
 
2372
 
2142
2373
        :see: Branch._synchronize_history
2143
2374
        """
2144
2375
        # XXX: The base Branch has a fast implementation of this method based
2302
2533
        value = self.get_config().get_user_option('append_revisions_only')
2303
2534
        return value == 'True'
2304
2535
 
2305
 
    def _make_tags(self):
2306
 
        return BasicTags(self)
2307
 
 
2308
2536
    @needs_write_lock
2309
2537
    def generate_revision_history(self, revision_id, last_rev=None,
2310
2538
                                  other_branch=None):
2384
2612
    :ivar new_revno: Revision number after pull.
2385
2613
    :ivar old_revid: Tip revision id before pull.
2386
2614
    :ivar new_revid: Tip revision id after pull.
2387
 
    :ivar source_branch: Source (local) branch object.
 
2615
    :ivar source_branch: Source (local) branch object. (read locked)
2388
2616
    :ivar master_branch: Master branch of the target, or the target if no
2389
2617
        Master
2390
2618
    :ivar local_branch: target branch if there is a Master, else None
2391
 
    :ivar target_branch: Target/destination branch object.
 
2619
    :ivar target_branch: Target/destination branch object. (write locked)
2392
2620
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2393
2621
    """
2394
2622
 
2405
2633
        self._show_tag_conficts(to_file)
2406
2634
 
2407
2635
 
2408
 
class PushResult(_Result):
 
2636
class BranchPushResult(_Result):
2409
2637
    """Result of a Branch.push operation.
2410
2638
 
2411
 
    :ivar old_revno: Revision number before push.
2412
 
    :ivar new_revno: Revision number after push.
2413
 
    :ivar old_revid: Tip revision id before push.
2414
 
    :ivar new_revid: Tip revision id after push.
2415
 
    :ivar source_branch: Source branch object.
2416
 
    :ivar master_branch: Master branch of the target, or None.
2417
 
    :ivar target_branch: Target/destination branch object.
 
2639
    :ivar old_revno: Revision number (eg 10) of the target before push.
 
2640
    :ivar new_revno: Revision number (eg 12) of the target after push.
 
2641
    :ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
 
2642
        before the push.
 
2643
    :ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
 
2644
        after the push.
 
2645
    :ivar source_branch: Source branch object that the push was from. This is
 
2646
        read locked, and generally is a local (and thus low latency) branch.
 
2647
    :ivar master_branch: If target is a bound branch, the master branch of
 
2648
        target, or target itself. Always write locked.
 
2649
    :ivar target_branch: The direct Branch where data is being sent (write
 
2650
        locked).
 
2651
    :ivar local_branch: If the target is a bound branch this will be the
 
2652
        target, otherwise it will be None.
2418
2653
    """
2419
2654
 
2420
2655
    def __int__(self):
2424
2659
    def report(self, to_file):
2425
2660
        """Write a human-readable description of the result."""
2426
2661
        if self.old_revid == self.new_revid:
2427
 
            to_file.write('No new revisions to push.\n')
 
2662
            note('No new revisions to push.')
2428
2663
        else:
2429
 
            to_file.write('Pushed up to revision %d.\n' % self.new_revno)
 
2664
            note('Pushed up to revision %d.' % self.new_revno)
2430
2665
        self._show_tag_conficts(to_file)
2431
2666
 
2432
2667
 
2441
2676
 
2442
2677
    def report_results(self, verbose):
2443
2678
        """Report the check results via trace.note.
2444
 
        
 
2679
 
2445
2680
        :param verbose: Requests more detailed display of what was checked,
2446
2681
            if any.
2447
2682
        """
2507
2742
            return callable(*args, **kwargs)
2508
2743
        finally:
2509
2744
            target.unlock()
2510
 
    
 
2745
 
2511
2746
    """
2512
2747
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
2513
2748
    # should share code?
2523
2758
    else:
2524
2759
        target.unlock()
2525
2760
        return result
 
2761
 
 
2762
 
 
2763
class InterBranch(InterObject):
 
2764
    """This class represents operations taking place between two branches.
 
2765
 
 
2766
    Its instances have methods like pull() and push() and contain
 
2767
    references to the source and target repositories these operations
 
2768
    can be carried out on.
 
2769
    """
 
2770
 
 
2771
    _optimisers = []
 
2772
    """The available optimised InterBranch types."""
 
2773
 
 
2774
    @staticmethod
 
2775
    def _get_branch_formats_to_test():
 
2776
        """Return a tuple with the Branch formats to use when testing."""
 
2777
        raise NotImplementedError(self._get_branch_formats_to_test)
 
2778
 
 
2779
    def update_revisions(self, stop_revision=None, overwrite=False,
 
2780
                         graph=None):
 
2781
        """Pull in new perfect-fit revisions.
 
2782
 
 
2783
        :param stop_revision: Updated until the given revision
 
2784
        :param overwrite: Always set the branch pointer, rather than checking
 
2785
            to see if it is a proper descendant.
 
2786
        :param graph: A Graph object that can be used to query history
 
2787
            information. This can be None.
 
2788
        :return: None
 
2789
        """
 
2790
        raise NotImplementedError(self.update_revisions)
 
2791
 
 
2792
 
 
2793
class GenericInterBranch(InterBranch):
 
2794
    """InterBranch implementation that uses public Branch functions.
 
2795
    """
 
2796
 
 
2797
    @staticmethod
 
2798
    def _get_branch_formats_to_test():
 
2799
        return BranchFormat._default_format, BranchFormat._default_format
 
2800
 
 
2801
    def update_revisions(self, stop_revision=None, overwrite=False,
 
2802
        graph=None):
 
2803
        """See InterBranch.update_revisions()."""
 
2804
        self.source.lock_read()
 
2805
        try:
 
2806
            other_revno, other_last_revision = self.source.last_revision_info()
 
2807
            stop_revno = None # unknown
 
2808
            if stop_revision is None:
 
2809
                stop_revision = other_last_revision
 
2810
                if _mod_revision.is_null(stop_revision):
 
2811
                    # if there are no commits, we're done.
 
2812
                    return
 
2813
                stop_revno = other_revno
 
2814
 
 
2815
            # what's the current last revision, before we fetch [and change it
 
2816
            # possibly]
 
2817
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
2818
            # we fetch here so that we don't process data twice in the common
 
2819
            # case of having something to pull, and so that the check for
 
2820
            # already merged can operate on the just fetched graph, which will
 
2821
            # be cached in memory.
 
2822
            self.target.fetch(self.source, stop_revision)
 
2823
            # Check to see if one is an ancestor of the other
 
2824
            if not overwrite:
 
2825
                if graph is None:
 
2826
                    graph = self.target.repository.get_graph()
 
2827
                if self.target._check_if_descendant_or_diverged(
 
2828
                        stop_revision, last_rev, graph, self.source):
 
2829
                    # stop_revision is a descendant of last_rev, but we aren't
 
2830
                    # overwriting, so we're done.
 
2831
                    return
 
2832
            if stop_revno is None:
 
2833
                if graph is None:
 
2834
                    graph = self.target.repository.get_graph()
 
2835
                this_revno, this_last_revision = \
 
2836
                        self.target.last_revision_info()
 
2837
                stop_revno = graph.find_distance_to_null(stop_revision,
 
2838
                                [(other_last_revision, other_revno),
 
2839
                                 (this_last_revision, this_revno)])
 
2840
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
2841
        finally:
 
2842
            self.source.unlock()
 
2843
 
 
2844
    @classmethod
 
2845
    def is_compatible(self, source, target):
 
2846
        # GenericBranch uses the public API, so always compatible
 
2847
        return True
 
2848
 
 
2849
 
 
2850
InterBranch.register_optimiser(GenericInterBranch)