~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Zearin
  • Date: 2010-11-12 22:08:18 UTC
  • mto: (5570.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5572.
  • Revision ID: zearin@users.sourceforge.net-20101112220818-mb62len4zyxr8qvd
Fixed capitalization of XML and HTTP.  Fixed by hand and only where appropriate (e.g., left http://some/url lowercase, but capitalized "When making an HTTP request…").

Show diffs side-by-side

added added

removed removed

Lines of Context:
25
25
        bzrdir,
26
26
        cache_utf8,
27
27
        config as _mod_config,
 
28
        controldir,
28
29
        debug,
29
30
        errors,
30
31
        lockdir,
31
32
        lockable_files,
 
33
        remote,
32
34
        repository,
33
35
        revision as _mod_revision,
34
36
        rio,
49
51
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
50
52
from bzrlib.hooks import HookPoint, Hooks
51
53
from bzrlib.inter import InterObject
52
 
from bzrlib.lock import _RelockDebugMixin
 
54
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
53
55
from bzrlib import registry
54
56
from bzrlib.symbol_versioning import (
55
57
    deprecated_in,
63
65
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
64
66
 
65
67
 
66
 
class Branch(bzrdir.ControlComponent):
 
68
class Branch(controldir.ControlComponent):
67
69
    """Branch holding a history of revisions.
68
70
 
69
71
    :ivar base:
90
92
        self._revision_id_to_revno_cache = None
91
93
        self._partial_revision_id_to_revno_cache = {}
92
94
        self._partial_revision_history_cache = []
 
95
        self._tags_bytes = None
93
96
        self._last_revision_info_cache = None
94
97
        self._merge_sorted_revisions_cache = None
95
98
        self._open_hook()
197
200
        return self.supports_tags() and self.tags.get_tag_dict()
198
201
 
199
202
    def get_config(self):
 
203
        """Get a bzrlib.config.BranchConfig for this Branch.
 
204
 
 
205
        This can then be used to get and set configuration options for the
 
206
        branch.
 
207
 
 
208
        :return: A bzrlib.config.BranchConfig.
 
209
        """
200
210
        return BranchConfig(self)
201
211
 
202
212
    def _get_config(self):
218
228
            possible_transports=[self.bzrdir.root_transport])
219
229
        return a_branch.repository
220
230
 
 
231
    @needs_read_lock
221
232
    def _get_tags_bytes(self):
222
233
        """Get the bytes of a serialised tags dict.
223
234
 
230
241
        :return: The bytes of the tags file.
231
242
        :seealso: Branch._set_tags_bytes.
232
243
        """
233
 
        return self._transport.get_bytes('tags')
 
244
        if self._tags_bytes is None:
 
245
            self._tags_bytes = self._transport.get_bytes('tags')
 
246
        return self._tags_bytes
234
247
 
235
248
    def _get_nick(self, local=False, possible_transports=None):
236
249
        config = self.get_config()
238
251
        if not local and not config.has_explicit_nickname():
239
252
            try:
240
253
                master = self.get_master_branch(possible_transports)
 
254
                if master and self.user_url == master.user_url:
 
255
                    raise errors.RecursiveBind(self.user_url)
241
256
                if master is not None:
242
257
                    # return the master branch value
243
258
                    return master.nick
 
259
            except errors.RecursiveBind, e:
 
260
                raise e
244
261
            except errors.BzrError, e:
245
262
                # Silently fall back to local implicit nick if the master is
246
263
                # unavailable
283
300
        new_history.reverse()
284
301
        return new_history
285
302
 
286
 
    def lock_write(self):
 
303
    def lock_write(self, token=None):
 
304
        """Lock the branch for write operations.
 
305
 
 
306
        :param token: A token to permit reacquiring a previously held and
 
307
            preserved lock.
 
308
        :return: A BranchWriteLockResult.
 
309
        """
287
310
        raise NotImplementedError(self.lock_write)
288
311
 
289
312
    def lock_read(self):
 
313
        """Lock the branch for read operations.
 
314
 
 
315
        :return: A bzrlib.lock.LogicalLockResult.
 
316
        """
290
317
        raise NotImplementedError(self.lock_read)
291
318
 
292
319
    def unlock(self):
783
810
            if len(old_repository._fallback_repositories) != 1:
784
811
                raise AssertionError("can't cope with fallback repositories "
785
812
                    "of %r" % (self.repository,))
786
 
            # unlock it, including unlocking the fallback
 
813
            # Open the new repository object.
 
814
            # Repositories don't offer an interface to remove fallback
 
815
            # repositories today; take the conceptually simpler option and just
 
816
            # reopen it.  We reopen it starting from the URL so that we
 
817
            # get a separate connection for RemoteRepositories and can
 
818
            # stream from one of them to the other.  This does mean doing
 
819
            # separate SSH connection setup, but unstacking is not a
 
820
            # common operation so it's tolerable.
 
821
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
822
            new_repository = new_bzrdir.find_repository()
 
823
            if new_repository._fallback_repositories:
 
824
                raise AssertionError("didn't expect %r to have "
 
825
                    "fallback_repositories"
 
826
                    % (self.repository,))
 
827
            # Replace self.repository with the new repository.
 
828
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
829
            # lock count) of self.repository to the new repository.
 
830
            lock_token = old_repository.lock_write().repository_token
 
831
            self.repository = new_repository
 
832
            if isinstance(self, remote.RemoteBranch):
 
833
                # Remote branches can have a second reference to the old
 
834
                # repository that need to be replaced.
 
835
                if self._real_branch is not None:
 
836
                    self._real_branch.repository = new_repository
 
837
            self.repository.lock_write(token=lock_token)
 
838
            if lock_token is not None:
 
839
                old_repository.leave_lock_in_place()
787
840
            old_repository.unlock()
 
841
            if lock_token is not None:
 
842
                # XXX: self.repository.leave_lock_in_place() before this
 
843
                # function will not be preserved.  Fortunately that doesn't
 
844
                # affect the current default format (2a), and would be a
 
845
                # corner-case anyway.
 
846
                #  - Andrew Bennetts, 2010/06/30
 
847
                self.repository.dont_leave_lock_in_place()
 
848
            old_lock_count = 0
 
849
            while True:
 
850
                try:
 
851
                    old_repository.unlock()
 
852
                except errors.LockNotHeld:
 
853
                    break
 
854
                old_lock_count += 1
 
855
            if old_lock_count == 0:
 
856
                raise AssertionError(
 
857
                    'old_repository should have been locked at least once.')
 
858
            for i in range(old_lock_count-1):
 
859
                self.repository.lock_write()
 
860
            # Fetch from the old repository into the new.
788
861
            old_repository.lock_read()
789
862
            try:
790
 
                # Repositories don't offer an interface to remove fallback
791
 
                # repositories today; take the conceptually simpler option and just
792
 
                # reopen it.  We reopen it starting from the URL so that we
793
 
                # get a separate connection for RemoteRepositories and can
794
 
                # stream from one of them to the other.  This does mean doing
795
 
                # separate SSH connection setup, but unstacking is not a
796
 
                # common operation so it's tolerable.
797
 
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
798
 
                new_repository = new_bzrdir.find_repository()
799
 
                self.repository = new_repository
800
 
                if self.repository._fallback_repositories:
801
 
                    raise AssertionError("didn't expect %r to have "
802
 
                        "fallback_repositories"
803
 
                        % (self.repository,))
804
 
                # this is not paired with an unlock because it's just restoring
805
 
                # the previous state; the lock's released when set_stacked_on_url
806
 
                # returns
807
 
                self.repository.lock_write()
808
863
                # XXX: If you unstack a branch while it has a working tree
809
864
                # with a pending merge, the pending-merged revisions will no
810
865
                # longer be present.  You can (probably) revert and remerge.
825
880
 
826
881
        :seealso: Branch._get_tags_bytes.
827
882
        """
828
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
829
 
            'tags', bytes)
 
883
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
884
                bytes)
 
885
 
 
886
    def _set_tags_bytes_locked(self, bytes):
 
887
        self._tags_bytes = bytes
 
888
        return self._transport.put_bytes('tags', bytes)
830
889
 
831
890
    def _cache_revision_history(self, rev_history):
832
891
        """Set the cached revision history to rev_history.
862
921
        self._merge_sorted_revisions_cache = None
863
922
        self._partial_revision_history_cache = []
864
923
        self._partial_revision_id_to_revno_cache = {}
 
924
        self._tags_bytes = None
865
925
 
866
926
    def _gen_revision_history(self):
867
927
        """Return sequence of revision hashes on to this branch.
951
1011
                raise errors.NoSuchRevision(self, stop_revision)
952
1012
        return other_history[self_len:stop_revision]
953
1013
 
954
 
    @needs_write_lock
955
1014
    def update_revisions(self, other, stop_revision=None, overwrite=False,
956
1015
                         graph=None):
957
1016
        """Pull in new perfect-fit revisions.
1006
1065
            self._extend_partial_history(distance_from_last)
1007
1066
        return self._partial_revision_history_cache[distance_from_last]
1008
1067
 
1009
 
    @needs_write_lock
1010
1068
    def pull(self, source, overwrite=False, stop_revision=None,
1011
1069
             possible_transports=None, *args, **kwargs):
1012
1070
        """Mirror source into this branch.
1255
1313
                revno = 1
1256
1314
        destination.set_last_revision_info(revno, revision_id)
1257
1315
 
1258
 
    @needs_read_lock
1259
1316
    def copy_content_into(self, destination, revision_id=None):
1260
1317
        """Copy the content of self into destination.
1261
1318
 
1262
1319
        revision_id: if not None, the revision history in the new branch will
1263
1320
                     be truncated to end with revision_id.
1264
1321
        """
1265
 
        self.update_references(destination)
1266
 
        self._synchronize_history(destination, revision_id)
1267
 
        try:
1268
 
            parent = self.get_parent()
1269
 
        except errors.InaccessibleParent, e:
1270
 
            mutter('parent was not accessible to copy: %s', e)
1271
 
        else:
1272
 
            if parent:
1273
 
                destination.set_parent(parent)
1274
 
        if self._push_should_merge_tags():
1275
 
            self.tags.merge_to(destination.tags)
 
1322
        return InterBranch.get(self, destination).copy_content_into(
 
1323
            revision_id=revision_id)
1276
1324
 
1277
1325
    def update_references(self, target):
1278
1326
        if not getattr(self._format, 'supports_reference_locations', False):
1333
1381
        return format
1334
1382
 
1335
1383
    def create_clone_on_transport(self, to_transport, revision_id=None,
1336
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1384
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1385
        no_tree=None):
1337
1386
        """Create a clone of this branch and its bzrdir.
1338
1387
 
1339
1388
        :param to_transport: The transport to clone onto.
1346
1395
        """
1347
1396
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1348
1397
        # clone call. Or something. 20090224 RBC/spiv.
 
1398
        # XXX: Should this perhaps clone colocated branches as well, 
 
1399
        # rather than just the default branch? 20100319 JRV
1349
1400
        if revision_id is None:
1350
1401
            revision_id = self.last_revision()
1351
1402
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1352
1403
            revision_id=revision_id, stacked_on=stacked_on,
1353
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1404
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1405
            no_tree=no_tree)
