1
# Copyright (C) 2005, 2006 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
from cStringIO import StringIO
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
22
from copy import deepcopy
23
from unittest import TestSuite
24
from warnings import warn
30
config as _mod_config,
35
revision as _mod_revision,
41
from bzrlib.config import BranchConfig, TreeConfig
42
from bzrlib.lockable_files import LockableFiles, TransportLock
45
from bzrlib.decorators import needs_read_lock, needs_write_lock
46
from bzrlib.errors import (BzrError, BzrCheckError, DivergedBranches,
47
HistoryMissing, InvalidRevisionId,
48
InvalidRevisionNumber, LockError, NoSuchFile,
49
NoSuchRevision, NoWorkingTree, NotVersionedError,
50
NotBranchError, UninitializableFormat,
51
UnlistableStore, UnlistableBranch,
53
from bzrlib.symbol_versioning import (deprecated_function,
57
zero_eight, zero_nine,
59
from bzrlib.trace import mutter, note
62
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
63
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
64
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
67
# TODO: Maybe include checks for common corruption of newlines, etc?
69
# TODO: Some operations like log might retrieve the same revisions
70
# repeatedly to calculate deltas. We could perhaps have a weakref
71
# cache in memory to make this faster. In general anything can be
72
# cached in memory between lock and unlock operations. .. nb thats
73
# what the transaction identity map provides
76
######################################################################
80
"""Branch holding a history of revisions.
83
Base directory/url of the branch.
85
hooks: An instance of BranchHooks.
87
# this is really an instance variable - FIXME move it there
91
def __init__(self, *ignored, **ignored_too):
92
raise NotImplementedError('The Branch class is abstract')
95
"""Break a lock if one is present from another instance.
97
Uses the ui factory to ask for confirmation if the lock may be from
100
This will probe the repository for its lock as well.
102
self.control_files.break_lock()
103
self.repository.break_lock()
104
master = self.get_master_branch()
105
if master is not None:
109
@deprecated_method(zero_eight)
110
def open_downlevel(base):
111
"""Open a branch which may be of an old format."""
112
return Branch.open(base, _unsupported=True)
115
def open(base, _unsupported=False):
116
"""Open the branch rooted at base.
118
For instance, if the branch is at URL/.bzr/branch,
119
Branch.open(URL) -> a Branch instance.
121
control = bzrdir.BzrDir.open(base, _unsupported)
122
return control.open_branch(_unsupported)
125
def open_containing(url):
126
"""Open an existing branch which contains url.
128
This probes for a branch at url, and searches upwards from there.
130
Basically we keep looking up until we find the control directory or
131
run into the root. If there isn't one, raises NotBranchError.
132
If there is one and it is either an unrecognised format or an unsupported
133
format, UnknownFormatError or UnsupportedFormatError are raised.
134
If there is one, it is returned, along with the unused portion of url.
136
control, relpath = bzrdir.BzrDir.open_containing(url)
137
return control.open_branch(), relpath
140
@deprecated_function(zero_eight)
141
def initialize(base):
142
"""Create a new working tree and branch, rooted at 'base' (url)
144
NOTE: This will soon be deprecated in favour of creation
147
return bzrdir.BzrDir.create_standalone_workingtree(base).branch
149
@deprecated_function(zero_eight)
150
def setup_caching(self, cache_root):
151
"""Subclasses that care about caching should override this, and set
152
up cached stores located under cache_root.
154
NOTE: This is unused.
158
def get_config(self):
159
return BranchConfig(self)
162
return self.get_config().get_nickname()
164
def _set_nick(self, nick):
165
self.get_config().set_user_option('nickname', nick)
167
nick = property(_get_nick, _set_nick)
170
raise NotImplementedError(self.is_locked)
172
def lock_write(self):
173
raise NotImplementedError(self.lock_write)
176
raise NotImplementedError(self.lock_read)
179
raise NotImplementedError(self.unlock)
181
def peek_lock_mode(self):
182
"""Return lock mode for the Branch: 'r', 'w' or None"""
183
raise NotImplementedError(self.peek_lock_mode)
185
def get_physical_lock_status(self):
186
raise NotImplementedError(self.get_physical_lock_status)
188
def abspath(self, name):
189
"""Return absolute filename for something in the branch
191
XXX: Robert Collins 20051017 what is this used for? why is it a branch
192
method and not a tree method.
194
raise NotImplementedError(self.abspath)
196
def bind(self, other):
197
"""Bind the local branch the other branch.
199
:param other: The branch to bind to
202
raise errors.UpgradeRequired(self.base)
205
def fetch(self, from_branch, last_revision=None, pb=None):
206
"""Copy revisions from from_branch into this branch.
208
:param from_branch: Where to copy from.
209
:param last_revision: What revision to stop at (None for at the end
211
:param pb: An optional progress bar to use.
213
Returns the copied revision count and the failed revisions in a tuple:
216
if self.base == from_branch.base:
219
nested_pb = ui.ui_factory.nested_progress_bar()
224
from_branch.lock_read()
226
if last_revision is None:
227
pb.update('get source history')
228
last_revision = from_branch.last_revision()
229
if last_revision is None:
230
last_revision = _mod_revision.NULL_REVISION
231
return self.repository.fetch(from_branch.repository,
232
revision_id=last_revision,
235
if nested_pb is not None:
239
def get_bound_location(self):
240
"""Return the URL of the branch we are bound to.
242
Older format branches cannot bind, please be sure to use a metadir
247
def get_commit_builder(self, parents, config=None, timestamp=None,
248
timezone=None, committer=None, revprops=None,
250
"""Obtain a CommitBuilder for this branch.
252
:param parents: Revision ids of the parents of the new revision.
253
:param config: Optional configuration to use.
254
:param timestamp: Optional timestamp recorded for commit.
255
:param timezone: Optional timezone for timestamp.
256
:param committer: Optional committer to set for commit.
257
:param revprops: Optional dictionary of revision properties.
258
:param revision_id: Optional revision id.
262
config = self.get_config()
264
return self.repository.get_commit_builder(self, parents, config,
265
timestamp, timezone, committer, revprops, revision_id)
267
def get_master_branch(self):
268
"""Return the branch we are bound to.
270
:return: Either a Branch, or None
274
def get_revision_delta(self, revno):
275
"""Return the delta for one revision.
277
The delta is relative to its mainline predecessor, or the
278
empty tree for revision 1.
280
assert isinstance(revno, int)
281
rh = self.revision_history()
282
if not (1 <= revno <= len(rh)):
283
raise InvalidRevisionNumber(revno)
284
return self.repository.get_revision_delta(rh[revno-1])
286
def get_root_id(self):
287
"""Return the id of this branches root"""
288
raise NotImplementedError(self.get_root_id)
290
def print_file(self, file, revision_id):
291
"""Print `file` to stdout."""
292
raise NotImplementedError(self.print_file)
294
def append_revision(self, *revision_ids):
295
raise NotImplementedError(self.append_revision)
297
def set_revision_history(self, rev_history):
298
raise NotImplementedError(self.set_revision_history)
300
def revision_history(self):
301
"""Return sequence of revision hashes on to this branch."""
302
raise NotImplementedError(self.revision_history)
305
"""Return current revision number for this branch.
307
That is equivalent to the number of revisions committed to
310
return len(self.revision_history())
313
"""Older format branches cannot bind or unbind."""
314
raise errors.UpgradeRequired(self.base)
316
def last_revision(self):
317
"""Return last revision id, or None"""
318
ph = self.revision_history()
324
def last_revision_info(self):
325
"""Return information about the last revision.
327
:return: A tuple (revno, last_revision_id).
329
rh = self.revision_history()
332
return (revno, rh[-1])
334
return (0, _mod_revision.NULL_REVISION)
336
def missing_revisions(self, other, stop_revision=None):
337
"""Return a list of new revisions that would perfectly fit.
339
If self and other have not diverged, return a list of the revisions
340
present in other, but missing from self.
342
self_history = self.revision_history()
343
self_len = len(self_history)
344
other_history = other.revision_history()
345
other_len = len(other_history)
346
common_index = min(self_len, other_len) -1
347
if common_index >= 0 and \
348
self_history[common_index] != other_history[common_index]:
349
raise DivergedBranches(self, other)
351
if stop_revision is None:
352
stop_revision = other_len
354
assert isinstance(stop_revision, int)
355
if stop_revision > other_len:
356
raise errors.NoSuchRevision(self, stop_revision)
357
return other_history[self_len:stop_revision]
359
def update_revisions(self, other, stop_revision=None):
360
"""Pull in new perfect-fit revisions.
362
:param other: Another Branch to pull from
363
:param stop_revision: Updated until the given revision
366
raise NotImplementedError(self.update_revisions)
368
def revision_id_to_revno(self, revision_id):
369
"""Given a revision id, return its revno"""
370
if revision_id is None:
372
history = self.revision_history()
374
return history.index(revision_id) + 1
376
raise bzrlib.errors.NoSuchRevision(self, revision_id)
378
def get_rev_id(self, revno, history=None):
379
"""Find the revision id of the specified revno."""
383
history = self.revision_history()
384
if revno <= 0 or revno > len(history):
385
raise bzrlib.errors.NoSuchRevision(self, revno)
386
return history[revno - 1]
388
def pull(self, source, overwrite=False, stop_revision=None):
389
"""Mirror source into this branch.
391
This branch is considered to be 'local', having low latency.
393
raise NotImplementedError(self.pull)
395
def push(self, target, overwrite=False, stop_revision=None):
396
"""Mirror this branch into target.
398
This branch is considered to be 'local', having low latency.
400
raise NotImplementedError(self.push)
402
def basis_tree(self):
403
"""Return `Tree` object for last revision."""
404
return self.repository.revision_tree(self.last_revision())
406
def rename_one(self, from_rel, to_rel):
409
This can change the directory or the filename or both.
411
raise NotImplementedError(self.rename_one)
413
def move(self, from_paths, to_name):
416
to_name must exist as a versioned directory.
418
If to_name exists and is a directory, the files are moved into
419
it, keeping their old names. If it is a directory,
421
Note that to_name is only the last component of the new name;
422
this doesn't change the directory.
424
This returns a list of (from_path, to_path) pairs for each
427
raise NotImplementedError(self.move)
429
def get_parent(self):
430
"""Return the parent location of the branch.
432
This is the default location for push/pull/missing. The usual
433
pattern is that the user can override it by specifying a
436
raise NotImplementedError(self.get_parent)
438
def get_submit_branch(self):
439
"""Return the submit location of the branch.
441
This is the default location for bundle. The usual
442
pattern is that the user can override it by specifying a
445
return self.get_config().get_user_option('submit_branch')
447
def set_submit_branch(self, location):
448
"""Return the submit location of the branch.
450
This is the default location for bundle. The usual
451
pattern is that the user can override it by specifying a
454
self.get_config().set_user_option('submit_branch', location)
456
def get_push_location(self):
457
"""Return the None or the location to push this branch to."""
458
raise NotImplementedError(self.get_push_location)
460
def set_push_location(self, location):
461
"""Set a new push location for this branch."""
462
raise NotImplementedError(self.set_push_location)
464
def set_parent(self, url):
465
raise NotImplementedError(self.set_parent)
469
"""Synchronise this branch with the master branch if any.
471
:return: None or the last_revision pivoted out during the update.
475
def check_revno(self, revno):
477
Check whether a revno corresponds to any revision.
478
Zero (the NULL revision) is considered valid.
481
self.check_real_revno(revno)
483
def check_real_revno(self, revno):
485
Check whether a revno corresponds to a real revision.
486
Zero (the NULL revision) is considered invalid
488
if revno < 1 or revno > self.revno():
489
raise InvalidRevisionNumber(revno)
492
def clone(self, *args, **kwargs):
493
"""Clone this branch into to_bzrdir preserving all semantic values.
495
revision_id: if not None, the revision history in the new branch will
496
be truncated to end with revision_id.
498
# for API compatibility, until 0.8 releases we provide the old api:
499
# def clone(self, to_location, revision=None, basis_branch=None, to_branch_format=None):
500
# after 0.8 releases, the *args and **kwargs should be changed:
501
# def clone(self, to_bzrdir, revision_id=None):
502
if (kwargs.get('to_location', None) or
503
kwargs.get('revision', None) or
504
kwargs.get('basis_branch', None) or
505
(len(args) and isinstance(args[0], basestring))):
506
# backwards compatibility api:
507
warn("Branch.clone() has been deprecated for BzrDir.clone() from"
508
" bzrlib 0.8.", DeprecationWarning, stacklevel=3)
511
basis_branch = args[2]
513
basis_branch = kwargs.get('basis_branch', None)
515
basis = basis_branch.bzrdir
520
revision_id = args[1]
522
revision_id = kwargs.get('revision', None)
527
# no default to raise if not provided.
528
url = kwargs.get('to_location')
529
return self.bzrdir.clone(url,
530
revision_id=revision_id,
531
basis=basis).open_branch()
533
# generate args by hand
535
revision_id = args[1]
537
revision_id = kwargs.get('revision_id', None)
541
# no default to raise if not provided.
542
to_bzrdir = kwargs.get('to_bzrdir')
543
result = self._format.initialize(to_bzrdir)
544
self.copy_content_into(result, revision_id=revision_id)
548
def sprout(self, to_bzrdir, revision_id=None):
549
"""Create a new line of development from the branch, into to_bzrdir.
551
revision_id: if not None, the revision history in the new branch will
552
be truncated to end with revision_id.
554
result = self._format.initialize(to_bzrdir)
555
self.copy_content_into(result, revision_id=revision_id)
556
result.set_parent(self.bzrdir.root_transport.base)
560
def copy_content_into(self, destination, revision_id=None):
561
"""Copy the content of self into destination.
563
revision_id: if not None, the revision history in the new branch will
564
be truncated to end with revision_id.
566
if revision_id is None:
567
revision_id = self.last_revision()
568
destination.set_last_revision(revision_id)
570
parent = self.get_parent()
571
except errors.InaccessibleParent, e:
572
mutter('parent was not accessible to copy: %s', e)
575
destination.set_parent(parent)
579
"""Check consistency of the branch.
581
In particular this checks that revisions given in the revision-history
582
do actually match up in the revision graph, and that they're all
583
present in the repository.
585
Callers will typically also want to check the repository.
587
:return: A BranchCheckResult.
589
mainline_parent_id = None
590
for revision_id in self.revision_history():
592
revision = self.repository.get_revision(revision_id)
593
except errors.NoSuchRevision, e:
594
raise errors.BzrCheckError("mainline revision {%s} not in repository"
596
# In general the first entry on the revision history has no parents.
597
# But it's not illegal for it to have parents listed; this can happen
598
# in imports from Arch when the parents weren't reachable.
599
if mainline_parent_id is not None:
600
if mainline_parent_id not in revision.parent_ids:
601
raise errors.BzrCheckError("previous revision {%s} not listed among "
603
% (mainline_parent_id, revision_id))
604
mainline_parent_id = revision_id
605
return BranchCheckResult(self)
607
def _get_checkout_format(self):
608
"""Return the most suitable metadir for a checkout of this branch.
609
Weaves are used if this branch's repostory uses weaves.
611
if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
612
from bzrlib import repository
613
format = bzrdir.BzrDirMetaFormat1()
614
format.repository_format = repository.RepositoryFormat7()
616
format = self.repository.bzrdir.cloning_metadir()
619
def create_checkout(self, to_location, revision_id=None,
621
"""Create a checkout of a branch.
623
:param to_location: The url to produce the checkout at
624
:param revision_id: The revision to check out
625
:param lightweight: If True, produce a lightweight checkout, otherwise,
626
produce a bound branch (heavyweight checkout)
627
:return: The tree of the created checkout
629
t = transport.get_transport(to_location)
632
except errors.FileExists:
635
checkout = bzrdir.BzrDirMetaFormat1().initialize_on_transport(t)
636
BranchReferenceFormat().initialize(checkout, self)
638
format = self._get_checkout_format()
639
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
640
to_location, force_new_tree=False, format=format)
641
checkout = checkout_branch.bzrdir
642
checkout_branch.bind(self)
643
# pull up to the specified revision_id to set the initial
644
# branch tip correctly, and seed it with history.
645
checkout_branch.pull(self, stop_revision=revision_id)
646
return checkout.create_workingtree(revision_id)
649
class BranchFormat(object):
650
"""An encapsulation of the initialization and open routines for a format.
652
Formats provide three things:
653
* An initialization routine,
657
Formats are placed in an dict by their format string for reference
658
during branch opening. Its not required that these be instances, they
659
can be classes themselves with class methods - it simply depends on
660
whether state is needed for a given format or not.
662
Once a format is deprecated, just deprecate the initialize and open
663
methods on the format class. Do not deprecate the object, as the
664
object will be created every time regardless.
667
_default_format = None
668
"""The default format used for new branches."""
671
"""The known formats."""
674
def find_format(klass, a_bzrdir):
675
"""Return the format for the branch object in a_bzrdir."""
677
transport = a_bzrdir.get_branch_transport(None)
678
format_string = transport.get("format").read()
679
return klass._formats[format_string]
681
raise NotBranchError(path=transport.base)
683
raise errors.UnknownFormatError(format=format_string)
686
def get_default_format(klass):
687
"""Return the current default format."""
688
return klass._default_format
690
def get_format_string(self):
691
"""Return the ASCII format string that identifies this format."""
692
raise NotImplementedError(self.get_format_string)
694
def get_format_description(self):
695
"""Return the short format description for this format."""
696
raise NotImplementedError(self.get_format_description)
698
def initialize(self, a_bzrdir):
699
"""Create a branch of this format in a_bzrdir."""
700
raise NotImplementedError(self.initialize)
702
def is_supported(self):
703
"""Is this format supported?
705
Supported formats can be initialized and opened.
706
Unsupported formats may not support initialization or committing or
707
some other features depending on the reason for not being supported.
711
def open(self, a_bzrdir, _found=False):
712
"""Return the branch object for a_bzrdir
714
_found is a private parameter, do not use it. It is used to indicate
715
if format probing has already be done.
717
raise NotImplementedError(self.open)
720
def register_format(klass, format):
721
klass._formats[format.get_format_string()] = format
724
def set_default_format(klass, format):
725
klass._default_format = format
728
def unregister_format(klass, format):
729
assert klass._formats[format.get_format_string()] is format
730
del klass._formats[format.get_format_string()]
733
return self.get_format_string().rstrip()
736
class BranchHooks(dict):
737
"""A dictionary mapping hook name to a list of callables for branch hooks.
739
e.g. ['set_rh'] Is the list of items to be called when the
740
set_revision_history function is invoked.
744
"""Create the default hooks.
746
These are all empty initially, because by default nothing should get
750
# invoked whenever the revision history has been set
751
# with set_revision_history. The api signature is
752
# (branch, revision_history), and the branch will
753
# be write-locked. Introduced in 0.15.
756
def install_hook(self, hook_name, a_callable):
757
"""Install a_callable in to the hook hook_name.
759
:param hook_name: A hook name. See the __init__ method of BranchHooks
760
for the complete list of hooks.
761
:param a_callable: The callable to be invoked when the hook triggers.
762
The exact signature will depend on the hook - see the __init__
763
method of BranchHooks for details on each hook.
766
self[hook_name].append(a_callable)
768
raise errors.UnknownHook('branch', hook_name)
771
# install the default hooks into the Branch class.
772
Branch.hooks = BranchHooks()
775
class BzrBranchFormat4(BranchFormat):
776
"""Bzr branch format 4.
779
- a revision-history file.
780
- a branch-lock lock file [ to be shared with the bzrdir ]
783
def get_format_description(self):
784
"""See BranchFormat.get_format_description()."""
785
return "Branch format 4"
787
def initialize(self, a_bzrdir):
788
"""Create a branch of this format in a_bzrdir."""
789
mutter('creating branch in %s', a_bzrdir.transport.base)
790
branch_transport = a_bzrdir.get_branch_transport(self)
791
utf8_files = [('revision-history', ''),
794
control_files = lockable_files.LockableFiles(branch_transport,
795
'branch-lock', lockable_files.TransportLock)
796
control_files.create_lock()
797
control_files.lock_write()
799
for file, content in utf8_files:
800
control_files.put_utf8(file, content)
802
control_files.unlock()
803
return self.open(a_bzrdir, _found=True)
806
super(BzrBranchFormat4, self).__init__()
807
self._matchingbzrdir = bzrdir.BzrDirFormat6()
809
def open(self, a_bzrdir, _found=False):
810
"""Return the branch object for a_bzrdir
812
_found is a private parameter, do not use it. It is used to indicate
813
if format probing has already be done.
816
# we are being called directly and must probe.
817
raise NotImplementedError
818
return BzrBranch(_format=self,
819
_control_files=a_bzrdir._control_files,
821
_repository=a_bzrdir.open_repository())
824
return "Bazaar-NG branch format 4"
827
class BzrBranchFormat5(BranchFormat):
828
"""Bzr branch format 5.
831
- a revision-history file.
833
- a lock dir guarding the branch itself
834
- all of this stored in a branch/ subdirectory
835
- works with shared repositories.
837
This format is new in bzr 0.8.
840
def get_format_string(self):
841
"""See BranchFormat.get_format_string()."""
842
return "Bazaar-NG branch format 5\n"
844
def get_format_description(self):
845
"""See BranchFormat.get_format_description()."""
846
return "Branch format 5"
848
def initialize(self, a_bzrdir):
849
"""Create a branch of this format in a_bzrdir."""
850
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
851
branch_transport = a_bzrdir.get_branch_transport(self)
852
utf8_files = [('revision-history', ''),
855
control_files = lockable_files.LockableFiles(branch_transport, 'lock',
857
control_files.create_lock()
858
control_files.lock_write()
859
control_files.put_utf8('format', self.get_format_string())
861
for file, content in utf8_files:
862
control_files.put_utf8(file, content)
864
control_files.unlock()
865
return self.open(a_bzrdir, _found=True, )
868
super(BzrBranchFormat5, self).__init__()
869
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
871
def open(self, a_bzrdir, _found=False):
872
"""Return the branch object for a_bzrdir
874
_found is a private parameter, do not use it. It is used to indicate
875
if format probing has already be done.
878
format = BranchFormat.find_format(a_bzrdir)
879
assert format.__class__ == self.__class__
880
transport = a_bzrdir.get_branch_transport(None)
881
control_files = lockable_files.LockableFiles(transport, 'lock',
883
return BzrBranch5(_format=self,
884
_control_files=control_files,
886
_repository=a_bzrdir.find_repository())
889
return "Bazaar-NG Metadir branch format 5"
892
class BzrBranchFormat6(BzrBranchFormat5):
893
"""Branch format with last-revision
895
Unlike previous formats, this has no explicit revision history, instead
896
the left-parent revision history is used.
899
def get_format_string(self):
900
"""See BranchFormat.get_format_string()."""
901
return "Bazaar-NG branch format 6\n"
903
def get_format_description(self):
904
"""See BranchFormat.get_format_description()."""
905
return "Branch format 6"
907
def initialize(self, a_bzrdir):
908
"""Create a branch of this format in a_bzrdir."""
909
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
910
branch_transport = a_bzrdir.get_branch_transport(self)
911
utf8_files = [('last-revision', 'null:\n'),
915
control_files = lockable_files.LockableFiles(branch_transport, 'lock',
917
control_files.create_lock()
918
control_files.lock_write()
919
control_files.put_utf8('format', self.get_format_string())
921
for file, content in utf8_files:
922
control_files.put_utf8(file, content)
924
control_files.unlock()
925
return self.open(a_bzrdir, _found=True, )
927
def open(self, a_bzrdir, _found=False):
928
"""Return the branch object for a_bzrdir
930
_found is a private parameter, do not use it. It is used to indicate
931
if format probing has already be done.
934
format = BranchFormat.find_format(a_bzrdir)
935
assert format.__class__ == self.__class__
936
transport = a_bzrdir.get_branch_transport(None)
937
control_files = lockable_files.LockableFiles(transport, 'lock',
939
return BzrBranch6(_format=self,
940
_control_files=control_files,
942
_repository=a_bzrdir.find_repository())
945
class BranchReferenceFormat(BranchFormat):
946
"""Bzr branch reference format.
948
Branch references are used in implementing checkouts, they
949
act as an alias to the real branch which is at some other url.
956
def get_format_string(self):
957
"""See BranchFormat.get_format_string()."""
958
return "Bazaar-NG Branch Reference Format 1\n"
960
def get_format_description(self):
961
"""See BranchFormat.get_format_description()."""
962
return "Checkout reference format 1"
964
def initialize(self, a_bzrdir, target_branch=None):
965
"""Create a branch of this format in a_bzrdir."""
966
if target_branch is None:
967
# this format does not implement branch itself, thus the implicit
968
# creation contract must see it as uninitializable
969
raise errors.UninitializableFormat(self)
970
mutter('creating branch reference in %s', a_bzrdir.transport.base)
971
branch_transport = a_bzrdir.get_branch_transport(self)
972
branch_transport.put_bytes('location',
973
target_branch.bzrdir.root_transport.base)
974
branch_transport.put_bytes('format', self.get_format_string())
975
return self.open(a_bzrdir, _found=True)
978
super(BranchReferenceFormat, self).__init__()
979
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
981
def _make_reference_clone_function(format, a_branch):
982
"""Create a clone() routine for a branch dynamically."""
983
def clone(to_bzrdir, revision_id=None):
984
"""See Branch.clone()."""
985
return format.initialize(to_bzrdir, a_branch)
986
# cannot obey revision_id limits when cloning a reference ...
987
# FIXME RBC 20060210 either nuke revision_id for clone, or
988
# emit some sort of warning/error to the caller ?!
991
def open(self, a_bzrdir, _found=False):
992
"""Return the branch that the branch reference in a_bzrdir points at.
994
_found is a private parameter, do not use it. It is used to indicate
995
if format probing has already be done.
998
format = BranchFormat.find_format(a_bzrdir)
999
assert format.__class__ == self.__class__
1000
transport = a_bzrdir.get_branch_transport(None)
1001
real_bzrdir = bzrdir.BzrDir.open(transport.get('location').read())
1002
result = real_bzrdir.open_branch()
1003
# this changes the behaviour of result.clone to create a new reference
1004
# rather than a copy of the content of the branch.
1005
# I did not use a proxy object because that needs much more extensive
1006
# testing, and we are only changing one behaviour at the moment.
1007
# If we decide to alter more behaviours - i.e. the implicit nickname
1008
# then this should be refactored to introduce a tested proxy branch
1009
# and a subclass of that for use in overriding clone() and ....
1011
result.clone = self._make_reference_clone_function(result)
1015
# formats which have no format string are not discoverable
1016
# and not independently creatable, so are not registered.
1017
__default_format = BzrBranchFormat5()
1018
BranchFormat.register_format(__default_format)
1019
BranchFormat.register_format(BranchReferenceFormat())
1020
BranchFormat.register_format(BzrBranchFormat6())
1021
BranchFormat.set_default_format(BzrBranchFormat6())
1022
_legacy_formats = [BzrBranchFormat4(),
1025
class BzrBranch(Branch):
1026
"""A branch stored in the actual filesystem.
1028
Note that it's "local" in the context of the filesystem; it doesn't
1029
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1030
it's writable, and can be accessed via the normal filesystem API.
1033
def __init__(self, transport=DEPRECATED_PARAMETER, init=DEPRECATED_PARAMETER,
1034
relax_version_check=DEPRECATED_PARAMETER, _format=None,
1035
_control_files=None, a_bzrdir=None, _repository=None):
1036
"""Create new branch object at a particular location.
1038
transport -- A Transport object, defining how to access files.
1040
init -- If True, create new control files in a previously
1041
unversioned directory. If False, the branch must already
1044
relax_version_check -- If true, the usual check for the branch
1045
version is not applied. This is intended only for
1046
upgrade/recovery type use; it's not guaranteed that
1047
all operations will work on old format branches.
1049
if a_bzrdir is None:
1050
self.bzrdir = bzrdir.BzrDir.open(transport.base)
1052
self.bzrdir = a_bzrdir
1053
self._transport = self.bzrdir.transport.clone('..')
1054
self._base = self._transport.base
1055
self._format = _format
1056
if _control_files is None:
1057
raise ValueError('BzrBranch _control_files is None')
1058
self.control_files = _control_files
1059
if deprecated_passed(init):
1060
warn("BzrBranch.__init__(..., init=XXX): The init parameter is "
1061
"deprecated as of bzr 0.8. Please use Branch.create().",
1065
# this is slower than before deprecation, oh well never mind.
1066
# -> its deprecated.
1067
self._initialize(transport.base)
1068
self._check_format(_format)
1069
if deprecated_passed(relax_version_check):
1070
warn("BzrBranch.__init__(..., relax_version_check=XXX_: The "
1071
"relax_version_check parameter is deprecated as of bzr 0.8. "
1072
"Please use BzrDir.open_downlevel, or a BzrBranchFormat's "
1076
if (not relax_version_check
1077
and not self._format.is_supported()):
1078
raise errors.UnsupportedFormatError(format=fmt)
1079
if deprecated_passed(transport):
1080
warn("BzrBranch.__init__(transport=XXX...): The transport "
1081
"parameter is deprecated as of bzr 0.8. "
1082
"Please use Branch.open, or bzrdir.open_branch().",
1085
self.repository = _repository
1088
return '%s(%r)' % (self.__class__.__name__, self.base)
1092
def _get_base(self):
1095
base = property(_get_base, doc="The URL for the root of this branch.")
1097
def _finish_transaction(self):
1098
"""Exit the current transaction."""
1099
return self.control_files._finish_transaction()
1101
def get_transaction(self):
1102
"""Return the current active transaction.
1104
If no transaction is active, this returns a passthrough object
1105
for which all data is immediately flushed and no caching happens.
1107
# this is an explicit function so that we can do tricky stuff
1108
# when the storage in rev_storage is elsewhere.
1109
# we probably need to hook the two 'lock a location' and
1110
# 'have a transaction' together more delicately, so that
1111
# we can have two locks (branch and storage) and one transaction
1112
# ... and finishing the transaction unlocks both, but unlocking
1113
# does not. - RBC 20051121
1114
return self.control_files.get_transaction()
1116
def _set_transaction(self, transaction):
1117
"""Set a new active transaction."""
1118
return self.control_files._set_transaction(transaction)
1120
def abspath(self, name):
1121
"""See Branch.abspath."""
1122
return self.control_files._transport.abspath(name)
1124
def _check_format(self, format):
1125
"""Identify the branch format if needed.
1127
The format is stored as a reference to the format object in
1128
self._format for code that needs to check it later.
1130
The format parameter is either None or the branch format class
1131
used to open this branch.
1133
FIXME: DELETE THIS METHOD when pre 0.8 support is removed.
1136
format = BranchFormat.find_format(self.bzrdir)
1137
self._format = format
1138
mutter("got branch format %s", self._format)
1141
def get_root_id(self):
1142
"""See Branch.get_root_id."""
1143
tree = self.repository.revision_tree(self.last_revision())
1144
return tree.inventory.root.file_id
1146
def is_locked(self):
1147
return self.control_files.is_locked()
1149
def lock_write(self):
1150
self.repository.lock_write()
1152
self.control_files.lock_write()
1154
self.repository.unlock()
1157
def lock_read(self):
1158
self.repository.lock_read()
1160
self.control_files.lock_read()
1162
self.repository.unlock()
1166
# TODO: test for failed two phase locks. This is known broken.
1168
self.control_files.unlock()
1170
self.repository.unlock()
1172
def peek_lock_mode(self):
1173
if self.control_files._lock_count == 0:
1176
return self.control_files._lock_mode
1178
def get_physical_lock_status(self):
1179
return self.control_files.get_physical_lock_status()
1182
def print_file(self, file, revision_id):
1183
"""See Branch.print_file."""
1184
return self.repository.print_file(file, revision_id)
1187
def append_revision(self, *revision_ids):
1188
"""See Branch.append_revision."""
1189
for revision_id in revision_ids:
1190
_mod_revision.check_not_reserved_id(revision_id)
1191
mutter("add {%s} to revision-history" % revision_id)
1192
rev_history = self.revision_history()
1193
rev_history.extend(revision_ids)
1194
self.set_revision_history(rev_history)
1197
def set_revision_history(self, rev_history):
1198
"""See Branch.set_revision_history."""
1199
self.control_files.put_utf8(
1200
'revision-history', '\n'.join(rev_history))
1201
transaction = self.get_transaction()
1202
history = transaction.map.find_revision_history()
1203
if history is not None:
1204
# update the revision history in the identity map.
1205
history[:] = list(rev_history)
1206
# this call is disabled because revision_history is
1207
# not really an object yet, and the transaction is for objects.
1208
# transaction.register_dirty(history)
1210
transaction.map.add_revision_history(rev_history)
1211
# this call is disabled because revision_history is
1212
# not really an object yet, and the transaction is for objects.
1213
# transaction.register_clean(history)
1214
for hook in Branch.hooks['set_rh']:
1215
hook(self, rev_history)
1218
def set_last_revision(self, revision_id):
1219
self.set_revision_history(self._lefthand_history(revision_id))
1222
def revision_history(self):
1223
"""See Branch.revision_history."""
1224
transaction = self.get_transaction()
1225
history = transaction.map.find_revision_history()
1226
if history is not None:
1227
# mutter("cache hit for revision-history in %s", self)
1228
return list(history)
1229
decode_utf8 = cache_utf8.decode
1230
history = [decode_utf8(l.rstrip('\r\n')) for l in
1231
self.control_files.get('revision-history').readlines()]
1232
transaction.map.add_revision_history(history)
1233
# this call is disabled because revision_history is
1234
# not really an object yet, and the transaction is for objects.
1235
# transaction.register_clean(history, precious=True)
1236
return list(history)
1238
def _lefthand_history(self, revision_id, last_rev=None,
1240
# stop_revision must be a descendant of last_revision
1241
stop_graph = self.repository.get_revision_graph(revision_id)
1242
if last_rev is not None and last_rev not in stop_graph:
1243
# our previous tip is not merged into stop_revision
1244
raise errors.DivergedBranches(self, other_branch)
1245
# make a new revision history from the graph
1246
current_rev_id = revision_id
1248
while current_rev_id not in (None, _mod_revision.NULL_REVISION):
1249
new_history.append(current_rev_id)
1250
current_rev_id_parents = stop_graph[current_rev_id]
1252
current_rev_id = current_rev_id_parents[0]
1254
current_rev_id = None
1255
new_history.reverse()
1259
def generate_revision_history(self, revision_id, last_rev=None,
1261
"""Create a new revision history that will finish with revision_id.
1263
:param revision_id: the new tip to use.
1264
:param last_rev: The previous last_revision. If not None, then this
1265
must be a ancestory of revision_id, or DivergedBranches is raised.
1266
:param other_branch: The other branch that DivergedBranches should
1267
raise with respect to.
1269
self.set_revision_history(self._lefthand_history(revision_id,
1270
last_rev, other_branch))
1273
def update_revisions(self, other, stop_revision=None):
1274
"""See Branch.update_revisions."""
1277
if stop_revision is None:
1278
stop_revision = other.last_revision()
1279
if stop_revision is None:
1280
# if there are no commits, we're done.
1282
# whats the current last revision, before we fetch [and change it
1284
last_rev = self.last_revision()
1285
# we fetch here regardless of whether we need to so that we pickup
1287
self.fetch(other, stop_revision)
1288
my_ancestry = self.repository.get_ancestry(last_rev)
1289
if stop_revision in my_ancestry:
1290
# last_revision is a descendant of stop_revision
1292
self.generate_revision_history(stop_revision, last_rev=last_rev,
1297
def basis_tree(self):
1298
"""See Branch.basis_tree."""
1299
return self.repository.revision_tree(self.last_revision())
1301
@deprecated_method(zero_eight)
1302
def working_tree(self):
1303
"""Create a Working tree object for this branch."""
1305
from bzrlib.transport.local import LocalTransport
1306
if (self.base.find('://') != -1 or
1307
not isinstance(self._transport, LocalTransport)):
1308
raise NoWorkingTree(self.base)
1309
return self.bzrdir.open_workingtree()
1312
def pull(self, source, overwrite=False, stop_revision=None):
1313
"""See Branch.pull."""
1316
old_count = self.last_revision_info()[0]
1318
self.update_revisions(source, stop_revision)
1319
except DivergedBranches:
1323
self.set_revision_history(source.revision_history())
1324
new_count = self.last_revision_info()[0]
1325
return new_count - old_count
1329
def _get_parent_location(self):
1330
_locs = ['parent', 'pull', 'x-pull']
1333
return self.control_files.get(l).read().strip('\n')
1339
def push(self, target, overwrite=False, stop_revision=None):
1340
"""See Branch.push."""
1343
old_count = len(target.revision_history())
1345
target.update_revisions(self, stop_revision)
1346
except DivergedBranches:
1350
target.set_revision_history(self.revision_history())
1351
new_count = len(target.revision_history())
1352
return new_count - old_count
1356
def get_parent(self):
1357
"""See Branch.get_parent."""
1359
assert self.base[-1] == '/'
1360
parent = self._get_parent_location()
1363
# This is an old-format absolute path to a local branch
1364
# turn it into a url
1365
if parent.startswith('/'):
1366
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1368
return urlutils.join(self.base[:-1], parent)
1369
except errors.InvalidURLJoin, e:
1370
raise errors.InaccessibleParent(parent, self.base)
1372
def get_push_location(self):
1373
"""See Branch.get_push_location."""
1374
push_loc = self.get_config().get_user_option('push_location')
1377
def set_push_location(self, location):
1378
"""See Branch.set_push_location."""
1379
self.get_config().set_user_option(
1380
'push_location', location,
1381
store=_mod_config.STORE_LOCATION_NORECURSE)
1384
def set_parent(self, url):
1385
"""See Branch.set_parent."""
1386
# TODO: Maybe delete old location files?
1387
# URLs should never be unicode, even on the local fs,
1388
# FIXUP this and get_parent in a future branch format bump:
1389
# read and rewrite the file, and have the new format code read
1390
# using .get not .get_utf8. RBC 20060125
1392
if isinstance(url, unicode):
1394
url = url.encode('ascii')
1395
except UnicodeEncodeError:
1396
raise bzrlib.errors.InvalidURL(url,
1397
"Urls must be 7-bit ascii, "
1398
"use bzrlib.urlutils.escape")
1400
url = urlutils.relative_url(self.base, url)
1401
self._set_parent_location(url)
1403
def _set_parent_location(self, url):
1405
self.control_files._transport.delete('parent')
1407
assert isinstance(url, str)
1408
self.control_files.put('parent', StringIO(url + '\n'))
1410
@deprecated_function(zero_nine)
1411
def tree_config(self):
1412
"""DEPRECATED; call get_config instead.
1413
TreeConfig has become part of BranchConfig."""
1414
return TreeConfig(self)
1417
class BzrBranch5(BzrBranch):
1418
"""A format 5 branch. This supports new features over plan branches.
1420
It has support for a master_branch which is the data for bound branches.
1428
super(BzrBranch5, self).__init__(_format=_format,
1429
_control_files=_control_files,
1431
_repository=_repository)
1434
def pull(self, source, overwrite=False, stop_revision=None):
1435
"""Extends branch.pull to be bound branch aware."""
1436
bound_location = self.get_bound_location()
1437
if source.base != bound_location:
1438
# not pulling from master, so we need to update master.
1439
master_branch = self.get_master_branch()
1441
master_branch.pull(source)
1442
source = master_branch
1443
return super(BzrBranch5, self).pull(source, overwrite, stop_revision)
1446
def push(self, target, overwrite=False, stop_revision=None):
1447
"""Updates branch.push to be bound branch aware."""
1448
bound_location = target.get_bound_location()
1449
if target.base != bound_location:
1450
# not pushing to master, so we need to update master.
1451
master_branch = target.get_master_branch()
1453
# push into the master from this branch.
1454
super(BzrBranch5, self).push(master_branch, overwrite,
1456
# and push into the target branch from this. Note that we push from
1457
# this branch again, because its considered the highest bandwidth
1459
return super(BzrBranch5, self).push(target, overwrite, stop_revision)
1461
def get_bound_location(self):
1463
return self.control_files.get_utf8('bound').read()[:-1]
1464
except errors.NoSuchFile:
1468
def get_master_branch(self):
1469
"""Return the branch we are bound to.
1471
:return: Either a Branch, or None
1473
This could memoise the branch, but if thats done
1474
it must be revalidated on each new lock.
1475
So for now we just don't memoise it.
1476
# RBC 20060304 review this decision.
1478
bound_loc = self.get_bound_location()
1482
return Branch.open(bound_loc)
1483
except (errors.NotBranchError, errors.ConnectionError), e:
1484
raise errors.BoundBranchConnectionFailure(
1488
def set_bound_location(self, location):
1489
"""Set the target where this branch is bound to.
1491
:param location: URL to the target branch
1494
self.control_files.put_utf8('bound', location+'\n')
1497
self.control_files._transport.delete('bound')
1503
def bind(self, other):
1504
"""Bind this branch to the branch other.
1506
This does not push or pull data between the branches, though it does
1507
check for divergence to raise an error when the branches are not
1508
either the same, or one a prefix of the other. That behaviour may not
1509
be useful, so that check may be removed in future.
1511
:param other: The branch to bind to
1514
# TODO: jam 20051230 Consider checking if the target is bound
1515
# It is debatable whether you should be able to bind to
1516
# a branch which is itself bound.
1517
# Committing is obviously forbidden,
1518
# but binding itself may not be.
1519
# Since we *have* to check at commit time, we don't
1520
# *need* to check here
1522
# we want to raise diverged if:
1523
# last_rev is not in the other_last_rev history, AND
1524
# other_last_rev is not in our history, and do it without pulling
1526
last_rev = self.last_revision()
1527
if last_rev is not None:
1530
other_last_rev = other.last_revision()
1531
if other_last_rev is not None:
1532
# neither branch is new, we have to do some work to
1533
# ascertain diversion.
1534
remote_graph = other.repository.get_revision_graph(
1536
local_graph = self.repository.get_revision_graph(last_rev)
1537
if (last_rev not in remote_graph and
1538
other_last_rev not in local_graph):
1539
raise errors.DivergedBranches(self, other)
1542
self.set_bound_location(other.base)
1546
"""If bound, unbind"""
1547
return self.set_bound_location(None)
1551
"""Synchronise this branch with the master branch if any.
1553
:return: None or the last_revision that was pivoted out during the
1556
master = self.get_master_branch()
1557
if master is not None:
1558
old_tip = self.last_revision()
1559
self.pull(master, overwrite=True)
1560
if old_tip in self.repository.get_ancestry(self.last_revision()):
1566
class BzrBranch6(BzrBranch5):
1569
def last_revision(self):
1570
"""Return last revision id, or None"""
1571
revision_id = self.control_files.get_utf8('last-revision').read()
1572
revision_id = revision_id.rstrip('\n')
1573
if revision_id == _mod_revision.NULL_REVISION:
1578
def set_last_revision(self, revision_id):
1579
if revision_id is None:
1580
revision_id = 'null:'
1581
self.control_files.put_utf8('last-revision', revision_id + '\n')
1584
def revision_history(self):
1585
"""Generate the revision history from last revision
1587
return self._lefthand_history(self.last_revision())
1590
def set_revision_history(self, history):
1591
"""Set the last_revision, not revision history"""
1592
if len(history) == 0:
1593
self.set_last_revision('null:')
1595
assert history == self._lefthand_history(history[-1])
1596
self.set_last_revision(history[-1])
1599
def append_revision(self, *revision_ids):
1600
if len(revision_ids) == 0:
1602
prev_revision = self.last_revision()
1603
for revision in self.repository.get_revisions(revision_ids):
1604
if prev_revision is None:
1605
assert revision.parent_ids == []
1607
assert revision.parent_ids[0] == prev_revision
1608
prev_revision = revision.revision_id
1609
self.set_last_revision(revision_ids[-1])
1612
def _set_parent_location(self, url):
1613
"""Set the parent branch"""
1616
url = urlutils.relative_url(self.base, url)
1617
self.get_config().set_user_option('parent_location', url)
1620
def _get_parent_location(self):
1621
"""Set the parent branch"""
1622
parent = self.get_config().get_user_option('parent_location')
1627
def set_push_location(self, location):
1628
"""See Branch.set_push_location."""
1629
self.get_config().set_user_option('push_location', location)
1631
def set_bound_location(self, location):
1632
"""See Branch.set_push_location."""
1634
if location is None:
1635
if self.get_bound_location() is None:
1639
self.get_config().set_user_option('bound_location', location)
1642
def get_bound_location(self):
1643
"""See Branch.set_push_location."""
1644
location = self.get_config().get_user_option('bound_location')
1650
class BranchTestProviderAdapter(object):
1651
"""A tool to generate a suite testing multiple branch formats at once.
1653
This is done by copying the test once for each transport and injecting
1654
the transport_server, transport_readonly_server, and branch_format
1655
classes into each copy. Each copy is also given a new id() to make it
1659
def __init__(self, transport_server, transport_readonly_server, formats):
1660
self._transport_server = transport_server
1661
self._transport_readonly_server = transport_readonly_server
1662
self._formats = formats
1664
def adapt(self, test):
1665
result = TestSuite()
1666
for branch_format, bzrdir_format in self._formats:
1667
new_test = deepcopy(test)
1668
new_test.transport_server = self._transport_server
1669
new_test.transport_readonly_server = self._transport_readonly_server
1670
new_test.bzrdir_format = bzrdir_format
1671
new_test.branch_format = branch_format
1672
def make_new_test_id():
1673
new_id = "%s(%s)" % (new_test.id(), branch_format.__class__.__name__)
1674
return lambda: new_id
1675
new_test.id = make_new_test_id()
1676
result.addTest(new_test)
1680
class BranchCheckResult(object):
1681
"""Results of checking branch consistency.
1686
def __init__(self, branch):
1687
self.branch = branch
1689
def report_results(self, verbose):
1690
"""Report the check results via trace.note.
1692
:param verbose: Requests more detailed display of what was checked,
1695
note('checked branch %s format %s',
1697
self.branch._format)
1700
######################################################################
1704
@deprecated_function(zero_eight)
1705
def is_control_file(*args, **kwargs):
1706
"""See bzrlib.workingtree.is_control_file."""
1707
from bzrlib import workingtree
1708
return workingtree.is_control_file(*args, **kwargs)