~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Robert Collins
  • Date: 2007-07-04 08:08:13 UTC
  • mfrom: (2572 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2587.
  • Revision ID: robertc@robertcollins.net-20070704080813-wzebx0r88fvwj5rq
Merge bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 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
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
from copy import deepcopy
19
18
from cStringIO import StringIO
20
 
from unittest import TestSuite
 
19
 
 
20
from bzrlib.lazy_import import lazy_import
 
21
lazy_import(globals(), """
21
22
from warnings import warn
22
23
 
23
24
import bzrlib
24
25
from bzrlib import (
25
26
        bzrdir,
26
27
        cache_utf8,
 
28
        config as _mod_config,
27
29
        errors,
28
30
        lockdir,
 
31
        lockable_files,
29
32
        osutils,
30
 
        revision,
 
33
        revision as _mod_revision,
31
34
        transport,
32
35
        tree,
 
36
        tsort,
33
37
        ui,
34
38
        urlutils,
35
39
        )
36
 
from bzrlib.config import TreeConfig
 
40
from bzrlib.config import BranchConfig, TreeConfig
 
41
from bzrlib.lockable_files import LockableFiles, TransportLock
 
42
from bzrlib.tag import (
 
43
    BasicTags,
 
44
    DisabledTags,
 
45
    )
 
46
""")
 
47
 
37
48
from bzrlib.decorators import needs_read_lock, needs_write_lock
38
 
import bzrlib.errors as errors
39
 
from bzrlib.errors import (BzrError, BzrCheckError, DivergedBranches, 
40
 
                           HistoryMissing, InvalidRevisionId, 
41
 
                           InvalidRevisionNumber, LockError, NoSuchFile, 
 
49
from bzrlib.errors import (BzrError, BzrCheckError, DivergedBranches,
 
50
                           HistoryMissing, InvalidRevisionId,
 
51
                           InvalidRevisionNumber, LockError, NoSuchFile,
42
52
                           NoSuchRevision, NoWorkingTree, NotVersionedError,
43
 
                           NotBranchError, UninitializableFormat, 
44
 
                           UnlistableStore, UnlistableBranch, 
 
53
                           NotBranchError, UninitializableFormat,
 
54
                           UnlistableStore, UnlistableBranch,
45
55
                           )
46
 
from bzrlib.lockable_files import LockableFiles, TransportLock
 
56
from bzrlib.hooks import Hooks
47
57
from bzrlib.symbol_versioning import (deprecated_function,
48
58
                                      deprecated_method,
49
59
                                      DEPRECATED_PARAMETER,
50
60
                                      deprecated_passed,
51
 
                                      zero_eight, zero_nine,
 
61
                                      zero_eight, zero_nine, zero_sixteen,
52
62
                                      )
53
63
from bzrlib.trace import mutter, note
54
64
 
55
65
 
56
66
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
57
67
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
58
 
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
 
68
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
59
69
 
60
70
 
61
71
# TODO: Maybe include checks for common corruption of newlines, etc?
75
85
 
76
86
    base
77
87
        Base directory/url of the branch.
 
88
 
 
89
    hooks: An instance of BranchHooks.
78
90
    """
79
91
    # this is really an instance variable - FIXME move it there
80
92
    # - RBC 20060112
81
93
    base = None
82
94
 
 
95
    # override this to set the strategy for storing tags
 
96
    def _make_tags(self):
 
97
        return DisabledTags(self)
 
98
 
83
99
    def __init__(self, *ignored, **ignored_too):
84
 
        raise NotImplementedError('The Branch class is abstract')
 
100
        self.tags = self._make_tags()
 
101
        self._revision_history_cache = None
 
102
        self._revision_id_to_revno_cache = None
85
103
 
86
104
    def break_lock(self):
87
105
        """Break a lock if one is present from another instance.
148
166
        pass
149
167
 
150
168
    def get_config(self):
151
 
        return bzrlib.config.BranchConfig(self)
 
169
        return BranchConfig(self)
152
170
 
153
171
    def _get_nick(self):
154
172
        return self.get_config().get_nickname()
177
195
    def get_physical_lock_status(self):
178
196
        raise NotImplementedError(self.get_physical_lock_status)
179
197
 
 
198
    @needs_read_lock
 
199
    def get_revision_id_to_revno_map(self):
 
200
        """Return the revision_id => dotted revno map.
 
201
 
 
202
        This will be regenerated on demand, but will be cached.
 
203
 
 
204
        :return: A dictionary mapping revision_id => dotted revno.
 
205
            This dictionary should not be modified by the caller.
 
206
        """
 
207
        if self._revision_id_to_revno_cache is not None:
 
208
            mapping = self._revision_id_to_revno_cache
 
209
        else:
 
210
            mapping = self._gen_revno_map()
 
211
            self._cache_revision_id_to_revno(mapping)
 
212
        # TODO: jam 20070417 Since this is being cached, should we be returning
 
213
        #       a copy?
 
214
        # I would rather not, and instead just declare that users should not
 
215
        # modify the return value.
 
216
        return mapping
 
217
 
 
218
    def _gen_revno_map(self):
 
219
        """Create a new mapping from revision ids to dotted revnos.
 
220
 
 
221
        Dotted revnos are generated based on the current tip in the revision
 
222
        history.
 
223
        This is the worker function for get_revision_id_to_revno_map, which
 
224
        just caches the return value.
 
225
 
 
226
        :return: A dictionary mapping revision_id => dotted revno.
 
227
        """
 
228
        last_revision = self.last_revision()
 
229
        revision_graph = self.repository.get_revision_graph(last_revision)
 
230
        merge_sorted_revisions = tsort.merge_sort(
 
231
            revision_graph,
 
232
            last_revision,
 
233
            None,
 
234
            generate_revno=True)
 
235
        revision_id_to_revno = dict((rev_id, revno)
 
236
                                    for seq_num, rev_id, depth, revno, end_of_merge
 
237
                                     in merge_sorted_revisions)
 
238
        return revision_id_to_revno
 
239
 
 
240
    def leave_lock_in_place(self):
 
241
        """Tell this branch object not to release the physical lock when this
 
242
        object is unlocked.
 
243
        
 
244
        If lock_write doesn't return a token, then this method is not supported.
 
245
        """
 
246
        self.control_files.leave_in_place()
 
247
 
 
248
    def dont_leave_lock_in_place(self):
 
249
        """Tell this branch object to release the physical lock when this
 
250
        object is unlocked, even if it didn't originally acquire it.
 
251
 
 
252
        If lock_write doesn't return a token, then this method is not supported.
 
253
        """
 
254
        self.control_files.dont_leave_in_place()
 
255
 
180
256
    def abspath(self, name):
181
257
        """Return absolute filename for something in the branch
182
258
        
217
293
        try:
218
294
            if last_revision is None:
219
295
                pb.update('get source history')
220
 
                from_history = from_branch.revision_history()
221
 
                if from_history:
222
 
                    last_revision = from_history[-1]
223
 
                else:
224
 
                    # no history in the source branch
225
 
                    last_revision = revision.NULL_REVISION
 
296
                last_revision = from_branch.last_revision()
 
297
                if last_revision is None:
 
298
                    last_revision = _mod_revision.NULL_REVISION
226
299
            return self.repository.fetch(from_branch.repository,
227
300
                                         revision_id=last_revision,
228
301
                                         pb=nested_pb)
239
312
        """
240
313
        return None
241
314
    
 
315
    def get_old_bound_location(self):
 
316
        """Return the URL of the branch we used to be bound to
 
317
        """
 
318
        raise errors.UpgradeRequired(self.base)
 
319
 
242
320
    def get_commit_builder(self, parents, config=None, timestamp=None, 
243
321
                           timezone=None, committer=None, revprops=None, 
244
322
                           revision_id=None):
256
334
        if config is None:
257
335
            config = self.get_config()
258
336
        
259
 
        return self.repository.get_commit_builder(self, parents, config, 
 
337
        return self.repository.get_commit_builder(self, parents, config,
260
338
            timestamp, timezone, committer, revprops, revision_id)
261
339
 
262
340
    def get_master_branch(self):
278
356
            raise InvalidRevisionNumber(revno)
279
357
        return self.repository.get_revision_delta(rh[revno-1])
280
358
 
 
359
    @deprecated_method(zero_sixteen)
281
360
    def get_root_id(self):
282
 
        """Return the id of this branches root"""
 
361
        """Return the id of this branches root
 
362
 
 
363
        Deprecated: branches don't have root ids-- trees do.
 
364
        Use basis_tree().get_root_id() instead.
 
365
        """
283
366
        raise NotImplementedError(self.get_root_id)
284
367
 
285
368
    def print_file(self, file, revision_id):
292
375
    def set_revision_history(self, rev_history):
293
376
        raise NotImplementedError(self.set_revision_history)
294
377
 
 
378
    def _cache_revision_history(self, rev_history):
 
379
        """Set the cached revision history to rev_history.
 
380
 
 
381
        The revision_history method will use this cache to avoid regenerating
 
382
        the revision history.
 
383
 
 
384
        This API is semi-public; it only for use by subclasses, all other code
 
385
        should consider it to be private.
 
386
        """
 
387
        self._revision_history_cache = rev_history
 
388
 
 
389
    def _cache_revision_id_to_revno(self, revision_id_to_revno):
 
390
        """Set the cached revision_id => revno map to revision_id_to_revno.
 
391
 
 
392
        This API is semi-public; it only for use by subclasses, all other code
 
393
        should consider it to be private.
 
394
        """
 
395
        self._revision_id_to_revno_cache = revision_id_to_revno
 
396
 
 
397
    def _clear_cached_state(self):
 
398
        """Clear any cached data on this branch, e.g. cached revision history.
 
399
 
 
400
        This means the next call to revision_history will need to call
 
401
        _gen_revision_history.
 
402
 
 
403
        This API is semi-public; it only for use by subclasses, all other code
 
404
        should consider it to be private.
 
405
        """
 
406
        self._revision_history_cache = None
 
407
        self._revision_id_to_revno_cache = None
 
408
 
 
409
    def _gen_revision_history(self):
 
410
        """Return sequence of revision hashes on to this branch.
 
411
        
 
412
        Unlike revision_history, this method always regenerates or rereads the
 
413
        revision history, i.e. it does not cache the result, so repeated calls
 
414
        may be expensive.
 
415
 
 
416
        Concrete subclasses should override this instead of revision_history so
 
417
        that subclasses do not need to deal with caching logic.
 
418
        
 
419
        This API is semi-public; it only for use by subclasses, all other code
 
420
        should consider it to be private.
 
421
        """
 
422
        raise NotImplementedError(self._gen_revision_history)
 
423
 
 
424
    @needs_read_lock
295
425
    def revision_history(self):
296
 
        """Return sequence of revision hashes on to this branch."""
297
 
        raise NotImplementedError(self.revision_history)
 
426
        """Return sequence of revision hashes on to this branch.
 
427
        
 
428
        This method will cache the revision history for as long as it is safe to
 
429
        do so.
 
430
        """
 
431
        if self._revision_history_cache is not None:
 
432
            history = self._revision_history_cache
 
433
        else:
 
434
            history = self._gen_revision_history()
 
435
            self._cache_revision_history(history)
 
436
        return list(history)
298
437
 
299
438
    def revno(self):
300
439
        """Return current revision number for this branch.
308
447
        """Older format branches cannot bind or unbind."""
309
448
        raise errors.UpgradeRequired(self.base)
310
449
 
 
450
    def set_append_revisions_only(self, enabled):
 
451
        """Older format branches are never restricted to append-only"""
 
452
        raise errors.UpgradeRequired(self.base)
 
453
 
311
454
    def last_revision(self):
312
455
        """Return last revision id, or None"""
313
456
        ph = self.revision_history()
316
459
        else:
317
460
            return None
318
461
 
 
462
    def last_revision_info(self):
 
463
        """Return information about the last revision.
 
464
 
 
465
        :return: A tuple (revno, last_revision_id).
 
466
        """
 
467
        rh = self.revision_history()
 
468
        revno = len(rh)
 
469
        if revno:
 
470
            return (revno, rh[-1])
 
471
        else:
 
472
            return (0, _mod_revision.NULL_REVISION)
 
473
 
319
474
    def missing_revisions(self, other, stop_revision=None):
320
475
        """Return a list of new revisions that would perfectly fit.
321
476
        
352
507
        """Given a revision id, return its revno"""
353
508
        if revision_id is None:
354
509
            return 0
 
510
        revision_id = osutils.safe_revision_id(revision_id)
355
511
        history = self.revision_history()
356
512
        try:
357
513
            return history.index(revision_id) + 1
358
514
        except ValueError:
359
 
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
515
            raise errors.NoSuchRevision(self, revision_id)
360
516
 
361
517
    def get_rev_id(self, revno, history=None):
362
518
        """Find the revision id of the specified revno."""
365
521
        if history is None:
366
522
            history = self.revision_history()
367
523
        if revno <= 0 or revno > len(history):
368
 
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
524
            raise errors.NoSuchRevision(self, revno)
369
525
        return history[revno - 1]
370
526
 
371
527
    def pull(self, source, overwrite=False, stop_revision=None):
 
528
        """Mirror source into this branch.
 
529
 
 
530
        This branch is considered to be 'local', having low latency.
 
531
 
 
532
        :returns: PullResult instance
 
533
        """
372
534
        raise NotImplementedError(self.pull)
373
535
 
 
536
    def push(self, target, overwrite=False, stop_revision=None):
 
537
        """Mirror this branch into target.
 
538
 
 
539
        This branch is considered to be 'local', having low latency.
 
540
        """
 
541
        raise NotImplementedError(self.push)
 
542
 
374
543
    def basis_tree(self):
375
544
        """Return `Tree` object for last revision."""
376
545
        return self.repository.revision_tree(self.last_revision())
407
576
        """
408
577
        raise NotImplementedError(self.get_parent)
409
578
 
 
579
    def _set_config_location(self, name, url, config=None,
 
580
                             make_relative=False):
 
581
        if config is None:
 
582
            config = self.get_config()
 
583
        if url is None:
 
584
            url = ''
 
585
        elif make_relative:
 
586
            url = urlutils.relative_url(self.base, url)
 
587
        config.set_user_option(name, url)
 
588
 
 
589
    def _get_config_location(self, name, config=None):
 
590
        if config is None:
 
591
            config = self.get_config()
 
592
        location = config.get_user_option(name)
 
593
        if location == '':
 
594
            location = None
 
595
        return location
 
596
 
410
597
    def get_submit_branch(self):
411
598
        """Return the submit location of the branch.
412
599
 
425
612
        """
426
613
        self.get_config().set_user_option('submit_branch', location)
427
614
 
 
615
    def get_public_branch(self):
 
616
        """Return the public location of the branch.
 
617
 
 
618
        This is is used by merge directives.
 
619
        """
 
620
        return self._get_config_location('public_branch')
 
621
 
 
622
    def set_public_branch(self, location):
 
623
        """Return the submit location of the branch.
 
624
 
 
625
        This is the default location for bundle.  The usual
 
626
        pattern is that the user can override it by specifying a
 
627
        location.
 
628
        """
 
629
        self._set_config_location('public_branch', location)
 
630
 
428
631
    def get_push_location(self):
429
632
        """Return the None or the location to push this branch to."""
430
 
        raise NotImplementedError(self.get_push_location)
 
633
        push_loc = self.get_config().get_user_option('push_location')
 
634
        return push_loc
431
635
 
432
636
    def set_push_location(self, location):
433
637
        """Set a new push location for this branch."""
461
665
            raise InvalidRevisionNumber(revno)
462
666
 
463
667
    @needs_read_lock
464
 
    def clone(self, *args, **kwargs):
 
668
    def clone(self, to_bzrdir, revision_id=None):
465
669
        """Clone this branch into to_bzrdir preserving all semantic values.
466
670
        
467
671
        revision_id: if not None, the revision history in the new branch will
468
672
                     be truncated to end with revision_id.
469
673
        """
470
 
        # for API compatibility, until 0.8 releases we provide the old api:
471
 
        # def clone(self, to_location, revision=None, basis_branch=None, to_branch_format=None):
472
 
        # after 0.8 releases, the *args and **kwargs should be changed:
473
 
        # def clone(self, to_bzrdir, revision_id=None):
474
 
        if (kwargs.get('to_location', None) or
475
 
            kwargs.get('revision', None) or
476
 
            kwargs.get('basis_branch', None) or
477
 
            (len(args) and isinstance(args[0], basestring))):
478
 
            # backwards compatibility api:
479
 
            warn("Branch.clone() has been deprecated for BzrDir.clone() from"
480
 
                 " bzrlib 0.8.", DeprecationWarning, stacklevel=3)
481
 
            # get basis_branch
482
 
            if len(args) > 2:
483
 
                basis_branch = args[2]
484
 
            else:
485
 
                basis_branch = kwargs.get('basis_branch', None)
486
 
            if basis_branch:
487
 
                basis = basis_branch.bzrdir
488
 
            else:
489
 
                basis = None
490
 
            # get revision
491
 
            if len(args) > 1:
492
 
                revision_id = args[1]
493
 
            else:
494
 
                revision_id = kwargs.get('revision', None)
495
 
            # get location
496
 
            if len(args):
497
 
                url = args[0]
498
 
            else:
499
 
                # no default to raise if not provided.
500
 
                url = kwargs.get('to_location')
501
 
            return self.bzrdir.clone(url,
502
 
                                     revision_id=revision_id,
503
 
                                     basis=basis).open_branch()
504
 
        # new cleaner api.
505
 
        # generate args by hand 
506
 
        if len(args) > 1:
507
 
            revision_id = args[1]
508
 
        else:
509
 
            revision_id = kwargs.get('revision_id', None)
510
 
        if len(args):
511
 
            to_bzrdir = args[0]
512
 
        else:
513
 
            # no default to raise if not provided.
514
 
            to_bzrdir = kwargs.get('to_bzrdir')
515
674
        result = self._format.initialize(to_bzrdir)
516
675
        self.copy_content_into(result, revision_id=revision_id)
517
676
        return  result
528
687
        result.set_parent(self.bzrdir.root_transport.base)
529
688
        return result
530
689
 
531
 
    @needs_read_lock
532
 
    def copy_content_into(self, destination, revision_id=None):
533
 
        """Copy the content of self into destination.
534
 
 
535
 
        revision_id: if not None, the revision history in the new branch will
536
 
                     be truncated to end with revision_id.
 
690
    def _synchronize_history(self, destination, revision_id):
 
691
        """Synchronize last revision and revision history between branches.
 
692
 
 
693
        This version is most efficient when the destination is also a
 
694
        BzrBranch5, but works for BzrBranch6 as long as the revision
 
695
        history is the true lefthand parent history, and all of the revisions
 
696
        are in the destination's repository.  If not, set_revision_history
 
697
        will fail.
 
698
 
 
699
        :param destination: The branch to copy the history into
 
700
        :param revision_id: The revision-id to truncate history at.  May
 
701
          be None to copy complete history.
537
702
        """
538
703
        new_history = self.revision_history()
539
704
        if revision_id is not None:
 
705
            revision_id = osutils.safe_revision_id(revision_id)
540
706
            try:
541
707
                new_history = new_history[:new_history.index(revision_id) + 1]
542
708
            except ValueError:
543
709
                rev = self.repository.get_revision(revision_id)
544
710
                new_history = rev.get_history(self.repository)[1:]
545
711
        destination.set_revision_history(new_history)
 
712
 
 
713
    @needs_read_lock
 
714
    def copy_content_into(self, destination, revision_id=None):
 
715
        """Copy the content of self into destination.
 
716
 
 
717
        revision_id: if not None, the revision history in the new branch will
 
718
                     be truncated to end with revision_id.
 
719
        """
 
720
        self._synchronize_history(destination, revision_id)
546
721
        try:
547
722
            parent = self.get_parent()
548
723
        except errors.InaccessibleParent, e:
550
725
        else:
551
726
            if parent:
552
727
                destination.set_parent(parent)
 
728
        self.tags.merge_to(destination.tags)
553
729
 
554
730
    @needs_read_lock
555
731
    def check(self):
583
759
 
584
760
    def _get_checkout_format(self):
585
761
        """Return the most suitable metadir for a checkout of this branch.
586
 
        Weaves are used if this branch's repostory uses weaves.
 
762
        Weaves are used if this branch's repository uses weaves.
587
763
        """
588
764
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
589
 
            from bzrlib import repository
 
765
            from bzrlib.repofmt import weaverepo
590
766
            format = bzrdir.BzrDirMetaFormat1()
591
 
            format.repository_format = repository.RepositoryFormat7()
 
767
            format.repository_format = weaverepo.RepositoryFormat7()
592
768
        else:
593
 
            format = self.repository.bzrdir.cloning_metadir()
 
769
            format = self.repository.bzrdir.checkout_metadir()
 
770
            format.set_branch_format(self._format)
594
771
        return format
595
772
 
596
 
    def create_checkout(self, to_location, revision_id=None, 
 
773
    def create_checkout(self, to_location, revision_id=None,
597
774
                        lightweight=False):
598
775
        """Create a checkout of a branch.
599
776
        
604
781
        :return: The tree of the created checkout
605
782
        """
606
783
        t = transport.get_transport(to_location)
607
 
        try:
608
 
            t.mkdir('.')
609
 
        except errors.FileExists:
610
 
            pass
 
784
        t.ensure_base()
611
785
        if lightweight:
612
 
            checkout = bzrdir.BzrDirMetaFormat1().initialize_on_transport(t)
 
786
            format = self._get_checkout_format()
 
787
            checkout = format.initialize_on_transport(t)
613
788
            BranchReferenceFormat().initialize(checkout, self)
614
789
        else:
615
790
            format = self._get_checkout_format()
620
795
            # pull up to the specified revision_id to set the initial 
621
796
            # branch tip correctly, and seed it with history.
622
797
            checkout_branch.pull(self, stop_revision=revision_id)
623
 
        return checkout.create_workingtree(revision_id)
 
798
        tree = checkout.create_workingtree(revision_id)
 
799
        basis_tree = tree.basis_tree()
 
800
        basis_tree.lock_read()
 
801
        try:
 
802
            for path, file_id in basis_tree.iter_references():
 
803
                reference_parent = self.reference_parent(file_id, path)
 
804
                reference_parent.create_checkout(tree.abspath(path),
 
805
                    basis_tree.get_reference_revision(file_id, path),
 
806
                    lightweight)
 
807
        finally:
 
808
            basis_tree.unlock()
 
809
        return tree
 
810
 
 
811
    def reference_parent(self, file_id, path):
 
812
        """Return the parent branch for a tree-reference file_id
 
813
        :param file_id: The file_id of the tree reference
 
814
        :param path: The path of the file_id in the tree
 
815
        :return: A branch associated with the file_id
 
816
        """
 
817
        # FIXME should provide multiple branches, based on config
 
818
        return Branch.open(self.bzrdir.root_transport.clone(path).base)
 
819
 
 
820
    def supports_tags(self):
 
821
        return self._format.supports_tags()
624
822
 
625
823
 
626
824
class BranchFormat(object):
647
845
    _formats = {}
648
846
    """The known formats."""
649
847
 
 
848
    def __eq__(self, other):
 
849
        return self.__class__ is other.__class__
 
850
 
 
851
    def __ne__(self, other):
 
852
        return not (self == other)
 
853
 
650
854
    @classmethod
651
855
    def find_format(klass, a_bzrdir):
652
856
        """Return the format for the branch object in a_bzrdir."""
664
868
        """Return the current default format."""
665
869
        return klass._default_format
666
870
 
 
871
    def get_reference(self, a_bzrdir):
 
872
        """Get the target reference of the branch in a_bzrdir.
 
873
 
 
874
        format probing must have been completed before calling
 
875
        this method - it is assumed that the format of the branch
 
876
        in a_bzrdir is correct.
 
877
 
 
878
        :param a_bzrdir: The bzrdir to get the branch data from.
 
879
        :return: None if the branch is not a reference branch.
 
880
        """
 
881
        return None
 
882
 
667
883
    def get_format_string(self):
668
884
        """Return the ASCII format string that identifies this format."""
669
885
        raise NotImplementedError(self.get_format_string)
670
886
 
671
887
    def get_format_description(self):
672
888
        """Return the short format description for this format."""
673
 
        raise NotImplementedError(self.get_format_string)
 
889
        raise NotImplementedError(self.get_format_description)
 
890
 
 
891
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
892
                           set_format=True):
 
893
        """Initialize a branch in a bzrdir, with specified files
 
894
 
 
895
        :param a_bzrdir: The bzrdir to initialize the branch in
 
896
        :param utf8_files: The files to create as a list of
 
897
            (filename, content) tuples
 
898
        :param set_format: If True, set the format with
 
899
            self.get_format_string.  (BzrBranch4 has its format set
 
900
            elsewhere)
 
901
        :return: a branch in this format
 
902
        """
 
903
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
904
        branch_transport = a_bzrdir.get_branch_transport(self)
 
905
        lock_map = {
 
906
            'metadir': ('lock', lockdir.LockDir),
 
907
            'branch4': ('branch-lock', lockable_files.TransportLock),
 
908
        }
 
909
        lock_name, lock_class = lock_map[lock_type]
 
910
        control_files = lockable_files.LockableFiles(branch_transport,
 
911
            lock_name, lock_class)
 
912
        control_files.create_lock()
 
913
        control_files.lock_write()
 
914
        if set_format:
 
915
            control_files.put_utf8('format', self.get_format_string())
 
916
        try:
 
917
            for file, content in utf8_files:
 
918
                control_files.put_utf8(file, content)
 
919
        finally:
 
920
            control_files.unlock()
 
921
        return self.open(a_bzrdir, _found=True)
674
922
 
675
923
    def initialize(self, a_bzrdir):
676
924
        """Create a branch of this format in a_bzrdir."""
709
957
    def __str__(self):
710
958
        return self.get_format_string().rstrip()
711
959
 
 
960
    def supports_tags(self):
 
961
        """True if this format supports tags stored in the branch"""
 
962
        return False  # by default
 
963
 
 
964
    # XXX: Probably doesn't really belong here -- mbp 20070212
 
965
    def _initialize_control_files(self, a_bzrdir, utf8_files, lock_filename,
 
966
            lock_class):
 
967
        branch_transport = a_bzrdir.get_branch_transport(self)
 
968
        control_files = lockable_files.LockableFiles(branch_transport,
 
969
            lock_filename, lock_class)
 
970
        control_files.create_lock()
 
971
        control_files.lock_write()
 
972
        try:
 
973
            for filename, content in utf8_files:
 
974
                control_files.put_utf8(filename, content)
 
975
        finally:
 
976
            control_files.unlock()
 
977
 
 
978
 
 
979
class BranchHooks(Hooks):
 
980
    """A dictionary mapping hook name to a list of callables for branch hooks.
 
981
    
 
982
    e.g. ['set_rh'] Is the list of items to be called when the
 
983
    set_revision_history function is invoked.
 
984
    """
 
985
 
 
986
    def __init__(self):
 
987
        """Create the default hooks.
 
988
 
 
989
        These are all empty initially, because by default nothing should get
 
990
        notified.
 
991
        """
 
992
        Hooks.__init__(self)
 
993
        # Introduced in 0.15:
 
994
        # invoked whenever the revision history has been set
 
995
        # with set_revision_history. The api signature is
 
996
        # (branch, revision_history), and the branch will
 
997
        # be write-locked.
 
998
        self['set_rh'] = []
 
999
        # invoked after a push operation completes.
 
1000
        # the api signature is
 
1001
        # (push_result)
 
1002
        # containing the members
 
1003
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
 
1004
        # where local is the local target branch or None, master is the target 
 
1005
        # master branch, and the rest should be self explanatory. The source
 
1006
        # is read locked and the target branches write locked. Source will
 
1007
        # be the local low-latency branch.
 
1008
        self['post_push'] = []
 
1009
        # invoked after a pull operation completes.
 
1010
        # the api signature is
 
1011
        # (pull_result)
 
1012
        # containing the members
 
1013
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
 
1014
        # where local is the local branch or None, master is the target 
 
1015
        # master branch, and the rest should be self explanatory. The source
 
1016
        # is read locked and the target branches write locked. The local
 
1017
        # branch is the low-latency branch.
 
1018
        self['post_pull'] = []
 
1019
        # invoked after a commit operation completes.
 
1020
        # the api signature is 
 
1021
        # (local, master, old_revno, old_revid, new_revno, new_revid)
 
1022
        # old_revid is NULL_REVISION for the first commit to a branch.
 
1023
        self['post_commit'] = []
 
1024
        # invoked after a uncommit operation completes.
 
1025
        # the api signature is
 
1026
        # (local, master, old_revno, old_revid, new_revno, new_revid) where
 
1027
        # local is the local branch or None, master is the target branch,
 
1028
        # and an empty branch recieves new_revno of 0, new_revid of None.
 
1029
        self['post_uncommit'] = []
 
1030
 
 
1031
 
 
1032
# install the default hooks into the Branch class.
 
1033
Branch.hooks = BranchHooks()
 
1034
 
712
1035
 
713
1036
class BzrBranchFormat4(BranchFormat):
714
1037
    """Bzr branch format 4.
724
1047
 
725
1048
    def initialize(self, a_bzrdir):
726
1049
        """Create a branch of this format in a_bzrdir."""
727
 
        mutter('creating branch in %s', a_bzrdir.transport.base)
728
 
        branch_transport = a_bzrdir.get_branch_transport(self)
729
1050
        utf8_files = [('revision-history', ''),
730
1051
                      ('branch-name', ''),
731
1052
                      ]
732
 
        control_files = LockableFiles(branch_transport, 'branch-lock',
733
 
                                      TransportLock)
734
 
        control_files.create_lock()
735
 
        control_files.lock_write()
736
 
        try:
737
 
            for file, content in utf8_files:
738
 
                control_files.put_utf8(file, content)
739
 
        finally:
740
 
            control_files.unlock()
741
 
        return self.open(a_bzrdir, _found=True)
 
1053
        return self._initialize_helper(a_bzrdir, utf8_files,
 
1054
                                       lock_type='branch4', set_format=False)
742
1055
 
743
1056
    def __init__(self):
744
1057
        super(BzrBranchFormat4, self).__init__()
785
1098
        
786
1099
    def initialize(self, a_bzrdir):
787
1100
        """Create a branch of this format in a_bzrdir."""
788
 
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
789
 
        branch_transport = a_bzrdir.get_branch_transport(self)
790
1101
        utf8_files = [('revision-history', ''),
791
1102
                      ('branch-name', ''),
792
1103
                      ]
793
 
        control_files = LockableFiles(branch_transport, 'lock', lockdir.LockDir)
794
 
        control_files.create_lock()
795
 
        control_files.lock_write()
796
 
        control_files.put_utf8('format', self.get_format_string())
797
 
        try:
798
 
            for file, content in utf8_files:
799
 
                control_files.put_utf8(file, content)
800
 
        finally:
801
 
            control_files.unlock()
802
 
        return self.open(a_bzrdir, _found=True, )
 
1104
        return self._initialize_helper(a_bzrdir, utf8_files)
803
1105
 
804
1106
    def __init__(self):
805
1107
        super(BzrBranchFormat5, self).__init__()
814
1116
        if not _found:
815
1117
            format = BranchFormat.find_format(a_bzrdir)
816
1118
            assert format.__class__ == self.__class__
 
1119
        try:
 
1120
            transport = a_bzrdir.get_branch_transport(None)
 
1121
            control_files = lockable_files.LockableFiles(transport, 'lock',
 
1122
                                                         lockdir.LockDir)
 
1123
            return BzrBranch5(_format=self,
 
1124
                              _control_files=control_files,
 
1125
                              a_bzrdir=a_bzrdir,
 
1126
                              _repository=a_bzrdir.find_repository())
 
1127
        except NoSuchFile:
 
1128
            raise NotBranchError(path=transport.base)
 
1129
 
 
1130
 
 
1131
class BzrBranchFormat6(BzrBranchFormat5):
 
1132
    """Branch format with last-revision
 
1133
 
 
1134
    Unlike previous formats, this has no explicit revision history. Instead,
 
1135
    this just stores the last-revision, and the left-hand history leading
 
1136
    up to there is the history.
 
1137
 
 
1138
    This format was introduced in bzr 0.15
 
1139
    """
 
1140
 
 
1141
    def get_format_string(self):
 
1142
        """See BranchFormat.get_format_string()."""
 
1143
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
 
1144
 
 
1145
    def get_format_description(self):
 
1146
        """See BranchFormat.get_format_description()."""
 
1147
        return "Branch format 6"
 
1148
 
 
1149
    def initialize(self, a_bzrdir):
 
1150
        """Create a branch of this format in a_bzrdir."""
 
1151
        utf8_files = [('last-revision', '0 null:\n'),
 
1152
                      ('branch-name', ''),
 
1153
                      ('branch.conf', ''),
 
1154
                      ('tags', ''),
 
1155
                      ]
 
1156
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1157
 
 
1158
    def open(self, a_bzrdir, _found=False):
 
1159
        """Return the branch object for a_bzrdir
 
1160
 
 
1161
        _found is a private parameter, do not use it. It is used to indicate
 
1162
               if format probing has already be done.
 
1163
        """
 
1164
        if not _found:
 
1165
            format = BranchFormat.find_format(a_bzrdir)
 
1166
            assert format.__class__ == self.__class__
817
1167
        transport = a_bzrdir.get_branch_transport(None)
818
 
        control_files = LockableFiles(transport, 'lock', lockdir.LockDir)
819
 
        return BzrBranch5(_format=self,
 
1168
        control_files = lockable_files.LockableFiles(transport, 'lock',
 
1169
                                                     lockdir.LockDir)
 
1170
        return BzrBranch6(_format=self,
820
1171
                          _control_files=control_files,
821
1172
                          a_bzrdir=a_bzrdir,
822
1173
                          _repository=a_bzrdir.find_repository())
823
1174
 
824
 
    def __str__(self):
825
 
        return "Bazaar-NG Metadir branch format 5"
 
1175
    def supports_tags(self):
 
1176
        return True
826
1177
 
827
1178
 
828
1179
class BranchReferenceFormat(BranchFormat):
844
1195
        """See BranchFormat.get_format_description()."""
845
1196
        return "Checkout reference format 1"
846
1197
        
 
1198
    def get_reference(self, a_bzrdir):
 
1199
        """See BranchFormat.get_reference()."""
 
1200
        transport = a_bzrdir.get_branch_transport(None)
 
1201
        return transport.get('location').read()
 
1202
 
847
1203
    def initialize(self, a_bzrdir, target_branch=None):
848
1204
        """Create a branch of this format in a_bzrdir."""
849
1205
        if target_branch is None:
871
1227
            # emit some sort of warning/error to the caller ?!
872
1228
        return clone
873
1229
 
874
 
    def open(self, a_bzrdir, _found=False):
 
1230
    def open(self, a_bzrdir, _found=False, location=None):
875
1231
        """Return the branch that the branch reference in a_bzrdir points at.
876
1232
 
877
1233
        _found is a private parameter, do not use it. It is used to indicate
880
1236
        if not _found:
881
1237
            format = BranchFormat.find_format(a_bzrdir)
882
1238
            assert format.__class__ == self.__class__
883
 
        transport = a_bzrdir.get_branch_transport(None)
884
 
        real_bzrdir = bzrdir.BzrDir.open(transport.get('location').read())
 
1239
        if location is None:
 
1240
            location = self.get_reference(a_bzrdir)
 
1241
        real_bzrdir = bzrdir.BzrDir.open(location)
885
1242
        result = real_bzrdir.open_branch()
886
1243
        # this changes the behaviour of result.clone to create a new reference
887
1244
        # rather than a copy of the content of the branch.
900
1257
__default_format = BzrBranchFormat5()
901
1258
BranchFormat.register_format(__default_format)
902
1259
BranchFormat.register_format(BranchReferenceFormat())
 
1260
BranchFormat.register_format(BzrBranchFormat6())
903
1261
BranchFormat.set_default_format(__default_format)
904
1262
_legacy_formats = [BzrBranchFormat4(),
905
1263
                   ]
912
1270
    it's writable, and can be accessed via the normal filesystem API.
913
1271
    """
914
1272
    
915
 
    def __init__(self, transport=DEPRECATED_PARAMETER, init=DEPRECATED_PARAMETER,
916
 
                 relax_version_check=DEPRECATED_PARAMETER, _format=None,
 
1273
    def __init__(self, _format=None,
917
1274
                 _control_files=None, a_bzrdir=None, _repository=None):
918
 
        """Create new branch object at a particular location.
919
 
 
920
 
        transport -- A Transport object, defining how to access files.
921
 
        
922
 
        init -- If True, create new control files in a previously
923
 
             unversioned directory.  If False, the branch must already
924
 
             be versioned.
925
 
 
926
 
        relax_version_check -- If true, the usual check for the branch
927
 
            version is not applied.  This is intended only for
928
 
            upgrade/recovery type use; it's not guaranteed that
929
 
            all operations will work on old format branches.
930
 
        """
 
1275
        """Create new branch object at a particular location."""
 
1276
        Branch.__init__(self)
931
1277
        if a_bzrdir is None:
932
 
            self.bzrdir = bzrdir.BzrDir.open(transport.base)
 
1278
            raise ValueError('a_bzrdir must be supplied')
933
1279
        else:
934
1280
            self.bzrdir = a_bzrdir
935
 
        self._transport = self.bzrdir.transport.clone('..')
936
 
        self._base = self._transport.base
 
1281
        # self._transport used to point to the directory containing the
 
1282
        # control directory, but was not used - now it's just the transport
 
1283
        # for the branch control files.  mbp 20070212
 
1284
        self._base = self.bzrdir.transport.clone('..').base
937
1285
        self._format = _format
938
1286
        if _control_files is None:
939
1287
            raise ValueError('BzrBranch _control_files is None')
940
1288
        self.control_files = _control_files
941
 
        if deprecated_passed(init):
942
 
            warn("BzrBranch.__init__(..., init=XXX): The init parameter is "
943
 
                 "deprecated as of bzr 0.8. Please use Branch.create().",
944
 
                 DeprecationWarning,
945
 
                 stacklevel=2)
946
 
            if init:
947
 
                # this is slower than before deprecation, oh well never mind.
948
 
                # -> its deprecated.
949
 
                self._initialize(transport.base)
950
 
        self._check_format(_format)
951
 
        if deprecated_passed(relax_version_check):
952
 
            warn("BzrBranch.__init__(..., relax_version_check=XXX_: The "
953
 
                 "relax_version_check parameter is deprecated as of bzr 0.8. "
954
 
                 "Please use BzrDir.open_downlevel, or a BzrBranchFormat's "
955
 
                 "open() method.",
956
 
                 DeprecationWarning,
957
 
                 stacklevel=2)
958
 
            if (not relax_version_check
959
 
                and not self._format.is_supported()):
960
 
                raise errors.UnsupportedFormatError(format=fmt)
961
 
        if deprecated_passed(transport):
962
 
            warn("BzrBranch.__init__(transport=XXX...): The transport "
963
 
                 "parameter is deprecated as of bzr 0.8. "
964
 
                 "Please use Branch.open, or bzrdir.open_branch().",
965
 
                 DeprecationWarning,
966
 
                 stacklevel=2)
 
1289
        self._transport = _control_files._transport
967
1290
        self.repository = _repository
968
1291
 
969
1292
    def __str__(self):
972
1295
    __repr__ = __str__
973
1296
 
974
1297
    def _get_base(self):
 
1298
        """Returns the directory containing the control directory."""
975
1299
        return self._base
976
1300
 
977
1301
    base = property(_get_base, doc="The URL for the root of this branch.")
978
1302
 
979
 
    def _finish_transaction(self):
980
 
        """Exit the current transaction."""
981
 
        return self.control_files._finish_transaction()
982
 
 
983
 
    def get_transaction(self):
984
 
        """Return the current active transaction.
985
 
 
986
 
        If no transaction is active, this returns a passthrough object
987
 
        for which all data is immediately flushed and no caching happens.
988
 
        """
989
 
        # this is an explicit function so that we can do tricky stuff
990
 
        # when the storage in rev_storage is elsewhere.
991
 
        # we probably need to hook the two 'lock a location' and 
992
 
        # 'have a transaction' together more delicately, so that
993
 
        # we can have two locks (branch and storage) and one transaction
994
 
        # ... and finishing the transaction unlocks both, but unlocking
995
 
        # does not. - RBC 20051121
996
 
        return self.control_files.get_transaction()
997
 
 
998
 
    def _set_transaction(self, transaction):
999
 
        """Set a new active transaction."""
1000
 
        return self.control_files._set_transaction(transaction)
1001
 
 
1002
1303
    def abspath(self, name):
1003
1304
        """See Branch.abspath."""
1004
1305
        return self.control_files._transport.abspath(name)
1005
1306
 
1006
 
    def _check_format(self, format):
1007
 
        """Identify the branch format if needed.
1008
 
 
1009
 
        The format is stored as a reference to the format object in
1010
 
        self._format for code that needs to check it later.
1011
 
 
1012
 
        The format parameter is either None or the branch format class
1013
 
        used to open this branch.
1014
 
 
1015
 
        FIXME: DELETE THIS METHOD when pre 0.8 support is removed.
1016
 
        """
1017
 
        if format is None:
1018
 
            format = BranchFormat.find_format(self.bzrdir)
1019
 
        self._format = format
1020
 
        mutter("got branch format %s", self._format)
1021
 
 
 
1307
 
 
1308
    @deprecated_method(zero_sixteen)
1022
1309
    @needs_read_lock
1023
1310
    def get_root_id(self):
1024
1311
        """See Branch.get_root_id."""
1028
1315
    def is_locked(self):
1029
1316
        return self.control_files.is_locked()
1030
1317
 
1031
 
    def lock_write(self):
1032
 
        self.repository.lock_write()
 
1318
    def lock_write(self, token=None):
 
1319
        repo_token = self.repository.lock_write()
1033
1320
        try:
1034
 
            self.control_files.lock_write()
 
1321
            token = self.control_files.lock_write(token=token)
1035
1322
        except:
1036
1323
            self.repository.unlock()
1037
1324
            raise
 
1325
        return token
1038
1326
 
1039
1327
    def lock_read(self):
1040
1328
        self.repository.lock_read()
1050
1338
            self.control_files.unlock()
1051
1339
        finally:
1052
1340
            self.repository.unlock()
 
1341
        if not self.control_files.is_locked():
 
1342
            # we just released the lock
 
1343
            self._clear_cached_state()
1053
1344
        
1054
1345
    def peek_lock_mode(self):
1055
1346
        if self.control_files._lock_count == 0:
1068
1359
    @needs_write_lock
1069
1360
    def append_revision(self, *revision_ids):
1070
1361
        """See Branch.append_revision."""
 
1362
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1071
1363
        for revision_id in revision_ids:
 
1364
            _mod_revision.check_not_reserved_id(revision_id)
1072
1365
            mutter("add {%s} to revision-history" % revision_id)
1073
1366
        rev_history = self.revision_history()
1074
1367
        rev_history.extend(revision_ids)
1075
1368
        self.set_revision_history(rev_history)
1076
1369
 
 
1370
    def _write_revision_history(self, history):
 
1371
        """Factored out of set_revision_history.
 
1372
 
 
1373
        This performs the actual writing to disk.
 
1374
        It is intended to be called by BzrBranch5.set_revision_history."""
 
1375
        self.control_files.put_bytes(
 
1376
            'revision-history', '\n'.join(history))
 
1377
 
1077
1378
    @needs_write_lock
1078
1379
    def set_revision_history(self, rev_history):
1079
1380
        """See Branch.set_revision_history."""
1080
 
        self.control_files.put_utf8(
1081
 
            'revision-history', '\n'.join(rev_history))
1082
 
        transaction = self.get_transaction()
1083
 
        history = transaction.map.find_revision_history()
1084
 
        if history is not None:
1085
 
            # update the revision history in the identity map.
1086
 
            history[:] = list(rev_history)
1087
 
            # this call is disabled because revision_history is 
1088
 
            # not really an object yet, and the transaction is for objects.
1089
 
            # transaction.register_dirty(history)
1090
 
        else:
1091
 
            transaction.map.add_revision_history(rev_history)
1092
 
            # this call is disabled because revision_history is 
1093
 
            # not really an object yet, and the transaction is for objects.
1094
 
            # transaction.register_clean(history)
1095
 
 
1096
 
    @needs_read_lock
1097
 
    def revision_history(self):
1098
 
        """See Branch.revision_history."""
1099
 
        transaction = self.get_transaction()
1100
 
        history = transaction.map.find_revision_history()
1101
 
        if history is not None:
1102
 
            # mutter("cache hit for revision-history in %s", self)
1103
 
            return list(history)
1104
 
        decode_utf8 = cache_utf8.decode
1105
 
        history = [decode_utf8(l.rstrip('\r\n')) for l in
1106
 
                self.control_files.get('revision-history').readlines()]
1107
 
        transaction.map.add_revision_history(history)
1108
 
        # this call is disabled because revision_history is 
1109
 
        # not really an object yet, and the transaction is for objects.
1110
 
        # transaction.register_clean(history, precious=True)
1111
 
        return list(history)
 
1381
        rev_history = [osutils.safe_revision_id(r) for r in rev_history]
 
1382
        self._clear_cached_state()
 
1383
        self._write_revision_history(rev_history)
 
1384
        self._cache_revision_history(rev_history)
 
1385
        for hook in Branch.hooks['set_rh']:
 
1386
            hook(self, rev_history)
1112
1387
 
1113
1388
    @needs_write_lock
1114
 
    def generate_revision_history(self, revision_id, last_rev=None, 
1115
 
        other_branch=None):
1116
 
        """Create a new revision history that will finish with revision_id.
1117
 
        
1118
 
        :param revision_id: the new tip to use.
1119
 
        :param last_rev: The previous last_revision. If not None, then this
1120
 
            must be a ancestory of revision_id, or DivergedBranches is raised.
1121
 
        :param other_branch: The other branch that DivergedBranches should
1122
 
            raise with respect to.
1123
 
        """
 
1389
    def set_last_revision_info(self, revno, revision_id):
 
1390
        revision_id = osutils.safe_revision_id(revision_id)
 
1391
        history = self._lefthand_history(revision_id)
 
1392
        assert len(history) == revno, '%d != %d' % (len(history), revno)
 
1393
        self.set_revision_history(history)
 
1394
 
 
1395
    def _gen_revision_history(self):
 
1396
        history = self.control_files.get('revision-history').read().split('\n')
 
1397
        if history[-1:] == ['']:
 
1398
            # There shouldn't be a trailing newline, but just in case.
 
1399
            history.pop()
 
1400
        return history
 
1401
 
 
1402
    def _lefthand_history(self, revision_id, last_rev=None,
 
1403
                          other_branch=None):
1124
1404
        # stop_revision must be a descendant of last_revision
1125
1405
        stop_graph = self.repository.get_revision_graph(revision_id)
1126
1406
        if last_rev is not None and last_rev not in stop_graph:
1129
1409
        # make a new revision history from the graph
1130
1410
        current_rev_id = revision_id
1131
1411
        new_history = []
1132
 
        while current_rev_id not in (None, revision.NULL_REVISION):
 
1412
        while current_rev_id not in (None, _mod_revision.NULL_REVISION):
1133
1413
            new_history.append(current_rev_id)
1134
1414
            current_rev_id_parents = stop_graph[current_rev_id]
1135
1415
            try:
1137
1417
            except IndexError:
1138
1418
                current_rev_id = None
1139
1419
        new_history.reverse()
1140
 
        self.set_revision_history(new_history)
 
1420
        return new_history
 
1421
 
 
1422
    @needs_write_lock
 
1423
    def generate_revision_history(self, revision_id, last_rev=None,
 
1424
        other_branch=None):
 
1425
        """Create a new revision history that will finish with revision_id.
 
1426
 
 
1427
        :param revision_id: the new tip to use.
 
1428
        :param last_rev: The previous last_revision. If not None, then this
 
1429
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
1430
        :param other_branch: The other branch that DivergedBranches should
 
1431
            raise with respect to.
 
1432
        """
 
1433
        revision_id = osutils.safe_revision_id(revision_id)
 
1434
        self.set_revision_history(self._lefthand_history(revision_id,
 
1435
            last_rev, other_branch))
1141
1436
 
1142
1437
    @needs_write_lock
1143
1438
    def update_revisions(self, other, stop_revision=None):
1149
1444
                if stop_revision is None:
1150
1445
                    # if there are no commits, we're done.
1151
1446
                    return
 
1447
            else:
 
1448
                stop_revision = osutils.safe_revision_id(stop_revision)
1152
1449
            # whats the current last revision, before we fetch [and change it
1153
1450
            # possibly]
1154
1451
            last_rev = self.last_revision()
1155
1452
            # we fetch here regardless of whether we need to so that we pickup
1156
1453
            # filled in ghosts.
1157
1454
            self.fetch(other, stop_revision)
1158
 
            my_ancestry = self.repository.get_ancestry(last_rev)
 
1455
            my_ancestry = self.repository.get_ancestry(last_rev,
 
1456
                                                       topo_sorted=False)
1159
1457
            if stop_revision in my_ancestry:
1160
1458
                # last_revision is a descendant of stop_revision
1161
1459
                return
1179
1477
        return self.bzrdir.open_workingtree()
1180
1478
 
1181
1479
    @needs_write_lock
1182
 
    def pull(self, source, overwrite=False, stop_revision=None):
1183
 
        """See Branch.pull."""
 
1480
    def pull(self, source, overwrite=False, stop_revision=None,
 
1481
             _hook_master=None, run_hooks=True):
 
1482
        """See Branch.pull.
 
1483
 
 
1484
        :param _hook_master: Private parameter - set the branch to 
 
1485
            be supplied as the master to push hooks.
 
1486
        :param run_hooks: Private parameter - if false, this branch
 
1487
            is being called because it's the master of the primary branch,
 
1488
            so it should not run its hooks.
 
1489
        """
 
1490
        result = PullResult()
 
1491
        result.source_branch = source
 
1492
        result.target_branch = self
1184
1493
        source.lock_read()
1185
1494
        try:
1186
 
            old_count = len(self.revision_history())
 
1495
            result.old_revno, result.old_revid = self.last_revision_info()
1187
1496
            try:
1188
1497
                self.update_revisions(source, stop_revision)
1189
1498
            except DivergedBranches:
1190
1499
                if not overwrite:
1191
1500
                    raise
1192
1501
            if overwrite:
1193
 
                self.set_revision_history(source.revision_history())
1194
 
            new_count = len(self.revision_history())
1195
 
            return new_count - old_count
 
1502
                if stop_revision is None:
 
1503
                    stop_revision = source.last_revision()
 
1504
                self.generate_revision_history(stop_revision)
 
1505
            result.tag_conflicts = source.tags.merge_to(self.tags)
 
1506
            result.new_revno, result.new_revid = self.last_revision_info()
 
1507
            if _hook_master:
 
1508
                result.master_branch = _hook_master
 
1509
                result.local_branch = self
 
1510
            else:
 
1511
                result.master_branch = self
 
1512
                result.local_branch = None
 
1513
            if run_hooks:
 
1514
                for hook in Branch.hooks['post_pull']:
 
1515
                    hook(result)
1196
1516
        finally:
1197
1517
            source.unlock()
 
1518
        return result
 
1519
 
 
1520
    def _get_parent_location(self):
 
1521
        _locs = ['parent', 'pull', 'x-pull']
 
1522
        for l in _locs:
 
1523
            try:
 
1524
                return self.control_files.get(l).read().strip('\n')
 
1525
            except NoSuchFile:
 
1526
                pass
 
1527
        return None
 
1528
 
 
1529
    @needs_read_lock
 
1530
    def push(self, target, overwrite=False, stop_revision=None,
 
1531
             _override_hook_source_branch=None):
 
1532
        """See Branch.push.
 
1533
 
 
1534
        This is the basic concrete implementation of push()
 
1535
 
 
1536
        :param _override_hook_source_branch: If specified, run
 
1537
        the hooks passing this Branch as the source, rather than self.  
 
1538
        This is for use of RemoteBranch, where push is delegated to the
 
1539
        underlying vfs-based Branch. 
 
1540
        """
 
1541
        # TODO: Public option to disable running hooks - should be trivial but
 
1542
        # needs tests.
 
1543
        target.lock_write()
 
1544
        try:
 
1545
            result = self._push_with_bound_branches(target, overwrite,
 
1546
                    stop_revision,
 
1547
                    _override_hook_source_branch=_override_hook_source_branch)
 
1548
            return result
 
1549
        finally:
 
1550
            target.unlock()
 
1551
 
 
1552
    def _push_with_bound_branches(self, target, overwrite,
 
1553
            stop_revision,
 
1554
            _override_hook_source_branch=None):
 
1555
        """Push from self into target, and into target's master if any.
 
1556
        
 
1557
        This is on the base BzrBranch class even though it doesn't support 
 
1558
        bound branches because the *target* might be bound.
 
1559
        """
 
1560
        def _run_hooks():
 
1561
            if _override_hook_source_branch:
 
1562
                result.source_branch = _override_hook_source_branch
 
1563
            for hook in Branch.hooks['post_push']:
 
1564
                hook(result)
 
1565
 
 
1566
        bound_location = target.get_bound_location()
 
1567
        if bound_location and target.base != bound_location:
 
1568
            # there is a master branch.
 
1569
            #
 
1570
            # XXX: Why the second check?  Is it even supported for a branch to
 
1571
            # be bound to itself? -- mbp 20070507
 
1572
            master_branch = target.get_master_branch()
 
1573
            master_branch.lock_write()
 
1574
            try:
 
1575
                # push into the master from this branch.
 
1576
                self._basic_push(master_branch, overwrite, stop_revision)
 
1577
                # and push into the target branch from this. Note that we push from
 
1578
                # this branch again, because its considered the highest bandwidth
 
1579
                # repository.
 
1580
                result = self._basic_push(target, overwrite, stop_revision)
 
1581
                result.master_branch = master_branch
 
1582
                result.local_branch = target
 
1583
                _run_hooks()
 
1584
                return result
 
1585
            finally:
 
1586
                master_branch.unlock()
 
1587
        else:
 
1588
            # no master branch
 
1589
            result = self._basic_push(target, overwrite, stop_revision)
 
1590
            # TODO: Why set master_branch and local_branch if there's no
 
1591
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
1592
            # 20070504
 
1593
            result.master_branch = target
 
1594
            result.local_branch = None
 
1595
            _run_hooks()
 
1596
            return result
 
1597
 
 
1598
    def _basic_push(self, target, overwrite, stop_revision):
 
1599
        """Basic implementation of push without bound branches or hooks.
 
1600
 
 
1601
        Must be called with self read locked and target write locked.
 
1602
        """
 
1603
        result = PushResult()
 
1604
        result.source_branch = self
 
1605
        result.target_branch = target
 
1606
        result.old_revno, result.old_revid = target.last_revision_info()
 
1607
        try:
 
1608
            target.update_revisions(self, stop_revision)
 
1609
        except DivergedBranches:
 
1610
            if not overwrite:
 
1611
                raise
 
1612
        if overwrite:
 
1613
            target.set_revision_history(self.revision_history())
 
1614
        result.tag_conflicts = self.tags.merge_to(target.tags)
 
1615
        result.new_revno, result.new_revid = target.last_revision_info()
 
1616
        return result
1198
1617
 
1199
1618
    def get_parent(self):
1200
1619
        """See Branch.get_parent."""
1201
1620
 
1202
 
        _locs = ['parent', 'pull', 'x-pull']
1203
1621
        assert self.base[-1] == '/'
1204
 
        for l in _locs:
1205
 
            try:
1206
 
                parent = self.control_files.get(l).read().strip('\n')
1207
 
            except NoSuchFile:
1208
 
                continue
1209
 
            # This is an old-format absolute path to a local branch
1210
 
            # turn it into a url
1211
 
            if parent.startswith('/'):
1212
 
                parent = urlutils.local_path_to_url(parent.decode('utf8'))
1213
 
            try:
1214
 
                return urlutils.join(self.base[:-1], parent)
1215
 
            except errors.InvalidURLJoin, e:
1216
 
                raise errors.InaccessibleParent(parent, self.base)
1217
 
        return None
1218
 
 
1219
 
    def get_push_location(self):
1220
 
        """See Branch.get_push_location."""
1221
 
        push_loc = self.get_config().get_user_option('push_location')
1222
 
        return push_loc
 
1622
        parent = self._get_parent_location()
 
1623
        if parent is None:
 
1624
            return parent
 
1625
        # This is an old-format absolute path to a local branch
 
1626
        # turn it into a url
 
1627
        if parent.startswith('/'):
 
1628
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
 
1629
        try:
 
1630
            return urlutils.join(self.base[:-1], parent)
 
1631
        except errors.InvalidURLJoin, e:
 
1632
            raise errors.InaccessibleParent(parent, self.base)
1223
1633
 
1224
1634
    def set_push_location(self, location):
1225
1635
        """See Branch.set_push_location."""
1226
 
        self.get_config().set_user_option('push_location', location, 
1227
 
                                          local=True)
 
1636
        self.get_config().set_user_option(
 
1637
            'push_location', location,
 
1638
            store=_mod_config.STORE_LOCATION_NORECURSE)
1228
1639
 
1229
1640
    @needs_write_lock
1230
1641
    def set_parent(self, url):
1234
1645
        # FIXUP this and get_parent in a future branch format bump:
1235
1646
        # read and rewrite the file, and have the new format code read
1236
1647
        # using .get not .get_utf8. RBC 20060125
1237
 
        if url is None:
1238
 
            self.control_files._transport.delete('parent')
1239
 
        else:
 
1648
        if url is not None:
1240
1649
            if isinstance(url, unicode):
1241
1650
                try: 
1242
1651
                    url = url.encode('ascii')
1243
1652
                except UnicodeEncodeError:
1244
 
                    raise bzrlib.errors.InvalidURL(url,
 
1653
                    raise errors.InvalidURL(url,
1245
1654
                        "Urls must be 7-bit ascii, "
1246
1655
                        "use bzrlib.urlutils.escape")
1247
 
                    
1248
1656
            url = urlutils.relative_url(self.base, url)
1249
 
            self.control_files.put('parent', StringIO(url + '\n'))
 
1657
        self._set_parent_location(url)
 
1658
 
 
1659
    def _set_parent_location(self, url):
 
1660
        if url is None:
 
1661
            self.control_files._transport.delete('parent')
 
1662
        else:
 
1663
            assert isinstance(url, str)
 
1664
            self.control_files.put_bytes('parent', url + '\n')
1250
1665
 
1251
1666
    @deprecated_function(zero_nine)
1252
1667
    def tree_config(self):
1272
1687
                                         _repository=_repository)
1273
1688
        
1274
1689
    @needs_write_lock
1275
 
    def pull(self, source, overwrite=False, stop_revision=None):
1276
 
        """Updates branch.pull to be bound branch aware."""
 
1690
    def pull(self, source, overwrite=False, stop_revision=None,
 
1691
             run_hooks=True):
 
1692
        """Pull from source into self, updating my master if any.
 
1693
        
 
1694
        :param run_hooks: Private parameter - if false, this branch
 
1695
            is being called because it's the master of the primary branch,
 
1696
            so it should not run its hooks.
 
1697
        """
1277
1698
        bound_location = self.get_bound_location()
1278
 
        if source.base != bound_location:
 
1699
        master_branch = None
 
1700
        if bound_location and source.base != bound_location:
1279
1701
            # not pulling from master, so we need to update master.
1280
1702
            master_branch = self.get_master_branch()
1281
 
            if master_branch:
1282
 
                master_branch.pull(source)
1283
 
                source = master_branch
1284
 
        return super(BzrBranch5, self).pull(source, overwrite, stop_revision)
 
1703
            master_branch.lock_write()
 
1704
        try:
 
1705
            if master_branch:
 
1706
                # pull from source into master.
 
1707
                master_branch.pull(source, overwrite, stop_revision,
 
1708
                    run_hooks=False)
 
1709
            return super(BzrBranch5, self).pull(source, overwrite,
 
1710
                stop_revision, _hook_master=master_branch,
 
1711
                run_hooks=run_hooks)
 
1712
        finally:
 
1713
            if master_branch:
 
1714
                master_branch.unlock()
1285
1715
 
1286
1716
    def get_bound_location(self):
1287
1717
        try:
1382
1812
        if master is not None:
1383
1813
            old_tip = self.last_revision()
1384
1814
            self.pull(master, overwrite=True)
1385
 
            if old_tip in self.repository.get_ancestry(self.last_revision()):
 
1815
            if old_tip in self.repository.get_ancestry(self.last_revision(),
 
1816
                                                       topo_sorted=False):
1386
1817
                return None
1387
1818
            return old_tip
1388
1819
        return None
1389
1820
 
1390
1821
 
1391
 
class BranchTestProviderAdapter(object):
1392
 
    """A tool to generate a suite testing multiple branch formats at once.
1393
 
 
1394
 
    This is done by copying the test once for each transport and injecting
1395
 
    the transport_server, transport_readonly_server, and branch_format
1396
 
    classes into each copy. Each copy is also given a new id() to make it
1397
 
    easy to identify.
1398
 
    """
1399
 
 
1400
 
    def __init__(self, transport_server, transport_readonly_server, formats):
1401
 
        self._transport_server = transport_server
1402
 
        self._transport_readonly_server = transport_readonly_server
1403
 
        self._formats = formats
1404
 
    
1405
 
    def adapt(self, test):
1406
 
        result = TestSuite()
1407
 
        for branch_format, bzrdir_format in self._formats:
1408
 
            new_test = deepcopy(test)
1409
 
            new_test.transport_server = self._transport_server
1410
 
            new_test.transport_readonly_server = self._transport_readonly_server
1411
 
            new_test.bzrdir_format = bzrdir_format
1412
 
            new_test.branch_format = branch_format
1413
 
            def make_new_test_id():
1414
 
                new_id = "%s(%s)" % (new_test.id(), branch_format.__class__.__name__)
1415
 
                return lambda: new_id
1416
 
            new_test.id = make_new_test_id()
1417
 
            result.addTest(new_test)
1418
 
        return result
 
1822
class BzrBranchExperimental(BzrBranch5):
 
1823
    """Bzr experimental branch format
 
1824
 
 
1825
    This format has:
 
1826
     - a revision-history file.
 
1827
     - a format string
 
1828
     - a lock dir guarding the branch itself
 
1829
     - all of this stored in a branch/ subdirectory
 
1830
     - works with shared repositories.
 
1831
     - a tag dictionary in the branch
 
1832
 
 
1833
    This format is new in bzr 0.15, but shouldn't be used for real data, 
 
1834
    only for testing.
 
1835
 
 
1836
    This class acts as it's own BranchFormat.
 
1837
    """
 
1838
 
 
1839
    _matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1840
 
 
1841
    @classmethod
 
1842
    def get_format_string(cls):
 
1843
        """See BranchFormat.get_format_string()."""
 
1844
        return "Bazaar-NG branch format experimental\n"
 
1845
 
 
1846
    @classmethod
 
1847
    def get_format_description(cls):
 
1848
        """See BranchFormat.get_format_description()."""
 
1849
        return "Experimental branch format"
 
1850
 
 
1851
    @classmethod
 
1852
    def get_reference(cls, a_bzrdir):
 
1853
        """Get the target reference of the branch in a_bzrdir.
 
1854
 
 
1855
        format probing must have been completed before calling
 
1856
        this method - it is assumed that the format of the branch
 
1857
        in a_bzrdir is correct.
 
1858
 
 
1859
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1860
        :return: None if the branch is not a reference branch.
 
1861
        """
 
1862
        return None
 
1863
 
 
1864
    @classmethod
 
1865
    def _initialize_control_files(cls, a_bzrdir, utf8_files, lock_filename,
 
1866
            lock_class):
 
1867
        branch_transport = a_bzrdir.get_branch_transport(cls)
 
1868
        control_files = lockable_files.LockableFiles(branch_transport,
 
1869
            lock_filename, lock_class)
 
1870
        control_files.create_lock()
 
1871
        control_files.lock_write()
 
1872
        try:
 
1873
            for filename, content in utf8_files:
 
1874
                control_files.put_utf8(filename, content)
 
1875
        finally:
 
1876
            control_files.unlock()
 
1877
        
 
1878
    @classmethod
 
1879
    def initialize(cls, a_bzrdir):
 
1880
        """Create a branch of this format in a_bzrdir."""
 
1881
        utf8_files = [('format', cls.get_format_string()),
 
1882
                      ('revision-history', ''),
 
1883
                      ('branch-name', ''),
 
1884
                      ('tags', ''),
 
1885
                      ]
 
1886
        cls._initialize_control_files(a_bzrdir, utf8_files,
 
1887
            'lock', lockdir.LockDir)
 
1888
        return cls.open(a_bzrdir, _found=True)
 
1889
 
 
1890
    @classmethod
 
1891
    def open(cls, a_bzrdir, _found=False):
 
1892
        """Return the branch object for a_bzrdir
 
1893
 
 
1894
        _found is a private parameter, do not use it. It is used to indicate
 
1895
               if format probing has already be done.
 
1896
        """
 
1897
        if not _found:
 
1898
            format = BranchFormat.find_format(a_bzrdir)
 
1899
            assert format.__class__ == cls
 
1900
        transport = a_bzrdir.get_branch_transport(None)
 
1901
        control_files = lockable_files.LockableFiles(transport, 'lock',
 
1902
                                                     lockdir.LockDir)
 
1903
        return cls(_format=cls,
 
1904
            _control_files=control_files,
 
1905
            a_bzrdir=a_bzrdir,
 
1906
            _repository=a_bzrdir.find_repository())
 
1907
 
 
1908
    @classmethod
 
1909
    def is_supported(cls):
 
1910
        return True
 
1911
 
 
1912
    def _make_tags(self):
 
1913
        return BasicTags(self)
 
1914
 
 
1915
    @classmethod
 
1916
    def supports_tags(cls):
 
1917
        return True
 
1918
 
 
1919
 
 
1920
BranchFormat.register_format(BzrBranchExperimental)
 
1921
 
 
1922
 
 
1923
class BzrBranch6(BzrBranch5):
 
1924
 
 
1925
    @needs_read_lock
 
1926
    def last_revision_info(self):
 
1927
        revision_string = self.control_files.get('last-revision').read()
 
1928
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
1929
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
1930
        revno = int(revno)
 
1931
        return revno, revision_id
 
1932
 
 
1933
    def last_revision(self):
 
1934
        """Return last revision id, or None"""
 
1935
        revision_id = self.last_revision_info()[1]
 
1936
        if revision_id == _mod_revision.NULL_REVISION:
 
1937
            revision_id = None
 
1938
        return revision_id
 
1939
 
 
1940
    def _write_last_revision_info(self, revno, revision_id):
 
1941
        """Simply write out the revision id, with no checks.
 
1942
 
 
1943
        Use set_last_revision_info to perform this safely.
 
1944
 
 
1945
        Does not update the revision_history cache.
 
1946
        Intended to be called by set_last_revision_info and
 
1947
        _write_revision_history.
 
1948
        """
 
1949
        if revision_id is None:
 
1950
            revision_id = 'null:'
 
1951
        out_string = '%d %s\n' % (revno, revision_id)
 
1952
        self.control_files.put_bytes('last-revision', out_string)
 
1953
 
 
1954
    @needs_write_lock
 
1955
    def set_last_revision_info(self, revno, revision_id):
 
1956
        revision_id = osutils.safe_revision_id(revision_id)
 
1957
        if self._get_append_revisions_only():
 
1958
            self._check_history_violation(revision_id)
 
1959
        self._write_last_revision_info(revno, revision_id)
 
1960
        self._clear_cached_state()
 
1961
 
 
1962
    def _check_history_violation(self, revision_id):
 
1963
        last_revision = self.last_revision()
 
1964
        if last_revision is None:
 
1965
            return
 
1966
        if last_revision not in self._lefthand_history(revision_id):
 
1967
            raise errors.AppendRevisionsOnlyViolation(self.base)
 
1968
 
 
1969
    def _gen_revision_history(self):
 
1970
        """Generate the revision history from last revision
 
1971
        """
 
1972
        history = list(self.repository.iter_reverse_revision_history(
 
1973
            self.last_revision()))
 
1974
        history.reverse()
 
1975
        return history
 
1976
 
 
1977
    def _write_revision_history(self, history):
 
1978
        """Factored out of set_revision_history.
 
1979
 
 
1980
        This performs the actual writing to disk, with format-specific checks.
 
1981
        It is intended to be called by BzrBranch5.set_revision_history.
 
1982
        """
 
1983
        if len(history) == 0:
 
1984
            last_revision = 'null:'
 
1985
        else:
 
1986
            if history != self._lefthand_history(history[-1]):
 
1987
                raise errors.NotLefthandHistory(history)
 
1988
            last_revision = history[-1]
 
1989
        if self._get_append_revisions_only():
 
1990
            self._check_history_violation(last_revision)
 
1991
        self._write_last_revision_info(len(history), last_revision)
 
1992
 
 
1993
    @needs_write_lock
 
1994
    def append_revision(self, *revision_ids):
 
1995
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
 
1996
        if len(revision_ids) == 0:
 
1997
            return
 
1998
        prev_revno, prev_revision = self.last_revision_info()
 
1999
        for revision in self.repository.get_revisions(revision_ids):
 
2000
            if prev_revision == _mod_revision.NULL_REVISION:
 
2001
                if revision.parent_ids != []:
 
2002
                    raise errors.NotLeftParentDescendant(self, prev_revision,
 
2003
                                                         revision.revision_id)
 
2004
            else:
 
2005
                if revision.parent_ids[0] != prev_revision:
 
2006
                    raise errors.NotLeftParentDescendant(self, prev_revision,
 
2007
                                                         revision.revision_id)
 
2008
            prev_revision = revision.revision_id
 
2009
        self.set_last_revision_info(prev_revno + len(revision_ids),
 
2010
                                    revision_ids[-1])
 
2011
 
 
2012
    @needs_write_lock
 
2013
    def _set_parent_location(self, url):
 
2014
        """Set the parent branch"""
 
2015
        self._set_config_location('parent_location', url, make_relative=True)
 
2016
 
 
2017
    @needs_read_lock
 
2018
    def _get_parent_location(self):
 
2019
        """Set the parent branch"""
 
2020
        return self._get_config_location('parent_location')
 
2021
 
 
2022
    def set_push_location(self, location):
 
2023
        """See Branch.set_push_location."""
 
2024
        self._set_config_location('push_location', location)
 
2025
 
 
2026
    def set_bound_location(self, location):
 
2027
        """See Branch.set_push_location."""
 
2028
        result = None
 
2029
        config = self.get_config()
 
2030
        if location is None:
 
2031
            if config.get_user_option('bound') != 'True':
 
2032
                return False
 
2033
            else:
 
2034
                config.set_user_option('bound', 'False')
 
2035
                return True
 
2036
        else:
 
2037
            self._set_config_location('bound_location', location,
 
2038
                                      config=config)
 
2039
            config.set_user_option('bound', 'True')
 
2040
        return True
 
2041
 
 
2042
    def _get_bound_location(self, bound):
 
2043
        """Return the bound location in the config file.
 
2044
 
 
2045
        Return None if the bound parameter does not match"""
 
2046
        config = self.get_config()
 
2047
        config_bound = (config.get_user_option('bound') == 'True')
 
2048
        if config_bound != bound:
 
2049
            return None
 
2050
        return self._get_config_location('bound_location', config=config)
 
2051
 
 
2052
    def get_bound_location(self):
 
2053
        """See Branch.set_push_location."""
 
2054
        return self._get_bound_location(True)
 
2055
 
 
2056
    def get_old_bound_location(self):
 
2057
        """See Branch.get_old_bound_location"""
 
2058
        return self._get_bound_location(False)
 
2059
 
 
2060
    def set_append_revisions_only(self, enabled):
 
2061
        if enabled:
 
2062
            value = 'True'
 
2063
        else:
 
2064
            value = 'False'
 
2065
        self.get_config().set_user_option('append_revisions_only', value)
 
2066
 
 
2067
    def _get_append_revisions_only(self):
 
2068
        value = self.get_config().get_user_option('append_revisions_only')
 
2069
        return value == 'True'
 
2070
 
 
2071
    def _synchronize_history(self, destination, revision_id):
 
2072
        """Synchronize last revision and revision history between branches.
 
2073
 
 
2074
        This version is most efficient when the destination is also a
 
2075
        BzrBranch6, but works for BzrBranch5, as long as the destination's
 
2076
        repository contains all the lefthand ancestors of the intended
 
2077
        last_revision.  If not, set_last_revision_info will fail.
 
2078
 
 
2079
        :param destination: The branch to copy the history into
 
2080
        :param revision_id: The revision-id to truncate history at.  May
 
2081
          be None to copy complete history.
 
2082
        """
 
2083
        if revision_id is None:
 
2084
            revno, revision_id = self.last_revision_info()
 
2085
        else:
 
2086
            # To figure out the revno for a random revision, we need to build
 
2087
            # the revision history, and count its length.
 
2088
            # We don't care about the order, just how long it is.
 
2089
            # Alternatively, we could start at the current location, and count
 
2090
            # backwards. But there is no guarantee that we will find it since
 
2091
            # it may be a merged revision.
 
2092
            revno = len(list(self.repository.iter_reverse_revision_history(
 
2093
                                                                revision_id)))
 
2094
        destination.set_last_revision_info(revno, revision_id)
 
2095
 
 
2096
    def _make_tags(self):
 
2097
        return BasicTags(self)
 
2098
 
 
2099
 
 
2100
######################################################################
 
2101
# results of operations
 
2102
 
 
2103
 
 
2104
class _Result(object):
 
2105
 
 
2106
    def _show_tag_conficts(self, to_file):
 
2107
        if not getattr(self, 'tag_conflicts', None):
 
2108
            return
 
2109
        to_file.write('Conflicting tags:\n')
 
2110
        for name, value1, value2 in self.tag_conflicts:
 
2111
            to_file.write('    %s\n' % (name, ))
 
2112
 
 
2113
 
 
2114
class PullResult(_Result):
 
2115
    """Result of a Branch.pull operation.
 
2116
 
 
2117
    :ivar old_revno: Revision number before pull.
 
2118
    :ivar new_revno: Revision number after pull.
 
2119
    :ivar old_revid: Tip revision id before pull.
 
2120
    :ivar new_revid: Tip revision id after pull.
 
2121
    :ivar source_branch: Source (local) branch object.
 
2122
    :ivar master_branch: Master branch of the target, or None.
 
2123
    :ivar target_branch: Target/destination branch object.
 
2124
    """
 
2125
 
 
2126
    def __int__(self):
 
2127
        # DEPRECATED: pull used to return the change in revno
 
2128
        return self.new_revno - self.old_revno
 
2129
 
 
2130
    def report(self, to_file):
 
2131
        if self.old_revid == self.new_revid:
 
2132
            to_file.write('No revisions to pull.\n')
 
2133
        else:
 
2134
            to_file.write('Now on revision %d.\n' % self.new_revno)
 
2135
        self._show_tag_conficts(to_file)
 
2136
 
 
2137
 
 
2138
class PushResult(_Result):
 
2139
    """Result of a Branch.push operation.
 
2140
 
 
2141
    :ivar old_revno: Revision number before push.
 
2142
    :ivar new_revno: Revision number after push.
 
2143
    :ivar old_revid: Tip revision id before push.
 
2144
    :ivar new_revid: Tip revision id after push.
 
2145
    :ivar source_branch: Source branch object.
 
2146
    :ivar master_branch: Master branch of the target, or None.
 
2147
    :ivar target_branch: Target/destination branch object.
 
2148
    """
 
2149
 
 
2150
    def __int__(self):
 
2151
        # DEPRECATED: push used to return the change in revno
 
2152
        return self.new_revno - self.old_revno
 
2153
 
 
2154
    def report(self, to_file):
 
2155
        """Write a human-readable description of the result."""
 
2156
        if self.old_revid == self.new_revid:
 
2157
            to_file.write('No new revisions to push.\n')
 
2158
        else:
 
2159
            to_file.write('Pushed up to revision %d.\n' % self.new_revno)
 
2160
        self._show_tag_conficts(to_file)
1419
2161
 
1420
2162
 
1421
2163
class BranchCheckResult(object):
1438
2180
             self.branch._format)
1439
2181
 
1440
2182
 
1441
 
######################################################################
1442
 
# predicates
1443
 
 
1444
 
 
1445
 
@deprecated_function(zero_eight)
1446
 
def is_control_file(*args, **kwargs):
1447
 
    """See bzrlib.workingtree.is_control_file."""
1448
 
    return bzrlib.workingtree.is_control_file(*args, **kwargs)
 
2183
class Converter5to6(object):
 
2184
    """Perform an in-place upgrade of format 5 to format 6"""
 
2185
 
 
2186
    def convert(self, branch):
 
2187
        # Data for 5 and 6 can peacefully coexist.
 
2188
        format = BzrBranchFormat6()
 
2189
        new_branch = format.open(branch.bzrdir, _found=True)
 
2190
 
 
2191
        # Copy source data into target
 
2192
        new_branch.set_last_revision_info(*branch.last_revision_info())
 
2193
        new_branch.set_parent(branch.get_parent())
 
2194
        new_branch.set_bound_location(branch.get_bound_location())
 
2195
        new_branch.set_push_location(branch.get_push_location())
 
2196
 
 
2197
        # New branch has no tags by default
 
2198
        new_branch.tags._set_tag_dict({})
 
2199
 
 
2200
        # Copying done; now update target format
 
2201
        new_branch.control_files.put_utf8('format',
 
2202
            format.get_format_string())
 
2203
 
 
2204
        # Clean up old files
 
2205
        new_branch.control_files._transport.delete('revision-history')
 
2206
        try:
 
2207
            branch.set_parent(None)
 
2208
        except NoSuchFile:
 
2209
            pass
 
2210
        branch.set_bound_location(None)