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 copy import deepcopy
19
from cStringIO import StringIO
24
from unittest import TestSuite
25
from warnings import warn
28
import bzrlib.bzrdir as bzrdir
29
from bzrlib.config import TreeConfig
30
from bzrlib.decorators import needs_read_lock, needs_write_lock
31
from bzrlib.delta import compare_trees
32
import bzrlib.errors as errors
33
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
34
NoSuchRevision, HistoryMissing, NotBranchError,
35
DivergedBranches, LockError,
36
UninitializableFormat,
38
UnlistableBranch, NoSuchFile, NotVersionedError,
40
import bzrlib.inventory as inventory
41
from bzrlib.inventory import Inventory
42
from bzrlib.lockable_files import LockableFiles, TransportLock
43
from bzrlib.lockdir import LockDir
44
from bzrlib.osutils import (isdir, quotefn,
45
rename, splitpath, sha_file,
46
file_kind, abspath, normpath, pathjoin,
50
from bzrlib.repository import Repository
51
from bzrlib.revision import (
56
from bzrlib.store import copy_all
57
from bzrlib.symbol_versioning import *
58
from bzrlib.trace import mutter, note
59
import bzrlib.transactions as transactions
60
from bzrlib.transport import Transport, get_transport
61
from bzrlib.tree import EmptyTree, RevisionTree
63
import bzrlib.urlutils as urlutils
67
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
68
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
69
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
72
# TODO: Maybe include checks for common corruption of newlines, etc?
74
# TODO: Some operations like log might retrieve the same revisions
75
# repeatedly to calculate deltas. We could perhaps have a weakref
76
# cache in memory to make this faster. In general anything can be
77
# cached in memory between lock and unlock operations. .. nb thats
78
# what the transaction identity map provides
81
######################################################################
85
"""Branch holding a history of revisions.
88
Base directory/url of the branch.
90
# this is really an instance variable - FIXME move it there
94
def __init__(self, *ignored, **ignored_too):
95
raise NotImplementedError('The Branch class is abstract')
98
"""Break a lock if one is present from another instance.
100
Uses the ui factory to ask for confirmation if the lock may be from
103
This will probe the repository for its lock as well.
105
self.control_files.break_lock()
106
self.repository.break_lock()
107
master = self.get_master_branch()
108
if master is not None:
112
@deprecated_method(zero_eight)
113
def open_downlevel(base):
114
"""Open a branch which may be of an old format."""
115
return Branch.open(base, _unsupported=True)
118
def open(base, _unsupported=False):
119
"""Open the repository rooted at base.
121
For instance, if the repository is at URL/.bzr/repository,
122
Repository.open(URL) -> a Repository instance.
124
control = bzrdir.BzrDir.open(base, _unsupported)
125
return control.open_branch(_unsupported)
128
def open_containing(url):
129
"""Open an existing branch which contains url.
131
This probes for a branch at url, and searches upwards from there.
133
Basically we keep looking up until we find the control directory or
134
run into the root. If there isn't one, raises NotBranchError.
135
If there is one and it is either an unrecognised format or an unsupported
136
format, UnknownFormatError or UnsupportedFormatError are raised.
137
If there is one, it is returned, along with the unused portion of url.
139
control, relpath = bzrdir.BzrDir.open_containing(url)
140
return control.open_branch(), relpath
143
@deprecated_function(zero_eight)
144
def initialize(base):
145
"""Create a new working tree and branch, rooted at 'base' (url)
147
NOTE: This will soon be deprecated in favour of creation
150
return bzrdir.BzrDir.create_standalone_workingtree(base).branch
152
def setup_caching(self, cache_root):
153
"""Subclasses that care about caching should override this, and set
154
up cached stores located under cache_root.
156
# seems to be unused, 2006-01-13 mbp
157
warn('%s is deprecated' % self.setup_caching)
158
self.cache_root = cache_root
161
cfg = self.tree_config()
162
return cfg.get_option(u"nickname", default=self.base.split('/')[-2])
164
def _set_nick(self, nick):
165
cfg = self.tree_config()
166
cfg.set_option(nick, "nickname")
167
assert cfg.get_option("nickname") == nick
169
nick = property(_get_nick, _set_nick)
172
raise NotImplementedError('is_locked is abstract')
174
def lock_write(self):
175
raise NotImplementedError('lock_write is abstract')
178
raise NotImplementedError('lock_read is abstract')
181
raise NotImplementedError('unlock is abstract')
183
def peek_lock_mode(self):
184
"""Return lock mode for the Branch: 'r', 'w' or None"""
185
raise NotImplementedError(self.peek_lock_mode)
187
def get_physical_lock_status(self):
188
raise NotImplementedError('get_physical_lock_status is abstract')
190
def abspath(self, name):
191
"""Return absolute filename for something in the branch
193
XXX: Robert Collins 20051017 what is this used for? why is it a branch
194
method and not a tree method.
196
raise NotImplementedError('abspath is abstract')
198
def bind(self, other):
199
"""Bind the local branch the other branch.
201
:param other: The branch to bind to
204
raise errors.UpgradeRequired(self.base)
207
def fetch(self, from_branch, last_revision=None, pb=None):
208
"""Copy revisions from from_branch into this branch.
210
:param from_branch: Where to copy from.
211
:param last_revision: What revision to stop at (None for at the end
213
:param pb: An optional progress bar to use.
215
Returns the copied revision count and the failed revisions in a tuple:
218
if self.base == from_branch.base:
221
nested_pb = bzrlib.ui.ui_factory.nested_progress_bar()
226
from_branch.lock_read()
228
if last_revision is None:
229
pb.update('get source history')
230
from_history = from_branch.revision_history()
232
last_revision = from_history[-1]
234
# no history in the source branch
235
last_revision = NULL_REVISION
236
return self.repository.fetch(from_branch.repository,
237
revision_id=last_revision,
240
if nested_pb is not None:
244
def get_bound_location(self):
245
"""Return the URL of the branch we are bound to.
247
Older format branches cannot bind, please be sure to use a metadir
252
def get_commit_builder(self, parents, config=None, timestamp=None,
253
timezone=None, committer=None, revprops=None,
255
"""Obtain a CommitBuilder for this branch.
257
:param parents: Revision ids of the parents of the new revision.
258
:param config: Optional configuration to use.
259
:param timestamp: Optional timestamp recorded for commit.
260
:param timezone: Optional timezone for timestamp.
261
:param committer: Optional committer to set for commit.
262
:param revprops: Optional dictionary of revision properties.
263
:param revision_id: Optional revision id.
267
config = bzrlib.config.BranchConfig(self)
269
return self.repository.get_commit_builder(self, parents, config,
270
timestamp, timezone, committer, revprops, revision_id)
272
def get_master_branch(self):
273
"""Return the branch we are bound to.
275
:return: Either a Branch, or None
279
def get_root_id(self):
280
"""Return the id of this branches root"""
281
raise NotImplementedError('get_root_id is abstract')
283
def print_file(self, file, revision_id):
284
"""Print `file` to stdout."""
285
raise NotImplementedError('print_file is abstract')
287
def append_revision(self, *revision_ids):
288
raise NotImplementedError('append_revision is abstract')
290
def set_revision_history(self, rev_history):
291
raise NotImplementedError('set_revision_history is abstract')
293
def revision_history(self):
294
"""Return sequence of revision hashes on to this branch."""
295
raise NotImplementedError('revision_history is abstract')
298
"""Return current revision number for this branch.
300
That is equivalent to the number of revisions committed to
303
return len(self.revision_history())
306
"""Older format branches cannot bind or unbind."""
307
raise errors.UpgradeRequired(self.base)
309
def last_revision(self):
310
"""Return last patch hash, or None if no history."""
311
ph = self.revision_history()
317
def missing_revisions(self, other, stop_revision=None):
318
"""Return a list of new revisions that would perfectly fit.
320
If self and other have not diverged, return a list of the revisions
321
present in other, but missing from self.
323
>>> from bzrlib.workingtree import WorkingTree
324
>>> bzrlib.trace.silent = True
325
>>> d1 = bzrdir.ScratchDir()
326
>>> br1 = d1.open_branch()
327
>>> wt1 = d1.open_workingtree()
328
>>> d2 = bzrdir.ScratchDir()
329
>>> br2 = d2.open_branch()
330
>>> wt2 = d2.open_workingtree()
331
>>> br1.missing_revisions(br2)
333
>>> wt2.commit("lala!", rev_id="REVISION-ID-1")
335
>>> br1.missing_revisions(br2)
337
>>> br2.missing_revisions(br1)
339
>>> wt1.commit("lala!", rev_id="REVISION-ID-1")
341
>>> br1.missing_revisions(br2)
343
>>> wt2.commit("lala!", rev_id="REVISION-ID-2A")
345
>>> br1.missing_revisions(br2)
347
>>> wt1.commit("lala!", rev_id="REVISION-ID-2B")
349
>>> br1.missing_revisions(br2)
350
Traceback (most recent call last):
351
DivergedBranches: These branches have diverged. Try merge.
353
self_history = self.revision_history()
354
self_len = len(self_history)
355
other_history = other.revision_history()
356
other_len = len(other_history)
357
common_index = min(self_len, other_len) -1
358
if common_index >= 0 and \
359
self_history[common_index] != other_history[common_index]:
360
raise DivergedBranches(self, other)
362
if stop_revision is None:
363
stop_revision = other_len
365
assert isinstance(stop_revision, int)
366
if stop_revision > other_len:
367
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
368
return other_history[self_len:stop_revision]
370
def update_revisions(self, other, stop_revision=None):
371
"""Pull in new perfect-fit revisions.
373
:param other: Another Branch to pull from
374
:param stop_revision: Updated until the given revision
377
raise NotImplementedError('update_revisions is abstract')
379
def revision_id_to_revno(self, revision_id):
380
"""Given a revision id, return its revno"""
381
if revision_id is None:
383
history = self.revision_history()
385
return history.index(revision_id) + 1
387
raise bzrlib.errors.NoSuchRevision(self, revision_id)
389
def get_rev_id(self, revno, history=None):
390
"""Find the revision id of the specified revno."""
394
history = self.revision_history()
395
elif revno <= 0 or revno > len(history):
396
raise bzrlib.errors.NoSuchRevision(self, revno)
397
return history[revno - 1]
399
def pull(self, source, overwrite=False, stop_revision=None):
400
raise NotImplementedError('pull is abstract')
402
def basis_tree(self):
403
"""Return `Tree` object for last revision.
405
If there are no revisions yet, return an `EmptyTree`.
407
return self.repository.revision_tree(self.last_revision())
409
def rename_one(self, from_rel, to_rel):
412
This can change the directory or the filename or both.
414
raise NotImplementedError('rename_one is abstract')
416
def move(self, from_paths, to_name):
419
to_name must exist as a versioned directory.
421
If to_name exists and is a directory, the files are moved into
422
it, keeping their old names. If it is a directory,
424
Note that to_name is only the last component of the new name;
425
this doesn't change the directory.
427
This returns a list of (from_path, to_path) pairs for each
430
raise NotImplementedError('move is abstract')
432
def get_parent(self):
433
"""Return the parent location of the branch.
435
This is the default location for push/pull/missing. The usual
436
pattern is that the user can override it by specifying a
439
raise NotImplementedError('get_parent is abstract')
441
def get_push_location(self):
442
"""Return the None or the location to push this branch to."""
443
raise NotImplementedError('get_push_location is abstract')
445
def set_push_location(self, location):
446
"""Set a new push location for this branch."""
447
raise NotImplementedError('set_push_location is abstract')
449
def set_parent(self, url):
450
raise NotImplementedError('set_parent is abstract')
454
"""Synchronise this branch with the master branch if any.
456
:return: None or the last_revision pivoted out during the update.
460
def check_revno(self, revno):
462
Check whether a revno corresponds to any revision.
463
Zero (the NULL revision) is considered valid.
466
self.check_real_revno(revno)
468
def check_real_revno(self, revno):
470
Check whether a revno corresponds to a real revision.
471
Zero (the NULL revision) is considered invalid
473
if revno < 1 or revno > self.revno():
474
raise InvalidRevisionNumber(revno)
477
def clone(self, *args, **kwargs):
478
"""Clone this branch into to_bzrdir preserving all semantic values.
480
revision_id: if not None, the revision history in the new branch will
481
be truncated to end with revision_id.
483
# for API compatibility, until 0.8 releases we provide the old api:
484
# def clone(self, to_location, revision=None, basis_branch=None, to_branch_format=None):
485
# after 0.8 releases, the *args and **kwargs should be changed:
486
# def clone(self, to_bzrdir, revision_id=None):
487
if (kwargs.get('to_location', None) or
488
kwargs.get('revision', None) or
489
kwargs.get('basis_branch', None) or
490
(len(args) and isinstance(args[0], basestring))):
491
# backwards compatibility api:
492
warn("Branch.clone() has been deprecated for BzrDir.clone() from"
493
" bzrlib 0.8.", DeprecationWarning, stacklevel=3)
496
basis_branch = args[2]
498
basis_branch = kwargs.get('basis_branch', None)
500
basis = basis_branch.bzrdir
505
revision_id = args[1]
507
revision_id = kwargs.get('revision', None)
512
# no default to raise if not provided.
513
url = kwargs.get('to_location')
514
return self.bzrdir.clone(url,
515
revision_id=revision_id,
516
basis=basis).open_branch()
518
# generate args by hand
520
revision_id = args[1]
522
revision_id = kwargs.get('revision_id', None)
526
# no default to raise if not provided.
527
to_bzrdir = kwargs.get('to_bzrdir')
528
result = self._format.initialize(to_bzrdir)
529
self.copy_content_into(result, revision_id=revision_id)
533
def sprout(self, to_bzrdir, revision_id=None):
534
"""Create a new line of development from the branch, into to_bzrdir.
536
revision_id: if not None, the revision history in the new branch will
537
be truncated to end with revision_id.
539
result = self._format.initialize(to_bzrdir)
540
self.copy_content_into(result, revision_id=revision_id)
541
result.set_parent(self.bzrdir.root_transport.base)
545
def copy_content_into(self, destination, revision_id=None):
546
"""Copy the content of self into destination.
548
revision_id: if not None, the revision history in the new branch will
549
be truncated to end with revision_id.
551
new_history = self.revision_history()
552
if revision_id is not None:
554
new_history = new_history[:new_history.index(revision_id) + 1]
556
rev = self.repository.get_revision(revision_id)
557
new_history = rev.get_history(self.repository)[1:]
558
destination.set_revision_history(new_history)
559
parent = self.get_parent()
561
destination.set_parent(parent)
565
"""Check consistency of the branch.
567
In particular this checks that revisions given in the revision-history
568
do actually match up in the revision graph, and that they're all
569
present in the repository.
571
:return: A BranchCheckResult.
573
mainline_parent_id = None
574
for revision_id in self.revision_history():
576
revision = self.repository.get_revision(revision_id)
577
except errors.NoSuchRevision, e:
578
raise BzrCheckError("mainline revision {%s} not in repository"
580
# In general the first entry on the revision history has no parents.
581
# But it's not illegal for it to have parents listed; this can happen
582
# in imports from Arch when the parents weren't reachable.
583
if mainline_parent_id is not None:
584
if mainline_parent_id not in revision.parent_ids:
585
raise BzrCheckError("previous revision {%s} not listed among "
587
% (mainline_parent_id, revision_id))
588
mainline_parent_id = revision_id
589
return BranchCheckResult(self)
592
class BranchFormat(object):
593
"""An encapsulation of the initialization and open routines for a format.
595
Formats provide three things:
596
* An initialization routine,
600
Formats are placed in an dict by their format string for reference
601
during branch opening. Its not required that these be instances, they
602
can be classes themselves with class methods - it simply depends on
603
whether state is needed for a given format or not.
605
Once a format is deprecated, just deprecate the initialize and open
606
methods on the format class. Do not deprecate the object, as the
607
object will be created every time regardless.
610
_default_format = None
611
"""The default format used for new branches."""
614
"""The known formats."""
617
def find_format(klass, a_bzrdir):
618
"""Return the format for the branch object in a_bzrdir."""
620
transport = a_bzrdir.get_branch_transport(None)
621
format_string = transport.get("format").read()
622
return klass._formats[format_string]
624
raise NotBranchError(path=transport.base)
626
raise errors.UnknownFormatError(format_string)
629
def get_default_format(klass):
630
"""Return the current default format."""
631
return klass._default_format
633
def get_format_string(self):
634
"""Return the ASCII format string that identifies this format."""
635
raise NotImplementedError(self.get_format_string)
637
def get_format_description(self):
638
"""Return the short format description for this format."""
639
raise NotImplementedError(self.get_format_string)
641
def initialize(self, a_bzrdir):
642
"""Create a branch of this format in a_bzrdir."""
643
raise NotImplementedError(self.initialize)
645
def is_supported(self):
646
"""Is this format supported?
648
Supported formats can be initialized and opened.
649
Unsupported formats may not support initialization or committing or
650
some other features depending on the reason for not being supported.
654
def open(self, a_bzrdir, _found=False):
655
"""Return the branch object for a_bzrdir
657
_found is a private parameter, do not use it. It is used to indicate
658
if format probing has already be done.
660
raise NotImplementedError(self.open)
663
def register_format(klass, format):
664
klass._formats[format.get_format_string()] = format
667
def set_default_format(klass, format):
668
klass._default_format = format
671
def unregister_format(klass, format):
672
assert klass._formats[format.get_format_string()] is format
673
del klass._formats[format.get_format_string()]
676
return self.get_format_string().rstrip()
679
class BzrBranchFormat4(BranchFormat):
680
"""Bzr branch format 4.
683
- a revision-history file.
684
- a branch-lock lock file [ to be shared with the bzrdir ]
687
def get_format_description(self):
688
"""See BranchFormat.get_format_description()."""
689
return "Branch format 4"
691
def initialize(self, a_bzrdir):
692
"""Create a branch of this format in a_bzrdir."""
693
mutter('creating branch in %s', a_bzrdir.transport.base)
694
branch_transport = a_bzrdir.get_branch_transport(self)
695
utf8_files = [('revision-history', ''),
698
control_files = LockableFiles(branch_transport, 'branch-lock',
700
control_files.create_lock()
701
control_files.lock_write()
703
for file, content in utf8_files:
704
control_files.put_utf8(file, content)
706
control_files.unlock()
707
return self.open(a_bzrdir, _found=True)
710
super(BzrBranchFormat4, self).__init__()
711
self._matchingbzrdir = bzrdir.BzrDirFormat6()
713
def open(self, a_bzrdir, _found=False):
714
"""Return the branch object for a_bzrdir
716
_found is a private parameter, do not use it. It is used to indicate
717
if format probing has already be done.
720
# we are being called directly and must probe.
721
raise NotImplementedError
722
return BzrBranch(_format=self,
723
_control_files=a_bzrdir._control_files,
725
_repository=a_bzrdir.open_repository())
728
return "Bazaar-NG branch format 4"
731
class BzrBranchFormat5(BranchFormat):
732
"""Bzr branch format 5.
735
- a revision-history file.
737
- a lock dir guarding the branch itself
738
- all of this stored in a branch/ subdirectory
739
- works with shared repositories.
741
This format is new in bzr 0.8.
744
def get_format_string(self):
745
"""See BranchFormat.get_format_string()."""
746
return "Bazaar-NG branch format 5\n"
748
def get_format_description(self):
749
"""See BranchFormat.get_format_description()."""
750
return "Branch format 5"
752
def initialize(self, a_bzrdir):
753
"""Create a branch of this format in a_bzrdir."""
754
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
755
branch_transport = a_bzrdir.get_branch_transport(self)
756
utf8_files = [('revision-history', ''),
759
control_files = LockableFiles(branch_transport, 'lock', LockDir)
760
control_files.create_lock()
761
control_files.lock_write()
762
control_files.put_utf8('format', self.get_format_string())
764
for file, content in utf8_files:
765
control_files.put_utf8(file, content)
767
control_files.unlock()
768
return self.open(a_bzrdir, _found=True, )
771
super(BzrBranchFormat5, self).__init__()
772
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
774
def open(self, a_bzrdir, _found=False):
775
"""Return the branch object for a_bzrdir
777
_found is a private parameter, do not use it. It is used to indicate
778
if format probing has already be done.
781
format = BranchFormat.find_format(a_bzrdir)
782
assert format.__class__ == self.__class__
783
transport = a_bzrdir.get_branch_transport(None)
784
control_files = LockableFiles(transport, 'lock', LockDir)
785
return BzrBranch5(_format=self,
786
_control_files=control_files,
788
_repository=a_bzrdir.find_repository())
791
return "Bazaar-NG Metadir branch format 5"
794
class BranchReferenceFormat(BranchFormat):
795
"""Bzr branch reference format.
797
Branch references are used in implementing checkouts, they
798
act as an alias to the real branch which is at some other url.
805
def get_format_string(self):
806
"""See BranchFormat.get_format_string()."""
807
return "Bazaar-NG Branch Reference Format 1\n"
809
def get_format_description(self):
810
"""See BranchFormat.get_format_description()."""
811
return "Checkout reference format 1"
813
def initialize(self, a_bzrdir, target_branch=None):
814
"""Create a branch of this format in a_bzrdir."""
815
if target_branch is None:
816
# this format does not implement branch itself, thus the implicit
817
# creation contract must see it as uninitializable
818
raise errors.UninitializableFormat(self)
819
mutter('creating branch reference in %s', a_bzrdir.transport.base)
820
branch_transport = a_bzrdir.get_branch_transport(self)
821
# FIXME rbc 20060209 one j-a-ms encoding branch lands this str() cast is not needed.
822
branch_transport.put('location', StringIO(str(target_branch.bzrdir.root_transport.base)))
823
branch_transport.put('format', StringIO(self.get_format_string()))
824
return self.open(a_bzrdir, _found=True)
827
super(BranchReferenceFormat, self).__init__()
828
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
830
def _make_reference_clone_function(format, a_branch):
831
"""Create a clone() routine for a branch dynamically."""
832
def clone(to_bzrdir, revision_id=None):
833
"""See Branch.clone()."""
834
return format.initialize(to_bzrdir, a_branch)
835
# cannot obey revision_id limits when cloning a reference ...
836
# FIXME RBC 20060210 either nuke revision_id for clone, or
837
# emit some sort of warning/error to the caller ?!
840
def open(self, a_bzrdir, _found=False):
841
"""Return the branch that the branch reference in a_bzrdir points at.
843
_found is a private parameter, do not use it. It is used to indicate
844
if format probing has already be done.
847
format = BranchFormat.find_format(a_bzrdir)
848
assert format.__class__ == self.__class__
849
transport = a_bzrdir.get_branch_transport(None)
850
real_bzrdir = bzrdir.BzrDir.open(transport.get('location').read())
851
result = real_bzrdir.open_branch()
852
# this changes the behaviour of result.clone to create a new reference
853
# rather than a copy of the content of the branch.
854
# I did not use a proxy object because that needs much more extensive
855
# testing, and we are only changing one behaviour at the moment.
856
# If we decide to alter more behaviours - i.e. the implicit nickname
857
# then this should be refactored to introduce a tested proxy branch
858
# and a subclass of that for use in overriding clone() and ....
860
result.clone = self._make_reference_clone_function(result)
864
# formats which have no format string are not discoverable
865
# and not independently creatable, so are not registered.
866
__default_format = BzrBranchFormat5()
867
BranchFormat.register_format(__default_format)
868
BranchFormat.register_format(BranchReferenceFormat())
869
BranchFormat.set_default_format(__default_format)
870
_legacy_formats = [BzrBranchFormat4(),
873
class BzrBranch(Branch):
874
"""A branch stored in the actual filesystem.
876
Note that it's "local" in the context of the filesystem; it doesn't
877
really matter if it's on an nfs/smb/afs/coda/... share, as long as
878
it's writable, and can be accessed via the normal filesystem API.
881
def __init__(self, transport=DEPRECATED_PARAMETER, init=DEPRECATED_PARAMETER,
882
relax_version_check=DEPRECATED_PARAMETER, _format=None,
883
_control_files=None, a_bzrdir=None, _repository=None):
884
"""Create new branch object at a particular location.
886
transport -- A Transport object, defining how to access files.
888
init -- If True, create new control files in a previously
889
unversioned directory. If False, the branch must already
892
relax_version_check -- If true, the usual check for the branch
893
version is not applied. This is intended only for
894
upgrade/recovery type use; it's not guaranteed that
895
all operations will work on old format branches.
898
self.bzrdir = bzrdir.BzrDir.open(transport.base)
900
self.bzrdir = a_bzrdir
901
self._transport = self.bzrdir.transport.clone('..')
902
self._base = self._transport.base
903
self._format = _format
904
if _control_files is None:
905
raise BzrBadParameterMissing('_control_files')
906
self.control_files = _control_files
907
if deprecated_passed(init):
908
warn("BzrBranch.__init__(..., init=XXX): The init parameter is "
909
"deprecated as of bzr 0.8. Please use Branch.create().",
913
# this is slower than before deprecation, oh well never mind.
915
self._initialize(transport.base)
916
self._check_format(_format)
917
if deprecated_passed(relax_version_check):
918
warn("BzrBranch.__init__(..., relax_version_check=XXX_: The "
919
"relax_version_check parameter is deprecated as of bzr 0.8. "
920
"Please use BzrDir.open_downlevel, or a BzrBranchFormat's "
924
if (not relax_version_check
925
and not self._format.is_supported()):
926
raise errors.UnsupportedFormatError(
927
'sorry, branch format %r not supported' % fmt,
928
['use a different bzr version',
929
'or remove the .bzr directory'
930
' and "bzr init" again'])
931
if deprecated_passed(transport):
932
warn("BzrBranch.__init__(transport=XXX...): The transport "
933
"parameter is deprecated as of bzr 0.8. "
934
"Please use Branch.open, or bzrdir.open_branch().",
937
self.repository = _repository
940
return '%s(%r)' % (self.__class__.__name__, self.base)
945
# TODO: It might be best to do this somewhere else,
946
# but it is nice for a Branch object to automatically
947
# cache it's information.
948
# Alternatively, we could have the Transport objects cache requests
949
# See the earlier discussion about how major objects (like Branch)
950
# should never expect their __del__ function to run.
951
# XXX: cache_root seems to be unused, 2006-01-13 mbp
952
if hasattr(self, 'cache_root') and self.cache_root is not None:
954
rmtree(self.cache_root)
957
self.cache_root = None
962
base = property(_get_base, doc="The URL for the root of this branch.")
964
def _finish_transaction(self):
965
"""Exit the current transaction."""
966
return self.control_files._finish_transaction()
968
def get_transaction(self):
969
"""Return the current active transaction.
971
If no transaction is active, this returns a passthrough object
972
for which all data is immediately flushed and no caching happens.
974
# this is an explicit function so that we can do tricky stuff
975
# when the storage in rev_storage is elsewhere.
976
# we probably need to hook the two 'lock a location' and
977
# 'have a transaction' together more delicately, so that
978
# we can have two locks (branch and storage) and one transaction
979
# ... and finishing the transaction unlocks both, but unlocking
980
# does not. - RBC 20051121
981
return self.control_files.get_transaction()
983
def _set_transaction(self, transaction):
984
"""Set a new active transaction."""
985
return self.control_files._set_transaction(transaction)
987
def abspath(self, name):
988
"""See Branch.abspath."""
989
return self.control_files._transport.abspath(name)
991
def _check_format(self, format):
992
"""Identify the branch format if needed.
994
The format is stored as a reference to the format object in
995
self._format for code that needs to check it later.
997
The format parameter is either None or the branch format class
998
used to open this branch.
1000
FIXME: DELETE THIS METHOD when pre 0.8 support is removed.
1003
format = BzrBranchFormat.find_format(self.bzrdir)
1004
self._format = format
1005
mutter("got branch format %s", self._format)
1008
def get_root_id(self):
1009
"""See Branch.get_root_id."""
1010
tree = self.repository.revision_tree(self.last_revision())
1011
return tree.inventory.root.file_id
1013
def is_locked(self):
1014
return self.control_files.is_locked()
1016
def lock_write(self):
1017
# TODO: test for failed two phase locks. This is known broken.
1018
self.control_files.lock_write()
1019
self.repository.lock_write()
1021
def lock_read(self):
1022
# TODO: test for failed two phase locks. This is known broken.
1023
self.control_files.lock_read()
1024
self.repository.lock_read()
1027
# TODO: test for failed two phase locks. This is known broken.
1029
self.repository.unlock()
1031
self.control_files.unlock()
1033
def peek_lock_mode(self):
1034
if self.control_files._lock_count == 0:
1037
return self.control_files._lock_mode
1039
def get_physical_lock_status(self):
1040
return self.control_files.get_physical_lock_status()
1043
def print_file(self, file, revision_id):
1044
"""See Branch.print_file."""
1045
return self.repository.print_file(file, revision_id)
1048
def append_revision(self, *revision_ids):
1049
"""See Branch.append_revision."""
1050
for revision_id in revision_ids:
1051
mutter("add {%s} to revision-history" % revision_id)
1052
rev_history = self.revision_history()
1053
rev_history.extend(revision_ids)
1054
self.set_revision_history(rev_history)
1057
def set_revision_history(self, rev_history):
1058
"""See Branch.set_revision_history."""
1059
self.control_files.put_utf8(
1060
'revision-history', '\n'.join(rev_history))
1061
transaction = self.get_transaction()
1062
history = transaction.map.find_revision_history()
1063
if history is not None:
1064
# update the revision history in the identity map.
1065
history[:] = list(rev_history)
1066
# this call is disabled because revision_history is
1067
# not really an object yet, and the transaction is for objects.
1068
# transaction.register_dirty(history)
1070
transaction.map.add_revision_history(rev_history)
1071
# this call is disabled because revision_history is
1072
# not really an object yet, and the transaction is for objects.
1073
# transaction.register_clean(history)
1075
def get_revision_delta(self, revno):
1076
"""Return the delta for one revision.
1078
The delta is relative to its mainline predecessor, or the
1079
empty tree for revision 1.
1081
assert isinstance(revno, int)
1082
rh = self.revision_history()
1083
if not (1 <= revno <= len(rh)):
1084
raise InvalidRevisionNumber(revno)
1086
# revno is 1-based; list is 0-based
1088
new_tree = self.repository.revision_tree(rh[revno-1])
1090
old_tree = EmptyTree()
1092
old_tree = self.repository.revision_tree(rh[revno-2])
1093
return compare_trees(old_tree, new_tree)
1096
def revision_history(self):
1097
"""See Branch.revision_history."""
1098
transaction = self.get_transaction()
1099
history = transaction.map.find_revision_history()
1100
if history is not None:
1101
mutter("cache hit for revision-history in %s", self)
1102
return list(history)
1103
history = [l.rstrip('\r\n') for l in
1104
self.control_files.get_utf8('revision-history').readlines()]
1105
transaction.map.add_revision_history(history)
1106
# this call is disabled because revision_history is
1107
# not really an object yet, and the transaction is for objects.
1108
# transaction.register_clean(history, precious=True)
1109
return list(history)
1112
def update_revisions(self, other, stop_revision=None):
1113
"""See Branch.update_revisions."""
1116
if stop_revision is None:
1117
stop_revision = other.last_revision()
1118
if stop_revision is None:
1119
# if there are no commits, we're done.
1121
# whats the current last revision, before we fetch [and change it
1123
last_rev = self.last_revision()
1124
# we fetch here regardless of whether we need to so that we pickup
1126
self.fetch(other, stop_revision)
1127
my_ancestry = self.repository.get_ancestry(last_rev)
1128
if stop_revision in my_ancestry:
1129
# last_revision is a descendant of stop_revision
1131
# stop_revision must be a descendant of last_revision
1132
stop_graph = self.repository.get_revision_graph(stop_revision)
1133
if last_rev is not None and last_rev not in stop_graph:
1134
# our previous tip is not merged into stop_revision
1135
raise errors.DivergedBranches(self, other)
1136
# make a new revision history from the graph
1137
current_rev_id = stop_revision
1139
while current_rev_id not in (None, NULL_REVISION):
1140
new_history.append(current_rev_id)
1141
current_rev_id_parents = stop_graph[current_rev_id]
1143
current_rev_id = current_rev_id_parents[0]
1145
current_rev_id = None
1146
new_history.reverse()
1147
self.set_revision_history(new_history)
1151
def basis_tree(self):
1152
"""See Branch.basis_tree."""
1153
return self.repository.revision_tree(self.last_revision())
1155
@deprecated_method(zero_eight)
1156
def working_tree(self):
1157
"""Create a Working tree object for this branch."""
1158
from bzrlib.workingtree import WorkingTree
1159
from bzrlib.transport.local import LocalTransport
1160
if (self.base.find('://') != -1 or
1161
not isinstance(self._transport, LocalTransport)):
1162
raise NoWorkingTree(self.base)
1163
return self.bzrdir.open_workingtree()
1166
def pull(self, source, overwrite=False, stop_revision=None):
1167
"""See Branch.pull."""
1170
old_count = len(self.revision_history())
1172
self.update_revisions(source,stop_revision)
1173
except DivergedBranches:
1177
self.set_revision_history(source.revision_history())
1178
new_count = len(self.revision_history())
1179
return new_count - old_count
1183
def get_parent(self):
1184
"""See Branch.get_parent."""
1186
_locs = ['parent', 'pull', 'x-pull']
1187
assert self.base[-1] == '/'
1190
parent = self.control_files.get(l).read().strip('\n')
1193
# This is an old-format absolute path to a local branch
1194
# turn it into a url
1195
if parent.startswith('/'):
1196
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1197
return urlutils.join(self.base[:-1], parent)
1200
def get_push_location(self):
1201
"""See Branch.get_push_location."""
1202
config = bzrlib.config.BranchConfig(self)
1203
push_loc = config.get_user_option('push_location')
1206
def set_push_location(self, location):
1207
"""See Branch.set_push_location."""
1208
config = bzrlib.config.LocationConfig(self.base)
1209
config.set_user_option('push_location', location)
1212
def set_parent(self, url):
1213
"""See Branch.set_parent."""
1214
# TODO: Maybe delete old location files?
1215
# URLs should never be unicode, even on the local fs,
1216
# FIXUP this and get_parent in a future branch format bump:
1217
# read and rewrite the file, and have the new format code read
1218
# using .get not .get_utf8. RBC 20060125
1220
self.control_files._transport.delete('parent')
1222
if isinstance(url, unicode):
1224
url = url.encode('ascii')
1225
except UnicodeEncodeError:
1226
raise bzrlib.errors.InvalidURL(url,
1227
"Urls must be 7-bit ascii, "
1228
"use bzrlib.urlutils.escape")
1230
url = urlutils.relative_url(self.base, url)
1231
self.control_files.put('parent', url + '\n')
1233
def tree_config(self):
1234
return TreeConfig(self)
1237
class BzrBranch5(BzrBranch):
1238
"""A format 5 branch. This supports new features over plan branches.
1240
It has support for a master_branch which is the data for bound branches.
1248
super(BzrBranch5, self).__init__(_format=_format,
1249
_control_files=_control_files,
1251
_repository=_repository)
1254
def pull(self, source, overwrite=False, stop_revision=None):
1255
"""Updates branch.pull to be bound branch aware."""
1256
bound_location = self.get_bound_location()
1257
if source.base != bound_location:
1258
# not pulling from master, so we need to update master.
1259
master_branch = self.get_master_branch()
1261
master_branch.pull(source)
1262
source = master_branch
1263
return super(BzrBranch5, self).pull(source, overwrite, stop_revision)
1265
def get_bound_location(self):
1267
return self.control_files.get_utf8('bound').read()[:-1]
1268
except errors.NoSuchFile:
1272
def get_master_branch(self):
1273
"""Return the branch we are bound to.
1275
:return: Either a Branch, or None
1277
This could memoise the branch, but if thats done
1278
it must be revalidated on each new lock.
1279
So for now we just don't memoise it.
1280
# RBC 20060304 review this decision.
1282
bound_loc = self.get_bound_location()
1286
return Branch.open(bound_loc)
1287
except (errors.NotBranchError, errors.ConnectionError), e:
1288
raise errors.BoundBranchConnectionFailure(
1292
def set_bound_location(self, location):
1293
"""Set the target where this branch is bound to.
1295
:param location: URL to the target branch
1298
self.control_files.put_utf8('bound', location+'\n')
1301
self.control_files._transport.delete('bound')
1307
def bind(self, other):
1308
"""Bind the local branch the other branch.
1310
:param other: The branch to bind to
1313
# TODO: jam 20051230 Consider checking if the target is bound
1314
# It is debatable whether you should be able to bind to
1315
# a branch which is itself bound.
1316
# Committing is obviously forbidden,
1317
# but binding itself may not be.
1318
# Since we *have* to check at commit time, we don't
1319
# *need* to check here
1322
# we are now equal to or a suffix of other.
1324
# Since we have 'pulled' from the remote location,
1325
# now we should try to pull in the opposite direction
1326
# in case the local tree has more revisions than the
1328
# There may be a different check you could do here
1329
# rather than actually trying to install revisions remotely.
1330
# TODO: capture an exception which indicates the remote branch
1332
# If it is up-to-date, this probably should not be a failure
1334
# lock other for write so the revision-history syncing cannot race
1338
# if this does not error, other now has the same last rev we do
1339
# it can only error if the pull from other was concurrent with
1340
# a commit to other from someone else.
1342
# until we ditch revision-history, we need to sync them up:
1343
self.set_revision_history(other.revision_history())
1344
# now other and self are up to date with each other and have the
1345
# same revision-history.
1349
self.set_bound_location(other.base)
1353
"""If bound, unbind"""
1354
return self.set_bound_location(None)
1358
"""Synchronise this branch with the master branch if any.
1360
:return: None or the last_revision that was pivoted out during the
1363
master = self.get_master_branch()
1364
if master is not None:
1365
old_tip = self.last_revision()
1366
self.pull(master, overwrite=True)
1367
if old_tip in self.repository.get_ancestry(self.last_revision()):
1373
class BranchTestProviderAdapter(object):
1374
"""A tool to generate a suite testing multiple branch formats at once.
1376
This is done by copying the test once for each transport and injecting
1377
the transport_server, transport_readonly_server, and branch_format
1378
classes into each copy. Each copy is also given a new id() to make it
1382
def __init__(self, transport_server, transport_readonly_server, formats):
1383
self._transport_server = transport_server
1384
self._transport_readonly_server = transport_readonly_server
1385
self._formats = formats
1387
def adapt(self, test):
1388
result = TestSuite()
1389
for branch_format, bzrdir_format in self._formats:
1390
new_test = deepcopy(test)
1391
new_test.transport_server = self._transport_server
1392
new_test.transport_readonly_server = self._transport_readonly_server
1393
new_test.bzrdir_format = bzrdir_format
1394
new_test.branch_format = branch_format
1395
def make_new_test_id():
1396
new_id = "%s(%s)" % (new_test.id(), branch_format.__class__.__name__)
1397
return lambda: new_id
1398
new_test.id = make_new_test_id()
1399
result.addTest(new_test)
1403
class BranchCheckResult(object):
1404
"""Results of checking branch consistency.
1409
def __init__(self, branch):
1410
self.branch = branch
1412
def report_results(self, verbose):
1413
"""Report the check results via trace.note.
1415
:param verbose: Requests more detailed display of what was checked,
1418
note('checked branch %s format %s',
1420
self.branch._format)
1423
######################################################################
1427
@deprecated_function(zero_eight)
1428
def ScratchBranch(*args, **kwargs):
1429
"""See bzrlib.bzrdir.ScratchDir."""
1430
d = ScratchDir(*args, **kwargs)
1431
return d.open_branch()
1434
@deprecated_function(zero_eight)
1435
def is_control_file(*args, **kwargs):
1436
"""See bzrlib.workingtree.is_control_file."""
1437
return bzrlib.workingtree.is_control_file(*args, **kwargs)