1354
1406
        return dir_to.open_branch()
1355
1407
 
1356
1408
    def create_checkout(self, to_location, revision_id=None,
1481
1533
     * an open routine.
1482
1534
 
1483
1535
    Formats are placed in an dict by their format string for reference
1484
 
    during branch opening. Its not required that these be instances, they
 
1536
    during branch opening. It's not required that these be instances, they
1485
1537
    can be classes themselves with class methods - it simply depends on
1486
1538
    whether state is needed for a given format or not.
1487
1539
 
1510
1562
        try:
1511
1563
            transport = a_bzrdir.get_branch_transport(None, name=name)
1512
1564
            format_string = transport.get_bytes("format")
1513
 
            return klass._formats[format_string]
 
1565
            format = klass._formats[format_string]
 
1566
            if isinstance(format, MetaDirBranchFormatFactory):
 
1567
                return format()
 
1568
            return format
1514
1569
        except errors.NoSuchFile:
1515
1570
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1516
1571
        except KeyError:
1521
1576
        """Return the current default format."""
1522
1577
        return klass._default_format
1523
1578
 
1524
 
    def get_reference(self, a_bzrdir):
 
1579
    @classmethod
 
1580
    def get_formats(klass):
 
1581
        """Get all the known formats.
 
1582
 
 
1583
        Warning: This triggers a load of all lazy registered formats: do not
 
1584
        use except when that is desireed.
 
1585
        """
 
1586
        result = []
 
1587
        for fmt in klass._formats.values():
 
1588
            if isinstance(fmt, MetaDirBranchFormatFactory):
 
1589
                fmt = fmt()
 
1590
            result.append(fmt)
 
1591
        return result
 
1592
 
 
1593
    def get_reference(self, a_bzrdir, name=None):
1525
1594
        """Get the target reference of the branch in a_bzrdir.
1526
1595
 
1527
1596
        format probing must have been completed before calling
1529
1598
        in a_bzrdir is correct.
1530
1599
 
1531
1600
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1601
        :param name: Name of the colocated branch to fetch
1532
1602
        :return: None if the branch is not a reference branch.
1533
1603
        """
1534
1604
        return None
1535
1605
 
1536
1606
    @classmethod
1537
 
    def set_reference(self, a_bzrdir, to_branch):
 
1607
    def set_reference(self, a_bzrdir, name, to_branch):
1538
1608
        """Set the target reference of the branch in a_bzrdir.
1539
1609
 
1540
1610
        format probing must have been completed before calling
1542
1612
        in a_bzrdir is correct.
1543
1613
 
1544
1614
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1615
        :param name: Name of colocated branch to set, None for default
1545
1616
        :param to_branch: branch that the checkout is to reference
1546
1617
        """
1547
1618
        raise NotImplementedError(self.set_reference)
1661
1732
 
1662
1733
    @classmethod
1663
1734
    def register_format(klass, format):
1664
 
        """Register a metadir format."""
 
1735
        """Register a metadir format.
 
1736
        
 
1737
        See MetaDirBranchFormatFactory for the ability to register a format
 
1738
        without loading the code the format needs until it is actually used.
 
1739
        """
1665
1740
        klass._formats[format.get_format_string()] = format
1666
1741
        # Metadir formats have a network name of their format string, and get
1667
 
        # registered as class factories.
1668
 
        network_format_registry.register(format.get_format_string(), format.__class__)
 
1742
        # registered as factories.
 
1743
        if isinstance(format, MetaDirBranchFormatFactory):
 
1744
            network_format_registry.register(format.get_format_string(), format)
 
1745
        else:
 
1746
            network_format_registry.register(format.get_format_string(),
 
1747
                format.__class__)
1669
1748
 
1670
1749
    @classmethod
1671
1750
    def set_default_format(klass, format):
1691
1770
        return False  # by default
1692
1771
 
1693
1772
 
 
1773
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1774
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1775
    
 
1776
    While none of the built in BranchFormats are lazy registered yet,
 
1777
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1778
    use it, and the bzr-loom plugin uses it as well (see
 
1779
    bzrlib.plugins.loom.formats).
 
1780
    """
 
1781
 
 
1782
    def __init__(self, format_string, module_name, member_name):
 
1783
        """Create a MetaDirBranchFormatFactory.
 
1784
 
 
1785
        :param format_string: The format string the format has.
 
1786
        :param module_name: Module to load the format class from.
 
1787
        :param member_name: Attribute name within the module for the format class.
 
1788
        """
 
1789
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1790
        self._format_string = format_string
 
1791
        
 
1792
    def get_format_string(self):
 
1793
        """See BranchFormat.get_format_string."""
 
1794
        return self._format_string
 
1795
 
 
1796
    def __call__(self):
 
1797
        """Used for network_format_registry support."""
 
1798
        return self.get_obj()()
 
1799
 
 
1800
 
1694
1801
class BranchHooks(Hooks):
1695
1802
    """A dictionary mapping hook name to a list of callables for branch hooks.
1696
1803
 
1723
1830
            "with a bzrlib.branch.PullResult object and only runs in the "
1724
1831
            "bzr client.", (0, 15), None))
