1
# Copyright (C) 2005, 2006, 2007 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 warnings import warn
28
config as _mod_config,
33
revision as _mod_revision,
40
from bzrlib.config import BranchConfig, TreeConfig
41
from bzrlib.lockable_files import LockableFiles, TransportLock
42
from bzrlib.tag import (
48
from bzrlib.decorators import needs_read_lock, needs_write_lock
49
from bzrlib.errors import (BzrError, BzrCheckError, DivergedBranches,
50
HistoryMissing, InvalidRevisionId,
51
InvalidRevisionNumber, LockError, NoSuchFile,
52
NoSuchRevision, NoWorkingTree, NotVersionedError,
53
NotBranchError, UninitializableFormat,
54
UnlistableStore, UnlistableBranch,
56
from bzrlib.hooks import Hooks
57
from bzrlib.symbol_versioning import (deprecated_function,
61
zero_eight, zero_nine, zero_sixteen,
64
from bzrlib.trace import mutter, note
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 Branch Format 6 (bzr 0.15)\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
hooks: An instance of BranchHooks.
92
# this is really an instance variable - FIXME move it there
96
# override this to set the strategy for storing tags
98
return DisabledTags(self)
100
def __init__(self, *ignored, **ignored_too):
101
self.tags = self._make_tags()
102
self._revision_history_cache = None
103
self._revision_id_to_revno_cache = None
105
def break_lock(self):
106
"""Break a lock if one is present from another instance.
108
Uses the ui factory to ask for confirmation if the lock may be from
111
This will probe the repository for its lock as well.
113
self.control_files.break_lock()
114
self.repository.break_lock()
115
master = self.get_master_branch()
116
if master is not None:
120
@deprecated_method(zero_eight)
121
def open_downlevel(base):
122
"""Open a branch which may be of an old format."""
123
return Branch.open(base, _unsupported=True)
126
def open(base, _unsupported=False):
127
"""Open the branch rooted at base.
129
For instance, if the branch is at URL/.bzr/branch,
130
Branch.open(URL) -> a Branch instance.
132
control = bzrdir.BzrDir.open(base, _unsupported)
133
return control.open_branch(_unsupported)
136
def open_from_transport(transport, _unsupported=False):
137
"""Open the branch rooted at transport"""
138
control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
139
return control.open_branch(_unsupported)
142
def open_containing(url, possible_transports=None):
143
"""Open an existing branch which contains url.
145
This probes for a branch at url, and searches upwards from there.
147
Basically we keep looking up until we find the control directory or
148
run into the root. If there isn't one, raises NotBranchError.
149
If there is one and it is either an unrecognised format or an unsupported
150
format, UnknownFormatError or UnsupportedFormatError are raised.
151
If there is one, it is returned, along with the unused portion of url.
153
control, relpath = bzrdir.BzrDir.open_containing(url,
155
return control.open_branch(), relpath
158
@deprecated_function(zero_eight)
159
def initialize(base):
160
"""Create a new working tree and branch, rooted at 'base' (url)
162
NOTE: This will soon be deprecated in favour of creation
165
return bzrdir.BzrDir.create_standalone_workingtree(base).branch
167
@deprecated_function(zero_eight)
168
def setup_caching(self, cache_root):
169
"""Subclasses that care about caching should override this, and set
170
up cached stores located under cache_root.
172
NOTE: This is unused.
176
def get_config(self):
177
return BranchConfig(self)
180
return self.get_config().get_nickname()
182
def _set_nick(self, nick):
183
self.get_config().set_user_option('nickname', nick, warn_masked=True)
185
nick = property(_get_nick, _set_nick)
188
raise NotImplementedError(self.is_locked)
190
def lock_write(self):
191
raise NotImplementedError(self.lock_write)
194
raise NotImplementedError(self.lock_read)
197
raise NotImplementedError(self.unlock)
199
def peek_lock_mode(self):
200
"""Return lock mode for the Branch: 'r', 'w' or None"""
201
raise NotImplementedError(self.peek_lock_mode)
203
def get_physical_lock_status(self):
204
raise NotImplementedError(self.get_physical_lock_status)
207
def get_revision_id_to_revno_map(self):
208
"""Return the revision_id => dotted revno map.
210
This will be regenerated on demand, but will be cached.
212
:return: A dictionary mapping revision_id => dotted revno.
213
This dictionary should not be modified by the caller.
215
if self._revision_id_to_revno_cache is not None:
216
mapping = self._revision_id_to_revno_cache
218
mapping = self._gen_revno_map()
219
self._cache_revision_id_to_revno(mapping)
220
# TODO: jam 20070417 Since this is being cached, should we be returning
222
# I would rather not, and instead just declare that users should not
223
# modify the return value.
226
def _gen_revno_map(self):
227
"""Create a new mapping from revision ids to dotted revnos.
229
Dotted revnos are generated based on the current tip in the revision
231
This is the worker function for get_revision_id_to_revno_map, which
232
just caches the return value.
234
:return: A dictionary mapping revision_id => dotted revno.
236
last_revision = self.last_revision()
237
revision_graph = self.repository.get_revision_graph(last_revision)
238
merge_sorted_revisions = tsort.merge_sort(
243
revision_id_to_revno = dict((rev_id, revno)
244
for seq_num, rev_id, depth, revno, end_of_merge
245
in merge_sorted_revisions)
246
return revision_id_to_revno
248
def leave_lock_in_place(self):
249
"""Tell this branch object not to release the physical lock when this
252
If lock_write doesn't return a token, then this method is not supported.
254
self.control_files.leave_in_place()
256
def dont_leave_lock_in_place(self):
257
"""Tell this branch object to release the physical lock when this
258
object is unlocked, even if it didn't originally acquire it.
260
If lock_write doesn't return a token, then this method is not supported.
262
self.control_files.dont_leave_in_place()
264
def abspath(self, name):
265
"""Return absolute filename for something in the branch
267
XXX: Robert Collins 20051017 what is this used for? why is it a branch
268
method and not a tree method.
270
raise NotImplementedError(self.abspath)
272
def bind(self, other):
273
"""Bind the local branch the other branch.
275
:param other: The branch to bind to
278
raise errors.UpgradeRequired(self.base)
281
def fetch(self, from_branch, last_revision=None, pb=None):
282
"""Copy revisions from from_branch into this branch.
284
:param from_branch: Where to copy from.
285
:param last_revision: What revision to stop at (None for at the end
287
:param pb: An optional progress bar to use.
289
Returns the copied revision count and the failed revisions in a tuple:
292
if self.base == from_branch.base:
295
nested_pb = ui.ui_factory.nested_progress_bar()
300
from_branch.lock_read()
302
if last_revision is None:
303
pb.update('get source history')
304
last_revision = from_branch.last_revision()
305
if last_revision is None:
306
last_revision = _mod_revision.NULL_REVISION
307
return self.repository.fetch(from_branch.repository,
308
revision_id=last_revision,
311
if nested_pb is not None:
315
def get_bound_location(self):
316
"""Return the URL of the branch we are bound to.
318
Older format branches cannot bind, please be sure to use a metadir
323
def get_old_bound_location(self):
324
"""Return the URL of the branch we used to be bound to
326
raise errors.UpgradeRequired(self.base)
328
def get_commit_builder(self, parents, config=None, timestamp=None,
329
timezone=None, committer=None, revprops=None,
331
"""Obtain a CommitBuilder for this branch.
333
:param parents: Revision ids of the parents of the new revision.
334
:param config: Optional configuration to use.
335
:param timestamp: Optional timestamp recorded for commit.
336
:param timezone: Optional timezone for timestamp.
337
:param committer: Optional committer to set for commit.
338
:param revprops: Optional dictionary of revision properties.
339
:param revision_id: Optional revision id.
343
config = self.get_config()
345
return self.repository.get_commit_builder(self, parents, config,
346
timestamp, timezone, committer, revprops, revision_id)
348
def get_master_branch(self):
349
"""Return the branch we are bound to.
351
:return: Either a Branch, or None
355
def get_revision_delta(self, revno):
356
"""Return the delta for one revision.
358
The delta is relative to its mainline predecessor, or the
359
empty tree for revision 1.
361
assert isinstance(revno, int)
362
rh = self.revision_history()
363
if not (1 <= revno <= len(rh)):
364
raise InvalidRevisionNumber(revno)
365
return self.repository.get_revision_delta(rh[revno-1])
367
@deprecated_method(zero_sixteen)
368
def get_root_id(self):
369
"""Return the id of this branches root
371
Deprecated: branches don't have root ids-- trees do.
372
Use basis_tree().get_root_id() instead.
374
raise NotImplementedError(self.get_root_id)
376
def print_file(self, file, revision_id):
377
"""Print `file` to stdout."""
378
raise NotImplementedError(self.print_file)
380
@deprecated_method(zero_ninetyone)
381
def append_revision(self, *revision_ids):
382
"""Append the specified revisions to the branch's revision history.
384
Rather than calling this, please use set_last_revision_info(), which
385
takes just the new tip revision.
387
raise NotImplementedError(self.append_revision)
389
def set_revision_history(self, rev_history):
390
raise NotImplementedError(self.set_revision_history)
392
def _cache_revision_history(self, rev_history):
393
"""Set the cached revision history to rev_history.
395
The revision_history method will use this cache to avoid regenerating
396
the revision history.
398
This API is semi-public; it only for use by subclasses, all other code
399
should consider it to be private.
401
self._revision_history_cache = rev_history
403
def _cache_revision_id_to_revno(self, revision_id_to_revno):
404
"""Set the cached revision_id => revno map to revision_id_to_revno.
406
This API is semi-public; it only for use by subclasses, all other code
407
should consider it to be private.
409
self._revision_id_to_revno_cache = revision_id_to_revno
411
def _clear_cached_state(self):
412
"""Clear any cached data on this branch, e.g. cached revision history.
414
This means the next call to revision_history will need to call
415
_gen_revision_history.
417
This API is semi-public; it only for use by subclasses, all other code
418
should consider it to be private.
420
self._revision_history_cache = None
421
self._revision_id_to_revno_cache = None
423
def _gen_revision_history(self):
424
"""Return sequence of revision hashes on to this branch.
426
Unlike revision_history, this method always regenerates or rereads the
427
revision history, i.e. it does not cache the result, so repeated calls
430
Concrete subclasses should override this instead of revision_history so
431
that subclasses do not need to deal with caching logic.
433
This API is semi-public; it only for use by subclasses, all other code
434
should consider it to be private.
436
raise NotImplementedError(self._gen_revision_history)
439
def revision_history(self):
440
"""Return sequence of revision hashes on to this branch.
442
This method will cache the revision history for as long as it is safe to
445
if self._revision_history_cache is not None:
446
history = self._revision_history_cache
448
history = self._gen_revision_history()
449
self._cache_revision_history(history)
453
"""Return current revision number for this branch.
455
That is equivalent to the number of revisions committed to
458
return len(self.revision_history())
461
"""Older format branches cannot bind or unbind."""
462
raise errors.UpgradeRequired(self.base)
464
def set_append_revisions_only(self, enabled):
465
"""Older format branches are never restricted to append-only"""
466
raise errors.UpgradeRequired(self.base)
468
def last_revision(self):
469
"""Return last revision id, or None"""
470
ph = self.revision_history()
476
def last_revision_info(self):
477
"""Return information about the last revision.
479
:return: A tuple (revno, last_revision_id).
481
rh = self.revision_history()
484
return (revno, rh[-1])
486
return (0, _mod_revision.NULL_REVISION)
488
def missing_revisions(self, other, stop_revision=None):
489
"""Return a list of new revisions that would perfectly fit.
491
If self and other have not diverged, return a list of the revisions
492
present in other, but missing from self.
494
self_history = self.revision_history()
495
self_len = len(self_history)
496
other_history = other.revision_history()
497
other_len = len(other_history)
498
common_index = min(self_len, other_len) -1
499
if common_index >= 0 and \
500
self_history[common_index] != other_history[common_index]:
501
raise DivergedBranches(self, other)
503
if stop_revision is None:
504
stop_revision = other_len
506
assert isinstance(stop_revision, int)
507
if stop_revision > other_len:
508
raise errors.NoSuchRevision(self, stop_revision)
509
return other_history[self_len:stop_revision]
511
def update_revisions(self, other, stop_revision=None):
512
"""Pull in new perfect-fit revisions.
514
:param other: Another Branch to pull from
515
:param stop_revision: Updated until the given revision
518
raise NotImplementedError(self.update_revisions)
520
def revision_id_to_revno(self, revision_id):
521
"""Given a revision id, return its revno"""
522
if _mod_revision.is_null(revision_id):
524
revision_id = osutils.safe_revision_id(revision_id)
525
history = self.revision_history()
527
return history.index(revision_id) + 1
529
raise errors.NoSuchRevision(self, revision_id)
531
def get_rev_id(self, revno, history=None):
532
"""Find the revision id of the specified revno."""
536
history = self.revision_history()
537
if revno <= 0 or revno > len(history):
538
raise errors.NoSuchRevision(self, revno)
539
return history[revno - 1]
541
def pull(self, source, overwrite=False, stop_revision=None):
542
"""Mirror source into this branch.
544
This branch is considered to be 'local', having low latency.
546
:returns: PullResult instance
548
raise NotImplementedError(self.pull)
550
def push(self, target, overwrite=False, stop_revision=None):
551
"""Mirror this branch into target.
553
This branch is considered to be 'local', having low latency.
555
raise NotImplementedError(self.push)
557
def basis_tree(self):
558
"""Return `Tree` object for last revision."""
559
return self.repository.revision_tree(self.last_revision())
561
def rename_one(self, from_rel, to_rel):
564
This can change the directory or the filename or both.
566
raise NotImplementedError(self.rename_one)
568
def move(self, from_paths, to_name):
571
to_name must exist as a versioned directory.
573
If to_name exists and is a directory, the files are moved into
574
it, keeping their old names. If it is a directory,
576
Note that to_name is only the last component of the new name;
577
this doesn't change the directory.
579
This returns a list of (from_path, to_path) pairs for each
582
raise NotImplementedError(self.move)
584
def get_parent(self):
585
"""Return the parent location of the branch.
587
This is the default location for push/pull/missing. The usual
588
pattern is that the user can override it by specifying a
591
raise NotImplementedError(self.get_parent)
593
def _set_config_location(self, name, url, config=None,
594
make_relative=False):
596
config = self.get_config()
600
url = urlutils.relative_url(self.base, url)
601
config.set_user_option(name, url, warn_masked=True)
603
def _get_config_location(self, name, config=None):
605
config = self.get_config()
606
location = config.get_user_option(name)
611
def get_submit_branch(self):
612
"""Return the submit location of the branch.
614
This is the default location for bundle. The usual
615
pattern is that the user can override it by specifying a
618
return self.get_config().get_user_option('submit_branch')
620
def set_submit_branch(self, location):
621
"""Return the submit location of the branch.
623
This is the default location for bundle. The usual
624
pattern is that the user can override it by specifying a
627
self.get_config().set_user_option('submit_branch', location,
630
def get_public_branch(self):
631
"""Return the public location of the branch.
633
This is is used by merge directives.
635
return self._get_config_location('public_branch')
637
def set_public_branch(self, location):
638
"""Return the submit location of the branch.
640
This is the default location for bundle. The usual
641
pattern is that the user can override it by specifying a
644
self._set_config_location('public_branch', location)
646
def get_push_location(self):
647
"""Return the None or the location to push this branch to."""
648
push_loc = self.get_config().get_user_option('push_location')
651
def set_push_location(self, location):
652
"""Set a new push location for this branch."""
653
raise NotImplementedError(self.set_push_location)
655
def set_parent(self, url):
656
raise NotImplementedError(self.set_parent)
660
"""Synchronise this branch with the master branch if any.
662
:return: None or the last_revision pivoted out during the update.
666
def check_revno(self, revno):
668
Check whether a revno corresponds to any revision.
669
Zero (the NULL revision) is considered valid.
672
self.check_real_revno(revno)
674
def check_real_revno(self, revno):
676
Check whether a revno corresponds to a real revision.
677
Zero (the NULL revision) is considered invalid
679
if revno < 1 or revno > self.revno():
680
raise InvalidRevisionNumber(revno)
683
def clone(self, to_bzrdir, revision_id=None):
684
"""Clone this branch into to_bzrdir preserving all semantic values.
686
revision_id: if not None, the revision history in the new branch will
687
be truncated to end with revision_id.
689
result = self._format.initialize(to_bzrdir)
690
self.copy_content_into(result, revision_id=revision_id)
694
def sprout(self, to_bzrdir, revision_id=None):
695
"""Create a new line of development from the branch, into to_bzrdir.
697
revision_id: if not None, the revision history in the new branch will
698
be truncated to end with revision_id.
700
result = self._format.initialize(to_bzrdir)
701
self.copy_content_into(result, revision_id=revision_id)
702
result.set_parent(self.bzrdir.root_transport.base)
705
def _synchronize_history(self, destination, revision_id):
706
"""Synchronize last revision and revision history between branches.
708
This version is most efficient when the destination is also a
709
BzrBranch5, but works for BzrBranch6 as long as the revision
710
history is the true lefthand parent history, and all of the revisions
711
are in the destination's repository. If not, set_revision_history
714
:param destination: The branch to copy the history into
715
:param revision_id: The revision-id to truncate history at. May
716
be None to copy complete history.
718
if revision_id == _mod_revision.NULL_REVISION:
720
new_history = self.revision_history()
721
if revision_id is not None and new_history != []:
722
revision_id = osutils.safe_revision_id(revision_id)
724
new_history = new_history[:new_history.index(revision_id) + 1]
726
rev = self.repository.get_revision(revision_id)
727
new_history = rev.get_history(self.repository)[1:]
728
destination.set_revision_history(new_history)
731
def copy_content_into(self, destination, revision_id=None):
732
"""Copy the content of self into destination.
734
revision_id: if not None, the revision history in the new branch will
735
be truncated to end with revision_id.
737
self._synchronize_history(destination, revision_id)
739
parent = self.get_parent()
740
except errors.InaccessibleParent, e:
741
mutter('parent was not accessible to copy: %s', e)
744
destination.set_parent(parent)
745
self.tags.merge_to(destination.tags)
749
"""Check consistency of the branch.
751
In particular this checks that revisions given in the revision-history
752
do actually match up in the revision graph, and that they're all
753
present in the repository.
755
Callers will typically also want to check the repository.
757
:return: A BranchCheckResult.
759
mainline_parent_id = None
760
for revision_id in self.revision_history():
762
revision = self.repository.get_revision(revision_id)
763
except errors.NoSuchRevision, e:
764
raise errors.BzrCheckError("mainline revision {%s} not in repository"
766
# In general the first entry on the revision history has no parents.
767
# But it's not illegal for it to have parents listed; this can happen
768
# in imports from Arch when the parents weren't reachable.
769
if mainline_parent_id is not None:
770
if mainline_parent_id not in revision.parent_ids:
771
raise errors.BzrCheckError("previous revision {%s} not listed among "
773
% (mainline_parent_id, revision_id))
774
mainline_parent_id = revision_id
775
return BranchCheckResult(self)
777
def _get_checkout_format(self):
778
"""Return the most suitable metadir for a checkout of this branch.
779
Weaves are used if this branch's repository uses weaves.
781
if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
782
from bzrlib.repofmt import weaverepo
783
format = bzrdir.BzrDirMetaFormat1()
784
format.repository_format = weaverepo.RepositoryFormat7()
786
format = self.repository.bzrdir.checkout_metadir()
787
format.set_branch_format(self._format)
790
def create_checkout(self, to_location, revision_id=None,
792
"""Create a checkout of a branch.
794
:param to_location: The url to produce the checkout at
795
:param revision_id: The revision to check out
796
:param lightweight: If True, produce a lightweight checkout, otherwise,
797
produce a bound branch (heavyweight checkout)
798
:return: The tree of the created checkout
800
t = transport.get_transport(to_location)
803
format = self._get_checkout_format()
804
checkout = format.initialize_on_transport(t)
805
BranchReferenceFormat().initialize(checkout, self)
807
format = self._get_checkout_format()
808
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
809
to_location, force_new_tree=False, format=format)
810
checkout = checkout_branch.bzrdir
811
checkout_branch.bind(self)
812
# pull up to the specified revision_id to set the initial
813
# branch tip correctly, and seed it with history.
814
checkout_branch.pull(self, stop_revision=revision_id)
815
tree = checkout.create_workingtree(revision_id)
816
basis_tree = tree.basis_tree()
817
basis_tree.lock_read()
819
for path, file_id in basis_tree.iter_references():
820
reference_parent = self.reference_parent(file_id, path)
821
reference_parent.create_checkout(tree.abspath(path),
822
basis_tree.get_reference_revision(file_id, path),
828
def reference_parent(self, file_id, path):
829
"""Return the parent branch for a tree-reference file_id
830
:param file_id: The file_id of the tree reference
831
:param path: The path of the file_id in the tree
832
:return: A branch associated with the file_id
834
# FIXME should provide multiple branches, based on config
835
return Branch.open(self.bzrdir.root_transport.clone(path).base)
837
def supports_tags(self):
838
return self._format.supports_tags()
841
class BranchFormat(object):
842
"""An encapsulation of the initialization and open routines for a format.
844
Formats provide three things:
845
* An initialization routine,
849
Formats are placed in an dict by their format string for reference
850
during branch opening. Its not required that these be instances, they
851
can be classes themselves with class methods - it simply depends on
852
whether state is needed for a given format or not.
854
Once a format is deprecated, just deprecate the initialize and open
855
methods on the format class. Do not deprecate the object, as the
856
object will be created every time regardless.
859
_default_format = None
860
"""The default format used for new branches."""
863
"""The known formats."""
865
def __eq__(self, other):
866
return self.__class__ is other.__class__
868
def __ne__(self, other):
869
return not (self == other)
872
def find_format(klass, a_bzrdir):
873
"""Return the format for the branch object in a_bzrdir."""
875
transport = a_bzrdir.get_branch_transport(None)
876
format_string = transport.get("format").read()
877
return klass._formats[format_string]
879
raise NotBranchError(path=transport.base)
881
raise errors.UnknownFormatError(format=format_string)
884
def get_default_format(klass):
885
"""Return the current default format."""
886
return klass._default_format
888
def get_reference(self, a_bzrdir):
889
"""Get the target reference of the branch in a_bzrdir.
891
format probing must have been completed before calling
892
this method - it is assumed that the format of the branch
893
in a_bzrdir is correct.
895
:param a_bzrdir: The bzrdir to get the branch data from.
896
:return: None if the branch is not a reference branch.
900
def get_format_string(self):
901
"""Return the ASCII format string that identifies this format."""
902
raise NotImplementedError(self.get_format_string)
904
def get_format_description(self):
905
"""Return the short format description for this format."""
906
raise NotImplementedError(self.get_format_description)
908
def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
910
"""Initialize a branch in a bzrdir, with specified files
912
:param a_bzrdir: The bzrdir to initialize the branch in
913
:param utf8_files: The files to create as a list of
914
(filename, content) tuples
915
:param set_format: If True, set the format with
916
self.get_format_string. (BzrBranch4 has its format set
918
:return: a branch in this format
920
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
921
branch_transport = a_bzrdir.get_branch_transport(self)
923
'metadir': ('lock', lockdir.LockDir),
924
'branch4': ('branch-lock', lockable_files.TransportLock),
926
lock_name, lock_class = lock_map[lock_type]
927
control_files = lockable_files.LockableFiles(branch_transport,
928
lock_name, lock_class)
929
control_files.create_lock()
930
control_files.lock_write()
932
control_files.put_utf8('format', self.get_format_string())
934
for file, content in utf8_files:
935
control_files.put_utf8(file, content)
937
control_files.unlock()
938
return self.open(a_bzrdir, _found=True)
940
def initialize(self, a_bzrdir):
941
"""Create a branch of this format in a_bzrdir."""
942
raise NotImplementedError(self.initialize)
944
def is_supported(self):
945
"""Is this format supported?
947
Supported formats can be initialized and opened.
948
Unsupported formats may not support initialization or committing or
949
some other features depending on the reason for not being supported.
953
def open(self, a_bzrdir, _found=False):
954
"""Return the branch object for a_bzrdir
956
_found is a private parameter, do not use it. It is used to indicate
957
if format probing has already be done.
959
raise NotImplementedError(self.open)
962
def register_format(klass, format):
963
klass._formats[format.get_format_string()] = format
966
def set_default_format(klass, format):
967
klass._default_format = format
970
def unregister_format(klass, format):
971
assert klass._formats[format.get_format_string()] is format
972
del klass._formats[format.get_format_string()]
975
return self.get_format_string().rstrip()
977
def supports_tags(self):
978
"""True if this format supports tags stored in the branch"""
979
return False # by default
981
# XXX: Probably doesn't really belong here -- mbp 20070212
982
def _initialize_control_files(self, a_bzrdir, utf8_files, lock_filename,
984
branch_transport = a_bzrdir.get_branch_transport(self)
985
control_files = lockable_files.LockableFiles(branch_transport,
986
lock_filename, lock_class)
987
control_files.create_lock()
988
control_files.lock_write()
990
for filename, content in utf8_files:
991
control_files.put_utf8(filename, content)
993
control_files.unlock()
996
class BranchHooks(Hooks):
997
"""A dictionary mapping hook name to a list of callables for branch hooks.
999
e.g. ['set_rh'] Is the list of items to be called when the
1000
set_revision_history function is invoked.
1004
"""Create the default hooks.
1006
These are all empty initially, because by default nothing should get
1009
Hooks.__init__(self)
1010
# Introduced in 0.15:
1011
# invoked whenever the revision history has been set
1012
# with set_revision_history. The api signature is
1013
# (branch, revision_history), and the branch will
1016
# invoked after a push operation completes.
1017
# the api signature is
1019
# containing the members
1020
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1021
# where local is the local target branch or None, master is the target
1022
# master branch, and the rest should be self explanatory. The source
1023
# is read locked and the target branches write locked. Source will
1024
# be the local low-latency branch.
1025
self['post_push'] = []
1026
# invoked after a pull operation completes.
1027
# the api signature is
1029
# containing the members
1030
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1031
# where local is the local branch or None, master is the target
1032
# master branch, and the rest should be self explanatory. The source
1033
# is read locked and the target branches write locked. The local
1034
# branch is the low-latency branch.
1035
self['post_pull'] = []
1036
# invoked after a commit operation completes.
1037
# the api signature is
1038
# (local, master, old_revno, old_revid, new_revno, new_revid)
1039
# old_revid is NULL_REVISION for the first commit to a branch.
1040
self['post_commit'] = []
1041
# invoked after a uncommit operation completes.
1042
# the api signature is
1043
# (local, master, old_revno, old_revid, new_revno, new_revid) where
1044
# local is the local branch or None, master is the target branch,
1045
# and an empty branch recieves new_revno of 0, new_revid of None.
1046
self['post_uncommit'] = []
1049
# install the default hooks into the Branch class.
1050
Branch.hooks = BranchHooks()
1053
class BzrBranchFormat4(BranchFormat):
1054
"""Bzr branch format 4.
1057
- a revision-history file.
1058
- a branch-lock lock file [ to be shared with the bzrdir ]
1061
def get_format_description(self):
1062
"""See BranchFormat.get_format_description()."""
1063
return "Branch format 4"
1065
def initialize(self, a_bzrdir):
1066
"""Create a branch of this format in a_bzrdir."""
1067
utf8_files = [('revision-history', ''),
1068
('branch-name', ''),
1070
return self._initialize_helper(a_bzrdir, utf8_files,
1071
lock_type='branch4', set_format=False)
1074
super(BzrBranchFormat4, self).__init__()
1075
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1077
def open(self, a_bzrdir, _found=False):
1078
"""Return the branch object for a_bzrdir
1080
_found is a private parameter, do not use it. It is used to indicate
1081
if format probing has already be done.
1084
# we are being called directly and must probe.
1085
raise NotImplementedError
1086
return BzrBranch(_format=self,
1087
_control_files=a_bzrdir._control_files,
1089
_repository=a_bzrdir.open_repository())
1092
return "Bazaar-NG branch format 4"
1095
class BzrBranchFormat5(BranchFormat):
1096
"""Bzr branch format 5.
1099
- a revision-history file.
1101
- a lock dir guarding the branch itself
1102
- all of this stored in a branch/ subdirectory
1103
- works with shared repositories.
1105
This format is new in bzr 0.8.
1108
def get_format_string(self):
1109
"""See BranchFormat.get_format_string()."""
1110
return "Bazaar-NG branch format 5\n"
1112
def get_format_description(self):
1113
"""See BranchFormat.get_format_description()."""
1114
return "Branch format 5"
1116
def initialize(self, a_bzrdir):
1117
"""Create a branch of this format in a_bzrdir."""
1118
utf8_files = [('revision-history', ''),
1119
('branch-name', ''),
1121
return self._initialize_helper(a_bzrdir, utf8_files)
1124
super(BzrBranchFormat5, self).__init__()
1125
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1127
def open(self, a_bzrdir, _found=False):
1128
"""Return the branch object for a_bzrdir
1130
_found is a private parameter, do not use it. It is used to indicate
1131
if format probing has already be done.
1134
format = BranchFormat.find_format(a_bzrdir)
1135
assert format.__class__ == self.__class__
1137
transport = a_bzrdir.get_branch_transport(None)
1138
control_files = lockable_files.LockableFiles(transport, 'lock',
1140
return BzrBranch5(_format=self,
1141
_control_files=control_files,
1143
_repository=a_bzrdir.find_repository())
1145
raise NotBranchError(path=transport.base)
1148
class BzrBranchFormat6(BzrBranchFormat5):
1149
"""Branch format with last-revision and tags.
1151
Unlike previous formats, this has no explicit revision history. Instead,
1152
this just stores the last-revision, and the left-hand history leading
1153
up to there is the history.
1155
This format was introduced in bzr 0.15
1156
and became the default in 0.91.
1159
def get_format_string(self):
1160
"""See BranchFormat.get_format_string()."""
1161
return "Bazaar Branch Format 6 (bzr 0.15)\n"
1163
def get_format_description(self):
1164
"""See BranchFormat.get_format_description()."""
1165
return "Branch format 6"
1167
def initialize(self, a_bzrdir):
1168
"""Create a branch of this format in a_bzrdir."""
1169
utf8_files = [('last-revision', '0 null:\n'),
1170
('branch-name', ''),
1171
('branch.conf', ''),
1174
return self._initialize_helper(a_bzrdir, utf8_files)
1176
def open(self, a_bzrdir, _found=False):
1177
"""Return the branch object for a_bzrdir
1179
_found is a private parameter, do not use it. It is used to indicate
1180
if format probing has already be done.
1183
format = BranchFormat.find_format(a_bzrdir)
1184
assert format.__class__ == self.__class__
1185
transport = a_bzrdir.get_branch_transport(None)
1186
control_files = lockable_files.LockableFiles(transport, 'lock',
1188
return BzrBranch6(_format=self,
1189
_control_files=control_files,
1191
_repository=a_bzrdir.find_repository())
1193
def supports_tags(self):
1197
class BranchReferenceFormat(BranchFormat):
1198
"""Bzr branch reference format.
1200
Branch references are used in implementing checkouts, they
1201
act as an alias to the real branch which is at some other url.
1208
def get_format_string(self):
1209
"""See BranchFormat.get_format_string()."""
1210
return "Bazaar-NG Branch Reference Format 1\n"
1212
def get_format_description(self):
1213
"""See BranchFormat.get_format_description()."""
1214
return "Checkout reference format 1"
1216
def get_reference(self, a_bzrdir):
1217
"""See BranchFormat.get_reference()."""
1218
transport = a_bzrdir.get_branch_transport(None)
1219
return transport.get('location').read()
1221
def initialize(self, a_bzrdir, target_branch=None):
1222
"""Create a branch of this format in a_bzrdir."""
1223
if target_branch is None:
1224
# this format does not implement branch itself, thus the implicit
1225
# creation contract must see it as uninitializable
1226
raise errors.UninitializableFormat(self)
1227
mutter('creating branch reference in %s', a_bzrdir.transport.base)
1228
branch_transport = a_bzrdir.get_branch_transport(self)
1229
branch_transport.put_bytes('location',
1230
target_branch.bzrdir.root_transport.base)
1231
branch_transport.put_bytes('format', self.get_format_string())
1232
return self.open(a_bzrdir, _found=True)
1235
super(BranchReferenceFormat, self).__init__()
1236
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1238
def _make_reference_clone_function(format, a_branch):
1239
"""Create a clone() routine for a branch dynamically."""
1240
def clone(to_bzrdir, revision_id=None):
1241
"""See Branch.clone()."""
1242
return format.initialize(to_bzrdir, a_branch)
1243
# cannot obey revision_id limits when cloning a reference ...
1244
# FIXME RBC 20060210 either nuke revision_id for clone, or
1245
# emit some sort of warning/error to the caller ?!
1248
def open(self, a_bzrdir, _found=False, location=None):
1249
"""Return the branch that the branch reference in a_bzrdir points at.
1251
_found is a private parameter, do not use it. It is used to indicate
1252
if format probing has already be done.
1255
format = BranchFormat.find_format(a_bzrdir)
1256
assert format.__class__ == self.__class__
1257
if location is None:
1258
location = self.get_reference(a_bzrdir)
1259
real_bzrdir = bzrdir.BzrDir.open(location)
1260
result = real_bzrdir.open_branch()
1261
# this changes the behaviour of result.clone to create a new reference
1262
# rather than a copy of the content of the branch.
1263
# I did not use a proxy object because that needs much more extensive
1264
# testing, and we are only changing one behaviour at the moment.
1265
# If we decide to alter more behaviours - i.e. the implicit nickname
1266
# then this should be refactored to introduce a tested proxy branch
1267
# and a subclass of that for use in overriding clone() and ....
1269
result.clone = self._make_reference_clone_function(result)
1273
# formats which have no format string are not discoverable
1274
# and not independently creatable, so are not registered.
1275
__format5 = BzrBranchFormat5()
1276
__format6 = BzrBranchFormat6()
1277
BranchFormat.register_format(__format5)
1278
BranchFormat.register_format(BranchReferenceFormat())
1279
BranchFormat.register_format(__format6)
1280
BranchFormat.set_default_format(__format6)
1281
_legacy_formats = [BzrBranchFormat4(),
1284
class BzrBranch(Branch):
1285
"""A branch stored in the actual filesystem.
1287
Note that it's "local" in the context of the filesystem; it doesn't
1288
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1289
it's writable, and can be accessed via the normal filesystem API.
1292
def __init__(self, _format=None,
1293
_control_files=None, a_bzrdir=None, _repository=None):
1294
"""Create new branch object at a particular location."""
1295
Branch.__init__(self)
1296
if a_bzrdir is None:
1297
raise ValueError('a_bzrdir must be supplied')
1299
self.bzrdir = a_bzrdir
1300
# self._transport used to point to the directory containing the
1301
# control directory, but was not used - now it's just the transport
1302
# for the branch control files. mbp 20070212
1303
self._base = self.bzrdir.transport.clone('..').base
1304
self._format = _format
1305
if _control_files is None:
1306
raise ValueError('BzrBranch _control_files is None')
1307
self.control_files = _control_files
1308
self._transport = _control_files._transport
1309
self.repository = _repository
1312
return '%s(%r)' % (self.__class__.__name__, self.base)
1316
def _get_base(self):
1317
"""Returns the directory containing the control directory."""
1320
base = property(_get_base, doc="The URL for the root of this branch.")
1322
def abspath(self, name):
1323
"""See Branch.abspath."""
1324
return self.control_files._transport.abspath(name)
1327
@deprecated_method(zero_sixteen)
1329
def get_root_id(self):
1330
"""See Branch.get_root_id."""
1331
tree = self.repository.revision_tree(self.last_revision())
1332
return tree.inventory.root.file_id
1334
def is_locked(self):
1335
return self.control_files.is_locked()
1337
def lock_write(self, token=None):
1338
repo_token = self.repository.lock_write()
1340
token = self.control_files.lock_write(token=token)
1342
self.repository.unlock()
1346
def lock_read(self):
1347
self.repository.lock_read()
1349
self.control_files.lock_read()
1351
self.repository.unlock()
1355
# TODO: test for failed two phase locks. This is known broken.
1357
self.control_files.unlock()
1359
self.repository.unlock()
1360
if not self.control_files.is_locked():
1361
# we just released the lock
1362
self._clear_cached_state()
1364
def peek_lock_mode(self):
1365
if self.control_files._lock_count == 0:
1368
return self.control_files._lock_mode
1370
def get_physical_lock_status(self):
1371
return self.control_files.get_physical_lock_status()
1374
def print_file(self, file, revision_id):
1375
"""See Branch.print_file."""
1376
return self.repository.print_file(file, revision_id)
1378
@deprecated_method(zero_ninetyone)
1380
def append_revision(self, *revision_ids):
1381
"""See Branch.append_revision."""
1382
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1383
for revision_id in revision_ids:
1384
_mod_revision.check_not_reserved_id(revision_id)
1385
mutter("add {%s} to revision-history" % revision_id)
1386
rev_history = self.revision_history()
1387
rev_history.extend(revision_ids)
1388
self.set_revision_history(rev_history)
1390
def _write_revision_history(self, history):
1391
"""Factored out of set_revision_history.
1393
This performs the actual writing to disk.
1394
It is intended to be called by BzrBranch5.set_revision_history."""
1395
self.control_files.put_bytes(
1396
'revision-history', '\n'.join(history))
1399
def set_revision_history(self, rev_history):
1400
"""See Branch.set_revision_history."""
1401
rev_history = [osutils.safe_revision_id(r) for r in rev_history]
1402
self._clear_cached_state()
1403
self._write_revision_history(rev_history)
1404
self._cache_revision_history(rev_history)
1405
for hook in Branch.hooks['set_rh']:
1406
hook(self, rev_history)
1409
def set_last_revision_info(self, revno, revision_id):
1410
revision_id = osutils.safe_revision_id(revision_id)
1411
history = self._lefthand_history(revision_id)
1412
assert len(history) == revno, '%d != %d' % (len(history), revno)
1413
self.set_revision_history(history)
1415
def _gen_revision_history(self):
1416
history = self.control_files.get('revision-history').read().split('\n')
1417
if history[-1:] == ['']:
1418
# There shouldn't be a trailing newline, but just in case.
1422
def _lefthand_history(self, revision_id, last_rev=None,
1424
# stop_revision must be a descendant of last_revision
1425
stop_graph = self.repository.get_revision_graph(revision_id)
1426
if (last_rev is not None and last_rev != _mod_revision.NULL_REVISION
1427
and last_rev not in stop_graph):
1428
# our previous tip is not merged into stop_revision
1429
raise errors.DivergedBranches(self, other_branch)
1430
# make a new revision history from the graph
1431
current_rev_id = revision_id
1433
while current_rev_id not in (None, _mod_revision.NULL_REVISION):
1434
new_history.append(current_rev_id)
1435
current_rev_id_parents = stop_graph[current_rev_id]
1437
current_rev_id = current_rev_id_parents[0]
1439
current_rev_id = None
1440
new_history.reverse()
1444
def generate_revision_history(self, revision_id, last_rev=None,
1446
"""Create a new revision history that will finish with revision_id.
1448
:param revision_id: the new tip to use.
1449
:param last_rev: The previous last_revision. If not None, then this
1450
must be a ancestory of revision_id, or DivergedBranches is raised.
1451
:param other_branch: The other branch that DivergedBranches should
1452
raise with respect to.
1454
revision_id = osutils.safe_revision_id(revision_id)
1455
self.set_revision_history(self._lefthand_history(revision_id,
1456
last_rev, other_branch))
1459
def update_revisions(self, other, stop_revision=None):
1460
"""See Branch.update_revisions."""
1463
if stop_revision is None:
1464
stop_revision = other.last_revision()
1465
if stop_revision is None:
1466
# if there are no commits, we're done.
1469
stop_revision = osutils.safe_revision_id(stop_revision)
1470
# whats the current last revision, before we fetch [and change it
1472
last_rev = _mod_revision.ensure_null(self.last_revision())
1473
# we fetch here regardless of whether we need to so that we pickup
1475
self.fetch(other, stop_revision)
1476
if self.repository.get_graph().is_ancestor(stop_revision,
1479
self.generate_revision_history(stop_revision, last_rev=last_rev,
1484
def basis_tree(self):
1485
"""See Branch.basis_tree."""
1486
return self.repository.revision_tree(self.last_revision())
1488
@deprecated_method(zero_eight)
1489
def working_tree(self):
1490
"""Create a Working tree object for this branch."""
1492
from bzrlib.transport.local import LocalTransport
1493
if (self.base.find('://') != -1 or
1494
not isinstance(self._transport, LocalTransport)):
1495
raise NoWorkingTree(self.base)
1496
return self.bzrdir.open_workingtree()
1499
def pull(self, source, overwrite=False, stop_revision=None,
1500
_hook_master=None, run_hooks=True):
1503
:param _hook_master: Private parameter - set the branch to
1504
be supplied as the master to push hooks.
1505
:param run_hooks: Private parameter - if false, this branch
1506
is being called because it's the master of the primary branch,
1507
so it should not run its hooks.
1509
result = PullResult()
1510
result.source_branch = source
1511
result.target_branch = self
1514
result.old_revno, result.old_revid = self.last_revision_info()
1516
self.update_revisions(source, stop_revision)
1517
except DivergedBranches:
1521
if stop_revision is None:
1522
stop_revision = source.last_revision()
1523
self.generate_revision_history(stop_revision)
1524
result.tag_conflicts = source.tags.merge_to(self.tags)
1525
result.new_revno, result.new_revid = self.last_revision_info()
1527
result.master_branch = _hook_master
1528
result.local_branch = self
1530
result.master_branch = self
1531
result.local_branch = None
1533
for hook in Branch.hooks['post_pull']:
1539
def _get_parent_location(self):
1540
_locs = ['parent', 'pull', 'x-pull']
1543
return self.control_files.get(l).read().strip('\n')
1549
def push(self, target, overwrite=False, stop_revision=None,
1550
_override_hook_source_branch=None):
1553
This is the basic concrete implementation of push()
1555
:param _override_hook_source_branch: If specified, run
1556
the hooks passing this Branch as the source, rather than self.
1557
This is for use of RemoteBranch, where push is delegated to the
1558
underlying vfs-based Branch.
1560
# TODO: Public option to disable running hooks - should be trivial but
1564
result = self._push_with_bound_branches(target, overwrite,
1566
_override_hook_source_branch=_override_hook_source_branch)
1571
def _push_with_bound_branches(self, target, overwrite,
1573
_override_hook_source_branch=None):
1574
"""Push from self into target, and into target's master if any.
1576
This is on the base BzrBranch class even though it doesn't support
1577
bound branches because the *target* might be bound.
1580
if _override_hook_source_branch:
1581
result.source_branch = _override_hook_source_branch
1582
for hook in Branch.hooks['post_push']:
1585
bound_location = target.get_bound_location()
1586
if bound_location and target.base != bound_location:
1587
# there is a master branch.
1589
# XXX: Why the second check? Is it even supported for a branch to
1590
# be bound to itself? -- mbp 20070507
1591
master_branch = target.get_master_branch()
1592
master_branch.lock_write()
1594
# push into the master from this branch.
1595
self._basic_push(master_branch, overwrite, stop_revision)
1596
# and push into the target branch from this. Note that we push from
1597
# this branch again, because its considered the highest bandwidth
1599
result = self._basic_push(target, overwrite, stop_revision)
1600
result.master_branch = master_branch
1601
result.local_branch = target
1605
master_branch.unlock()
1608
result = self._basic_push(target, overwrite, stop_revision)
1609
# TODO: Why set master_branch and local_branch if there's no
1610
# binding? Maybe cleaner to just leave them unset? -- mbp
1612
result.master_branch = target
1613
result.local_branch = None
1617
def _basic_push(self, target, overwrite, stop_revision):
1618
"""Basic implementation of push without bound branches or hooks.
1620
Must be called with self read locked and target write locked.
1622
result = PushResult()
1623
result.source_branch = self
1624
result.target_branch = target
1625
result.old_revno, result.old_revid = target.last_revision_info()
1627
target.update_revisions(self, stop_revision)
1628
except DivergedBranches:
1632
target.set_revision_history(self.revision_history())
1633
result.tag_conflicts = self.tags.merge_to(target.tags)
1634
result.new_revno, result.new_revid = target.last_revision_info()
1637
def get_parent(self):
1638
"""See Branch.get_parent."""
1640
assert self.base[-1] == '/'
1641
parent = self._get_parent_location()
1644
# This is an old-format absolute path to a local branch
1645
# turn it into a url
1646
if parent.startswith('/'):
1647
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1649
return urlutils.join(self.base[:-1], parent)
1650
except errors.InvalidURLJoin, e:
1651
raise errors.InaccessibleParent(parent, self.base)
1653
def set_push_location(self, location):
1654
"""See Branch.set_push_location."""
1655
self.get_config().set_user_option(
1656
'push_location', location,
1657
store=_mod_config.STORE_LOCATION_NORECURSE)
1660
def set_parent(self, url):
1661
"""See Branch.set_parent."""
1662
# TODO: Maybe delete old location files?
1663
# URLs should never be unicode, even on the local fs,
1664
# FIXUP this and get_parent in a future branch format bump:
1665
# read and rewrite the file, and have the new format code read
1666
# using .get not .get_utf8. RBC 20060125
1668
if isinstance(url, unicode):
1670
url = url.encode('ascii')
1671
except UnicodeEncodeError:
1672
raise errors.InvalidURL(url,
1673
"Urls must be 7-bit ascii, "
1674
"use bzrlib.urlutils.escape")
1675
url = urlutils.relative_url(self.base, url)
1676
self._set_parent_location(url)
1678
def _set_parent_location(self, url):
1680
self.control_files._transport.delete('parent')
1682
assert isinstance(url, str)
1683
self.control_files.put_bytes('parent', url + '\n')
1685
@deprecated_function(zero_nine)
1686
def tree_config(self):
1687
"""DEPRECATED; call get_config instead.
1688
TreeConfig has become part of BranchConfig."""
1689
return TreeConfig(self)
1692
class BzrBranch5(BzrBranch):
1693
"""A format 5 branch. This supports new features over plan branches.
1695
It has support for a master_branch which is the data for bound branches.
1703
super(BzrBranch5, self).__init__(_format=_format,
1704
_control_files=_control_files,
1706
_repository=_repository)
1709
def pull(self, source, overwrite=False, stop_revision=None,
1711
"""Pull from source into self, updating my master if any.
1713
:param run_hooks: Private parameter - if false, this branch
1714
is being called because it's the master of the primary branch,
1715
so it should not run its hooks.
1717
bound_location = self.get_bound_location()
1718
master_branch = None
1719
if bound_location and source.base != bound_location:
1720
# not pulling from master, so we need to update master.
1721
master_branch = self.get_master_branch()
1722
master_branch.lock_write()
1725
# pull from source into master.
1726
master_branch.pull(source, overwrite, stop_revision,
1728
return super(BzrBranch5, self).pull(source, overwrite,
1729
stop_revision, _hook_master=master_branch,
1730
run_hooks=run_hooks)
1733
master_branch.unlock()
1735
def get_bound_location(self):
1737
return self.control_files.get_utf8('bound').read()[:-1]
1738
except errors.NoSuchFile:
1742
def get_master_branch(self):
1743
"""Return the branch we are bound to.
1745
:return: Either a Branch, or None
1747
This could memoise the branch, but if thats done
1748
it must be revalidated on each new lock.
1749
So for now we just don't memoise it.
1750
# RBC 20060304 review this decision.
1752
bound_loc = self.get_bound_location()
1756
return Branch.open(bound_loc)
1757
except (errors.NotBranchError, errors.ConnectionError), e:
1758
raise errors.BoundBranchConnectionFailure(
1762
def set_bound_location(self, location):
1763
"""Set the target where this branch is bound to.
1765
:param location: URL to the target branch
1768
self.control_files.put_utf8('bound', location+'\n')
1771
self.control_files._transport.delete('bound')
1777
def bind(self, other):
1778
"""Bind this branch to the branch other.
1780
This does not push or pull data between the branches, though it does
1781
check for divergence to raise an error when the branches are not
1782
either the same, or one a prefix of the other. That behaviour may not
1783
be useful, so that check may be removed in future.
1785
:param other: The branch to bind to
1788
# TODO: jam 20051230 Consider checking if the target is bound
1789
# It is debatable whether you should be able to bind to
1790
# a branch which is itself bound.
1791
# Committing is obviously forbidden,
1792
# but binding itself may not be.
1793
# Since we *have* to check at commit time, we don't
1794
# *need* to check here
1796
# we want to raise diverged if:
1797
# last_rev is not in the other_last_rev history, AND
1798
# other_last_rev is not in our history, and do it without pulling
1800
last_rev = _mod_revision.ensure_null(self.last_revision())
1801
if last_rev != _mod_revision.NULL_REVISION:
1804
other_last_rev = other.last_revision()
1805
if not _mod_revision.is_null(other_last_rev):
1806
# neither branch is new, we have to do some work to
1807
# ascertain diversion.
1808
remote_graph = other.repository.get_revision_graph(
1810
local_graph = self.repository.get_revision_graph(last_rev)
1811
if (last_rev not in remote_graph and
1812
other_last_rev not in local_graph):
1813
raise errors.DivergedBranches(self, other)
1816
self.set_bound_location(other.base)
1820
"""If bound, unbind"""
1821
return self.set_bound_location(None)
1825
"""Synchronise this branch with the master branch if any.
1827
:return: None or the last_revision that was pivoted out during the
1830
master = self.get_master_branch()
1831
if master is not None:
1832
old_tip = _mod_revision.ensure_null(self.last_revision())
1833
self.pull(master, overwrite=True)
1834
if self.repository.get_graph().is_ancestor(old_tip,
1835
_mod_revision.ensure_null(self.last_revision())):
1841
class BzrBranchExperimental(BzrBranch5):
1842
"""Bzr experimental branch format
1845
- a revision-history file.
1847
- a lock dir guarding the branch itself
1848
- all of this stored in a branch/ subdirectory
1849
- works with shared repositories.
1850
- a tag dictionary in the branch
1852
This format is new in bzr 0.15, but shouldn't be used for real data,
1855
This class acts as it's own BranchFormat.
1858
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1861
def get_format_string(cls):
1862
"""See BranchFormat.get_format_string()."""
1863
return "Bazaar-NG branch format experimental\n"
1866
def get_format_description(cls):
1867
"""See BranchFormat.get_format_description()."""
1868
return "Experimental branch format"
1871
def get_reference(cls, a_bzrdir):
1872
"""Get the target reference of the branch in a_bzrdir.
1874
format probing must have been completed before calling
1875
this method - it is assumed that the format of the branch
1876
in a_bzrdir is correct.
1878
:param a_bzrdir: The bzrdir to get the branch data from.
1879
:return: None if the branch is not a reference branch.
1884
def _initialize_control_files(cls, a_bzrdir, utf8_files, lock_filename,
1886
branch_transport = a_bzrdir.get_branch_transport(cls)
1887
control_files = lockable_files.LockableFiles(branch_transport,
1888
lock_filename, lock_class)
1889
control_files.create_lock()
1890
control_files.lock_write()
1892
for filename, content in utf8_files:
1893
control_files.put_utf8(filename, content)
1895
control_files.unlock()
1898
def initialize(cls, a_bzrdir):
1899
"""Create a branch of this format in a_bzrdir."""
1900
utf8_files = [('format', cls.get_format_string()),
1901
('revision-history', ''),
1902
('branch-name', ''),
1905
cls._initialize_control_files(a_bzrdir, utf8_files,
1906
'lock', lockdir.LockDir)
1907
return cls.open(a_bzrdir, _found=True)
1910
def open(cls, a_bzrdir, _found=False):
1911
"""Return the branch object for a_bzrdir
1913
_found is a private parameter, do not use it. It is used to indicate
1914
if format probing has already be done.
1917
format = BranchFormat.find_format(a_bzrdir)
1918
assert format.__class__ == cls
1919
transport = a_bzrdir.get_branch_transport(None)
1920
control_files = lockable_files.LockableFiles(transport, 'lock',
1922
return cls(_format=cls,
1923
_control_files=control_files,
1925
_repository=a_bzrdir.find_repository())
1928
def is_supported(cls):
1931
def _make_tags(self):
1932
return BasicTags(self)
1935
def supports_tags(cls):
1939
BranchFormat.register_format(BzrBranchExperimental)
1942
class BzrBranch6(BzrBranch5):
1945
def last_revision_info(self):
1946
revision_string = self.control_files.get('last-revision').read()
1947
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
1948
revision_id = cache_utf8.get_cached_utf8(revision_id)
1950
return revno, revision_id
1952
def last_revision(self):
1953
"""Return last revision id, or None"""
1954
revision_id = self.last_revision_info()[1]
1955
if revision_id == _mod_revision.NULL_REVISION:
1959
def _write_last_revision_info(self, revno, revision_id):
1960
"""Simply write out the revision id, with no checks.
1962
Use set_last_revision_info to perform this safely.
1964
Does not update the revision_history cache.
1965
Intended to be called by set_last_revision_info and
1966
_write_revision_history.
1968
if revision_id is None:
1969
revision_id = 'null:'
1970
out_string = '%d %s\n' % (revno, revision_id)
1971
self.control_files.put_bytes('last-revision', out_string)
1974
def set_last_revision_info(self, revno, revision_id):
1975
revision_id = osutils.safe_revision_id(revision_id)
1976
if self._get_append_revisions_only():
1977
self._check_history_violation(revision_id)
1978
self._write_last_revision_info(revno, revision_id)
1979
self._clear_cached_state()
1981
def _check_history_violation(self, revision_id):
1982
last_revision = _mod_revision.ensure_null(self.last_revision())
1983
if _mod_revision.is_null(last_revision):
1985
if last_revision not in self._lefthand_history(revision_id):
1986
raise errors.AppendRevisionsOnlyViolation(self.base)
1988
def _gen_revision_history(self):
1989
"""Generate the revision history from last revision
1991
history = list(self.repository.iter_reverse_revision_history(
1992
self.last_revision()))
1996
def _write_revision_history(self, history):
1997
"""Factored out of set_revision_history.
1999
This performs the actual writing to disk, with format-specific checks.
2000
It is intended to be called by BzrBranch5.set_revision_history.
2002
if len(history) == 0:
2003
last_revision = 'null:'
2005
if history != self._lefthand_history(history[-1]):
2006
raise errors.NotLefthandHistory(history)
2007
last_revision = history[-1]
2008
if self._get_append_revisions_only():
2009
self._check_history_violation(last_revision)
2010
self._write_last_revision_info(len(history), last_revision)
2012
@deprecated_method(zero_ninetyone)
2014
def append_revision(self, *revision_ids):
2015
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
2016
if len(revision_ids) == 0:
2018
prev_revno, prev_revision = self.last_revision_info()
2019
for revision in self.repository.get_revisions(revision_ids):
2020
if prev_revision == _mod_revision.NULL_REVISION:
2021
if revision.parent_ids != []:
2022
raise errors.NotLeftParentDescendant(self, prev_revision,
2023
revision.revision_id)
2025
if revision.parent_ids[0] != prev_revision:
2026
raise errors.NotLeftParentDescendant(self, prev_revision,
2027
revision.revision_id)
2028
prev_revision = revision.revision_id
2029
self.set_last_revision_info(prev_revno + len(revision_ids),
2033
def _set_parent_location(self, url):
2034
"""Set the parent branch"""
2035
self._set_config_location('parent_location', url, make_relative=True)
2038
def _get_parent_location(self):
2039
"""Set the parent branch"""
2040
return self._get_config_location('parent_location')
2042
def set_push_location(self, location):
2043
"""See Branch.set_push_location."""
2044
self._set_config_location('push_location', location)
2046
def set_bound_location(self, location):
2047
"""See Branch.set_push_location."""
2049
config = self.get_config()
2050
if location is None:
2051
if config.get_user_option('bound') != 'True':
2054
config.set_user_option('bound', 'False', warn_masked=True)
2057
self._set_config_location('bound_location', location,
2059
config.set_user_option('bound', 'True', warn_masked=True)
2062
def _get_bound_location(self, bound):
2063
"""Return the bound location in the config file.
2065
Return None if the bound parameter does not match"""
2066
config = self.get_config()
2067
config_bound = (config.get_user_option('bound') == 'True')
2068
if config_bound != bound:
2070
return self._get_config_location('bound_location', config=config)
2072
def get_bound_location(self):
2073
"""See Branch.set_push_location."""
2074
return self._get_bound_location(True)
2076
def get_old_bound_location(self):
2077
"""See Branch.get_old_bound_location"""
2078
return self._get_bound_location(False)
2080
def set_append_revisions_only(self, enabled):
2085
self.get_config().set_user_option('append_revisions_only', value,
2088
def _get_append_revisions_only(self):
2089
value = self.get_config().get_user_option('append_revisions_only')
2090
return value == 'True'
2092
def _synchronize_history(self, destination, revision_id):
2093
"""Synchronize last revision and revision history between branches.
2095
This version is most efficient when the destination is also a
2096
BzrBranch6, but works for BzrBranch5, as long as the destination's
2097
repository contains all the lefthand ancestors of the intended
2098
last_revision. If not, set_last_revision_info will fail.
2100
:param destination: The branch to copy the history into
2101
:param revision_id: The revision-id to truncate history at. May
2102
be None to copy complete history.
2104
source_revno, source_revision_id = self.last_revision_info()
2105
if revision_id is None:
2106
revno, revision_id = source_revno, source_revision_id
2107
elif source_revision_id == revision_id:
2108
# we know the revno without needing to walk all of history
2109
revno = source_revno
2111
# To figure out the revno for a random revision, we need to build
2112
# the revision history, and count its length.
2113
# We don't care about the order, just how long it is.
2114
# Alternatively, we could start at the current location, and count
2115
# backwards. But there is no guarantee that we will find it since
2116
# it may be a merged revision.
2117
revno = len(list(self.repository.iter_reverse_revision_history(
2119
destination.set_last_revision_info(revno, revision_id)
2121
def _make_tags(self):
2122
return BasicTags(self)
2125
######################################################################
2126
# results of operations
2129
class _Result(object):
2131
def _show_tag_conficts(self, to_file):
2132
if not getattr(self, 'tag_conflicts', None):
2134
to_file.write('Conflicting tags:\n')
2135
for name, value1, value2 in self.tag_conflicts:
2136
to_file.write(' %s\n' % (name, ))
2139
class PullResult(_Result):
2140
"""Result of a Branch.pull operation.
2142
:ivar old_revno: Revision number before pull.
2143
:ivar new_revno: Revision number after pull.
2144
:ivar old_revid: Tip revision id before pull.
2145
:ivar new_revid: Tip revision id after pull.
2146
:ivar source_branch: Source (local) branch object.
2147
:ivar master_branch: Master branch of the target, or None.
2148
:ivar target_branch: Target/destination branch object.
2152
# DEPRECATED: pull used to return the change in revno
2153
return self.new_revno - self.old_revno
2155
def report(self, to_file):
2156
if self.old_revid == self.new_revid:
2157
to_file.write('No revisions to pull.\n')
2159
to_file.write('Now on revision %d.\n' % self.new_revno)
2160
self._show_tag_conficts(to_file)
2163
class PushResult(_Result):
2164
"""Result of a Branch.push operation.
2166
:ivar old_revno: Revision number before push.
2167
:ivar new_revno: Revision number after push.
2168
:ivar old_revid: Tip revision id before push.
2169
:ivar new_revid: Tip revision id after push.
2170
:ivar source_branch: Source branch object.
2171
:ivar master_branch: Master branch of the target, or None.
2172
:ivar target_branch: Target/destination branch object.
2176
# DEPRECATED: push used to return the change in revno
2177
return self.new_revno - self.old_revno
2179
def report(self, to_file):
2180
"""Write a human-readable description of the result."""
2181
if self.old_revid == self.new_revid:
2182
to_file.write('No new revisions to push.\n')
2184
to_file.write('Pushed up to revision %d.\n' % self.new_revno)
2185
self._show_tag_conficts(to_file)
2188
class BranchCheckResult(object):
2189
"""Results of checking branch consistency.
2194
def __init__(self, branch):
2195
self.branch = branch
2197
def report_results(self, verbose):
2198
"""Report the check results via trace.note.
2200
:param verbose: Requests more detailed display of what was checked,
2203
note('checked branch %s format %s',
2205
self.branch._format)
2208
class Converter5to6(object):
2209
"""Perform an in-place upgrade of format 5 to format 6"""
2211
def convert(self, branch):
2212
# Data for 5 and 6 can peacefully coexist.
2213
format = BzrBranchFormat6()
2214
new_branch = format.open(branch.bzrdir, _found=True)
2216
# Copy source data into target
2217
new_branch.set_last_revision_info(*branch.last_revision_info())
2218
new_branch.set_parent(branch.get_parent())
2219
new_branch.set_bound_location(branch.get_bound_location())
2220
new_branch.set_push_location(branch.get_push_location())
2222
# New branch has no tags by default
2223
new_branch.tags._set_tag_dict({})
2225
# Copying done; now update target format
2226
new_branch.control_files.put_utf8('format',
2227
format.get_format_string())
2229
# Clean up old files
2230
new_branch.control_files._transport.delete('revision-history')
2232
branch.set_parent(None)
2235
branch.set_bound_location(None)