1725
1832
        self.create_hook(HookPoint('pre_commit',
1726
 
            "Called after a commit is calculated but before it is is "
 
1833
            "Called after a commit is calculated but before it is "
1727
1834
            "completed. pre_commit is called with (local, master, old_revno, "
1728
1835
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1729
1836
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1766
1873
            "all are called with the url returned from the previous hook."
1767
1874
            "The order is however undefined.", (1, 9), None))
1768
1875
        self.create_hook(HookPoint('automatic_tag_name',
1769
 
            "Called to determine an automatic tag name for a revision."
 
1876
            "Called to determine an automatic tag name for a revision. "
1770
1877
            "automatic_tag_name is called with (branch, revision_id) and "
1771
1878
            "should return a tag name or None if no tag name could be "
1772
1879
            "determined. The first non-None tag name returned will be used.",
1863
1970
        return self.__dict__ == other.__dict__
1864
1971
 
1865
1972
    def __repr__(self):
1866
 
        if self.branch:
1867
 
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
1868
 
        else:
1869
 
            return "<%s of format:%s bzrdir:%s>" % (
1870
 
                self.__class__.__name__, self.branch,
1871
 
                self.format, self.bzrdir)
 
1973
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1872
1974
 
1873
1975
 
1874
1976
class SwitchHookParams(object):
2157
2259
        """See BranchFormat.get_format_description()."""
2158
2260
        return "Checkout reference format 1"
2159
2261
 
2160
 
    def get_reference(self, a_bzrdir):
 
2262
    def get_reference(self, a_bzrdir, name=None):
2161
2263
        """See BranchFormat.get_reference()."""
2162
 
        transport = a_bzrdir.get_branch_transport(None)
 
2264
        transport = a_bzrdir.get_branch_transport(None, name=name)
2163
2265
        return transport.get_bytes('location')
2164
2266
 
2165
 
    def set_reference(self, a_bzrdir, to_branch):
 
2267
    def set_reference(self, a_bzrdir, name, to_branch):
2166
2268
        """See BranchFormat.set_reference()."""
2167
 
        transport = a_bzrdir.get_branch_transport(None)
 
2269
        transport = a_bzrdir.get_branch_transport(None, name=name)
2168
2270
        location = transport.put_bytes('location', to_branch.base)
2169
2271
 
2170
2272
    def initialize(self, a_bzrdir, name=None, target_branch=None):
2221
2323
                raise AssertionError("wrong format %r found for %r" %
2222
2324
                    (format, self))
2223
2325
        if location is None:
2224
 
            location = self.get_reference(a_bzrdir)
 
2326
            location = self.get_reference(a_bzrdir, name)
2225
2327
        real_bzrdir = bzrdir.BzrDir.open(
2226
2328
            location, possible_transports=possible_transports)
2227
2329
        result = real_bzrdir.open_branch(name=name, 
2265
2367
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2266
2368
 
2267
2369
 
 
2370
class BranchWriteLockResult(LogicalLockResult):
 
2371
    """The result of write locking a branch.
 
2372
 
 
2373
    :ivar branch_token: The token obtained from the underlying branch lock, or
 
2374
        None.
 
2375
    :ivar unlock: A callable which will unlock the lock.
 
2376
    """
 
2377
 
 
2378
    def __init__(self, unlock, branch_token):
 
2379
        LogicalLockResult.__init__(self, unlock)
 
2380
        self.branch_token = branch_token
 
2381
 
 
2382
    def __repr__(self):
 
2383
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
2384
            self.unlock)
 
2385
 
 
2386
 
2268
2387
class BzrBranch(Branch, _RelockDebugMixin):
2269
2388
    """A branch stored in the actual filesystem.
2270
2389
 
2324
2443
        return self.control_files.is_locked()
2325
2444
 
2326
2445
    def lock_write(self, token=None):
 
2446
        """Lock the branch for write operations.
 
2447
 
 
2448
        :param token: A token to permit reacquiring a previously held and
 
2449
            preserved lock.
 
2450
        :return: A BranchWriteLockResult.
 
2451
        """
2327
2452
        if not self.is_locked():
2328
2453
            self._note_lock('w')
2329
2454
        # All-in-one needs to always unlock/lock.
2335
2460
        else:
2336
2461
            took_lock = False
2337
2462
        try:
2338
 
            return self.control_files.lock_write(token=token)
 
2463
            return BranchWriteLockResult(self.unlock,
 
2464
                self.control_files.lock_write(token=token))
2339
2465
        except:
2340
2466
            if took_lock:
2341
2467
                self.repository.unlock()
2342
2468
            raise
2343
2469
 
2344
2470
    def lock_read(self):
 
2471
        """Lock the branch for read operations.
 
2472
 
 
2473
        :return: A bzrlib.lock.LogicalLockResult.
 
2474
        """
2345
2475
        if not self.is_locked():
2346
2476
            self._note_lock('r')
2347
2477
        # All-in-one needs to always unlock/lock.
2354
2484
            took_lock = False
2355
2485
        try:
2356
2486
            self.control_files.lock_read()
 
2487
            return LogicalLockResult(self.unlock)
2357
2488
        except:
2358
2489
            if took_lock:
2359
2490
                self.repository.unlock()
2983
3114
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2984
3115
    """
2985
3116
 
 
3117
    @deprecated_method(deprecated_in((2, 3, 0)))
2986
3118
    def __int__(self):
2987
 
        # DEPRECATED: pull used to return the change in revno
 
3119
        """Return the relative change in revno.
 
3120
 
 
3121
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3122
        """
2988
3123
        return self.new_revno - self.old_revno
2989
3124
 
2990
3125
    def report(self, to_file):
3015
3150
        target, otherwise it will be None.
3016
3151
    """
3017
3152
 
 
3153
    @deprecated_method(deprecated_in((2, 3, 0)))
3018
3154
    def __int__(self):
3019
 
        # DEPRECATED: push used to return the change in revno
 
3155
        """Return the relative change in revno.
 
3156
 
 
3157
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3158
        """
3020
3159
        return self.new_revno - self.old_revno
3021
3160
 
3022
3161
    def report(self, to_file):
3145
3284
    _optimisers = []
3146
3285
    """The available optimised InterBranch types."""
3147
3286
 
3148
 
    @staticmethod
3149
 
    def _get_branch_formats_to_test():
3150
 
        """Return a tuple with the Branch formats to use when testing."""
3151
 
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
 
3287
    @classmethod
 
3288
    def _get_branch_formats_to_test(klass):
 
3289
        """Return an iterable of format tuples for testing.
 
3290
        
 
3291
        :return: An iterable of (from_format, to_format) to use when testing
 
3292
            this InterBranch class. Each InterBranch class should define this
 
3293
            method itself.
 
3294
        """
 
3295
        raise NotImplementedError(klass._get_branch_formats_to_test)
3152
3296
 
 
3297
    @needs_write_lock
3153
3298
    def pull(self, overwrite=False, stop_revision=None,
3154
3299
             possible_transports=None, local=False):
3155
3300
        """Mirror source into target branch.
3160
3305
        """
3161
3306
        raise NotImplementedError(self.pull)
3162
3307
 
 
3308
    @needs_write_lock
3163
3309
    def update_revisions(self, stop_revision=None, overwrite=False,
3164
3310
                         graph=None):
3165
3311
        """Pull in new perfect-fit revisions.
3173
3319
        """
3174
3320
        raise NotImplementedError(self.update_revisions)
3175
3321
 
 
3322
    @needs_write_lock
3176
3323
    def push(self, overwrite=False, stop_revision=None,
3177
3324
             _override_hook_source_branch=None):
3178
3325
        """Mirror the source branch into the target branch.
3181
3328
        """
3182
3329
        raise NotImplementedError(self.push)
3183
3330
 
 
3331
    @needs_write_lock
 
3332
    def copy_content_into(self, revision_id=None):
 
3333
        """Copy the content of source into target
 
3334
 
 
3335
        revision_id: if not None, the revision history in the new branch will
 
3336
                     be truncated to end with revision_id.
 
3337
        """
 
3338
        raise NotImplementedError(self.copy_content_into)
 
3339
 
3184
3340
 
3185
3341
class GenericInterBranch(InterBranch):
3186
 
    """InterBranch implementation that uses public Branch functions.
3187
 
    """
3188
 
 
3189
 
    @staticmethod
3190
 
    def _get_branch_formats_to_test():
3191
 
        return BranchFormat._default_format, BranchFormat._default_format
3192
 
 
 
3342
    """InterBranch implementation that uses public Branch functions."""
 
3343
 
 
3344
    @classmethod
 
3345
    def is_compatible(klass, source, target):
 
3346
        # GenericBranch uses the public API, so always compatible
 
3347
        return True
 
3348
 
 
3349
    @classmethod
 
3350
    def _get_branch_formats_to_test(klass):
 
3351
        return [(BranchFormat._default_format, BranchFormat._default_format)]
 
3352
 
 
3353
    @classmethod
 
3354
    def unwrap_format(klass, format):
 
3355
        if isinstance(format, remote.RemoteBranchFormat):
 
3356
            format._ensure_real()
 
3357
            return format._custom_format
 
3358
        return format                                                                                                  
 
3359
 
 
3360
    @needs_write_lock
 
3361
    def copy_content_into(self, revision_id=None):
 
3362
        """Copy the content of source into target
 
3363
 
 
3364
        revision_id: if not None, the revision history in the new branch will
 
3365
                     be truncated to end with revision_id.
 
3366
        """
 
3367
        self.source.update_references(self.target)
 
3368
        self.source._synchronize_history(self.target, revision_id)
 
3369
        try:
 
3370
            parent = self.source.get_parent()
 
3371
        except errors.InaccessibleParent, e:
 
3372
            mutter('parent was not accessible to copy: %s', e)
 
3373
        else:
 
3374
            if parent:
 
3375
                self.target.set_parent(parent)
 
3376
        if self.source._push_should_merge_tags():
 
3377
            self.source.tags.merge_to(self.target.tags)
 
3378
 
 
3379
    @needs_write_lock
3193
3380
    def update_revisions(self, stop_revision=None, overwrite=False,
3194
3381
        graph=None):
3195
3382
        """See InterBranch.update_revisions()."""
3196
 
        self.source.lock_read()
3197
 
        try:
3198
 
            other_revno, other_last_revision = self.source.last_revision_info()
3199
 
            stop_revno = None # unknown
3200
 
            if stop_revision is None:
3201
 
                stop_revision = other_last_revision
3202
 
                if _mod_revision.is_null(stop_revision):
3203
 
                    # if there are no commits, we're done.
3204
 
                    return
3205
 
                stop_revno = other_revno
3206
 
 
3207
 
            # what's the current last revision, before we fetch [and change it
3208
 
            # possibly]
3209
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
3210
 
            # we fetch here so that we don't process data twice in the common
3211
 
            # case of having something to pull, and so that the check for
3212
 
            # already merged can operate on the just fetched graph, which will
3213
 
            # be cached in memory.
3214
 
            self.target.fetch(self.source, stop_revision)
3215
 
            # Check to see if one is an ancestor of the other
3216
 
            if not overwrite:
3217
 
                if graph is None:
3218
 
                    graph = self.target.repository.get_graph()
3219
 
                if self.target._check_if_descendant_or_diverged(
3220
 
                        stop_revision, last_rev, graph, self.source):
3221
 
                    # stop_revision is a descendant of last_rev, but we aren't
3222
 
                    # overwriting, so we're done.
3223
 
                    return
3224
 
            if stop_revno is None:
3225
 
                if graph is None:
3226
 
                    graph = self.target.repository.get_graph()
3227
 
                this_revno, this_last_revision = \
3228
 
                        self.target.last_revision_info()
3229
 
                stop_revno = graph.find_distance_to_null(stop_revision,
3230
 
                                [(other_last_revision, other_revno),
3231
 
                                 (this_last_revision, this_revno)])
3232
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
3233
 
        finally:
3234
 
            self.source.unlock()
3235
 
 
 
3383
        other_revno, other_last_revision = self.source.last_revision_info()
 
3384
        stop_revno = None # unknown
 
3385
        if stop_revision is None:
 
3386
            stop_revision = other_last_revision
 
3387
            if _mod_revision.is_null(stop_revision):
 
3388
                # if there are no commits, we're done.
 
3389
                return
 
3390
            stop_revno = other_revno
 
3391
 
 
3392
        # what's the current last revision, before we fetch [and change it
 
3393
        # possibly]
 
3394
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3395
        # we fetch here so that we don't process data twice in the common
 
3396
        # case of having something to pull, and so that the check for
 
3397
        # already merged can operate on the just fetched graph, which will
 
3398
        # be cached in memory.
 
3399
        self.target.fetch(self.source, stop_revision)
 
3400
        # Check to see if one is an ancestor of the other
 
3401
        if not overwrite:
 
3402
            if graph is None:
 
3403
                graph = self.target.repository.get_graph()
 
3404
            if self.target._check_if_descendant_or_diverged(
 
3405
                    stop_revision, last_rev, graph, self.source):
 
3406
                # stop_revision is a descendant of last_rev, but we aren't
 
3407
                # overwriting, so we're done.
 
3408
                return
 
3409
        if stop_revno is None:
 
3410
            if graph is None:
 
3411
                graph = self.target.repository.get_graph()
 
3412
            this_revno, this_last_revision = \
 
3413
                    self.target.last_revision_info()
 
3414
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3415
                            [(other_last_revision, other_revno),
 
3416
                             (this_last_revision, this_revno)])
 
3417
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3418
 
 
3419
    @needs_write_lock
3236
3420
    def pull(self, overwrite=False, stop_revision=None,
3237
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3421
             possible_transports=None, run_hooks=True,
3238
3422
             _override_hook_target=None, local=False):
3239
 
        """See Branch.pull.
 
3423
        """Pull from source into self, updating my master if any.
3240
3424
 
3241
 
        :param _hook_master: Private parameter - set the branch to
3242
 
            be supplied as the master to pull hooks.
3243
3425
        :param run_hooks: Private parameter - if false, this branch
3244
3426
            is being called because it's the master of the primary branch,
3245
3427
            so it should not run its hooks.
3246
 
        :param _override_hook_target: Private parameter - set the branch to be
3247
 
            supplied as the target_branch to pull hooks.
3248
 
        :param local: Only update the local branch, and not the bound branch.
3249
3428
        """
3250
 
        # This type of branch can't be bound.
3251
 
        if local:
 
3429
        bound_location = self.target.get_bound_location()
 
3430
        if local and not bound_location:
3252
3431
            raise errors.LocalRequiresBoundBranch()
3253
 
        result = PullResult()
3254
 
        result.source_branch = self.source
3255
 
        if _override_hook_target is None:
3256
 
            result.target_branch = self.target
3257
 
        else:
3258
 
            result.target_branch = _override_hook_target
3259
 
        self.source.lock_read()
 
3432
        master_branch = None
 
3433
        if not local and bound_location and self.source.user_url != bound_location:
 
3434
            # not pulling from master, so we need to update master.
 
3435
            master_branch = self.target.get_master_branch(possible_transports)
 
3436
            master_branch.lock_write()
3260
3437
        try:
3261
 
            # We assume that during 'pull' the target repository is closer than
3262
 
            # the source one.
3263
 
            self.source.update_references(self.target)
3264
 
            graph = self.target.repository.get_graph(self.source.repository)
3265
 
            # TODO: Branch formats should have a flag that indicates 
3266
 
            # that revno's are expensive, and pull() should honor that flag.
3267
 
            # -- JRV20090506
3268
 
            result.old_revno, result.old_revid = \
3269
 
                self.target.last_revision_info()
3270
 
            self.target.update_revisions(self.source, stop_revision,
3271
 
                overwrite=overwrite, graph=graph)
3272
 
            # TODO: The old revid should be specified when merging tags, 
3273
 
            # so a tags implementation that versions tags can only 
3274
 
            # pull in the most recent changes. -- JRV20090506
3275
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3276
 
                overwrite)
3277
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3278
 
            if _hook_master:
3279
 
                result.master_branch = _hook_master
3280
 
                result.local_branch = result.target_branch
3281
 
            else:
3282
 
                result.master_branch = result.target_branch
3283
 
                result.local_branch = None
3284
 
            if run_hooks:
3285
 
                for hook in Branch.hooks['post_pull']:
3286
 
                    hook(result)
 
3438
            if master_branch:
 
3439
                # pull from source into master.
 
3440
                master_branch.pull(self.source, overwrite, stop_revision,
 
3441
                    run_hooks=False)
 
3442
            return self._pull(overwrite,
 
3443
                stop_revision, _hook_master=master_branch,
 
3444
                run_hooks=run_hooks,
 
3445
                _override_hook_target=_override_hook_target)
3287
3446
        finally:
3288
 
            self.source.unlock()
3289
 
        return result
 
3447
            if master_branch:
 
3448
                master_branch.unlock()
3290
3449
 
3291
3450
    def push(self, overwrite=False, stop_revision=None,
3292
3451
             _override_hook_source_branch=None):
3332
3491
                # push into the master from the source branch.
3333
3492
                self.source._basic_push(master_branch, overwrite, stop_revision)
3334
3493
                # and push into the target branch from the source. Note that we
3335
 
                # push from the source branch again, because its considered the
 
3494
                # push from the source branch again, because it's considered the
3336
3495
                # highest bandwidth repository.
3337
3496
                result = self.source._basic_push(self.target, overwrite,
3338
3497
                    stop_revision)
3354
3513
            _run_hooks()
3355
3514
            return result
3356
3515
 
3357
 
    @classmethod
3358
 
    def is_compatible(self, source, target):
3359
 
        # GenericBranch uses the public API, so always compatible
3360
 
        return True
3361
 
 
3362
 
 
3363
 
class InterToBranch5(GenericInterBranch):
3364
 
 
3365
 
    @staticmethod
3366
 
    def _get_branch_formats_to_test():
3367
 
        return BranchFormat._default_format, BzrBranchFormat5()
3368
 
 
3369
 
    def pull(self, overwrite=False, stop_revision=None,
3370
 
             possible_transports=None, run_hooks=True,
 
3516
    def _pull(self, overwrite=False, stop_revision=None,
 
3517
             possible_transports=None, _hook_master=None, run_hooks=True,
3371
3518
             _override_hook_target=None, local=False):
3372
 
        """Pull from source into self, updating my master if any.
3373
 
 
 
3519
        """See Branch.pull.
 
3520
 
 
3521
        This function is the core worker, used by GenericInterBranch.pull to
 
3522
        avoid duplication when pulling source->master and source->local.
 
3523
 
 
3524
        :param _hook_master: Private parameter - set the branch to
 
3525
            be supplied as the master to pull hooks.
3374
3526
        :param run_hooks: Private parameter - if false, this branch
3375
3527
            is being called because it's the master of the primary branch,
3376
3528
            so it should not run its hooks.
 
3529
        :param _override_hook_target: Private parameter - set the branch to be
 
3530
            supplied as the target_branch to pull hooks.
 
3531
        :param local: Only update the local branch, and not the bound branch.
3377
3532
        """
3378
 
        bound_location = self.target.get_bound_location()
3379
 
        if local and not bound_location:
 
3533
        # This type of branch can't be bound.
 
3534
        if local:
3380
3535
            raise errors.LocalRequiresBoundBranch()
3381
 
        master_branch = None
3382
 
        if not local and bound_location and self.source.user_url != bound_location:
3383
 
            # not pulling from master, so we need to update master.
3384
 
            master_branch = self.target.get_master_branch(possible_transports)
3385
 
            master_branch.lock_write()
 
3536
        result = PullResult()
 
3537
        result.source_branch = self.source
 
3538
        if _override_hook_target is None:
 
3539
            result.target_branch = self.target
 
3540
        else:
 
3541
            result.target_branch = _override_hook_target
 
3542
        self.source.lock_read()
3386
3543
        try:
3387
 
            if master_branch:
3388
 
                # pull from source into master.
3389
 
                master_branch.pull(self.source, overwrite, stop_revision,
3390
 
                    run_hooks=False)
3391
 
            return super(InterToBranch5, self).pull(overwrite,
3392
 
                stop_revision, _hook_master=master_branch,
3393
 
                run_hooks=run_hooks,
3394
 
                _override_hook_target=_override_hook_target)
 
3544
            # We assume that during 'pull' the target repository is closer than
 
3545
            # the source one.
 
3546
            self.source.update_references(self.target)
 
3547
            graph = self.target.repository.get_graph(self.source.repository)
 
3548
            # TODO: Branch formats should have a flag that indicates 
 
3549
            # that revno's are expensive, and pull() should honor that flag.
 
3550
            # -- JRV20090506
 
3551
            result.old_revno, result.old_revid = \
 
3552
                self.target.last_revision_info()
 
3553
            self.target.update_revisions(self.source, stop_revision,
 
3554
                overwrite=overwrite, graph=graph)
 
3555
            # TODO: The old revid should be specified when merging tags, 
 
3556
            # so a tags implementation that versions tags can only 
 
3557
            # pull in the most recent changes. -- JRV20090506
 
3558
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3559
                overwrite)
 
3560
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3561
            if _hook_master:
 
3562
                result.master_branch = _hook_master
 
3563
                result.local_branch = result.target_branch
 
3564
            else:
 
3565
                result.master_branch = result.target_branch
 
3566
                result.local_branch = None
 
3567
            if run_hooks:
 
3568
                for hook in Branch.hooks['post_pull']:
 
3569
                    hook(result)
3395
3570
        finally:
3396
 
            if master_branch:
3397
 
                master_branch.unlock()
 
3571
            self.source.unlock()
 
3572
        return result
3398
3573
 
3399
3574
 
3400
3575
InterBranch.register_optimiser(GenericInterBranch)
3401
 
InterBranch.register_optimiser(InterToBranch5)