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 copy import deepcopy
23
from unittest import TestSuite
24
from warnings import warn
30
config as _mod_config,
35
revision as _mod_revision,
42
from bzrlib.config import BranchConfig, TreeConfig
43
from bzrlib.lockable_files import LockableFiles, TransportLock
44
from bzrlib.tag import (
50
from bzrlib.decorators import needs_read_lock, needs_write_lock
51
from bzrlib.errors import (BzrError, BzrCheckError, DivergedBranches,
52
HistoryMissing, InvalidRevisionId,
53
InvalidRevisionNumber, LockError, NoSuchFile,
54
NoSuchRevision, NoWorkingTree, NotVersionedError,
55
NotBranchError, UninitializableFormat,
56
UnlistableStore, UnlistableBranch,
58
from bzrlib.hooks import Hooks
59
from bzrlib.symbol_versioning import (deprecated_function,
63
zero_eight, zero_nine, zero_sixteen,
65
from bzrlib.trace import mutter, note
68
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
69
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
70
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
73
# TODO: Maybe include checks for common corruption of newlines, etc?
75
# TODO: Some operations like log might retrieve the same revisions
76
# repeatedly to calculate deltas. We could perhaps have a weakref
77
# cache in memory to make this faster. In general anything can be
78
# cached in memory between lock and unlock operations. .. nb thats
79
# what the transaction identity map provides
82
######################################################################
86
"""Branch holding a history of revisions.
89
Base directory/url of the branch.
91
hooks: An instance of BranchHooks.
93
# this is really an instance variable - FIXME move it there
97
# override this to set the strategy for storing tags
99
return DisabledTags(self)
101
def __init__(self, *ignored, **ignored_too):
102
self.tags = self._make_tags()
103
self._revision_history_cache = None
104
self._revision_id_to_revno_cache = None
106
def break_lock(self):
107
"""Break a lock if one is present from another instance.
109
Uses the ui factory to ask for confirmation if the lock may be from
112
This will probe the repository for its lock as well.
114
self.control_files.break_lock()
115
self.repository.break_lock()
116
master = self.get_master_branch()
117
if master is not None:
121
@deprecated_method(zero_eight)
122
def open_downlevel(base):
123
"""Open a branch which may be of an old format."""
124
return Branch.open(base, _unsupported=True)
127
def open(base, _unsupported=False):
128
"""Open the branch rooted at base.
130
For instance, if the branch is at URL/.bzr/branch,
131
Branch.open(URL) -> a Branch instance.
133
control = bzrdir.BzrDir.open(base, _unsupported)
134
return control.open_branch(_unsupported)
137
def open_containing(url):
138
"""Open an existing branch which contains url.
140
This probes for a branch at url, and searches upwards from there.
142
Basically we keep looking up until we find the control directory or
143
run into the root. If there isn't one, raises NotBranchError.
144
If there is one and it is either an unrecognised format or an unsupported
145
format, UnknownFormatError or UnsupportedFormatError are raised.
146
If there is one, it is returned, along with the unused portion of url.
148
control, relpath = bzrdir.BzrDir.open_containing(url)
149
return control.open_branch(), relpath
152
@deprecated_function(zero_eight)
153
def initialize(base):
154
"""Create a new working tree and branch, rooted at 'base' (url)
156
NOTE: This will soon be deprecated in favour of creation
159
return bzrdir.BzrDir.create_standalone_workingtree(base).branch
161
@deprecated_function(zero_eight)
162
def setup_caching(self, cache_root):
163
"""Subclasses that care about caching should override this, and set
164
up cached stores located under cache_root.
166
NOTE: This is unused.
170
def get_config(self):
171
return BranchConfig(self)
174
return self.get_config().get_nickname()
176
def _set_nick(self, nick):
177
self.get_config().set_user_option('nickname', nick)
179
nick = property(_get_nick, _set_nick)
182
raise NotImplementedError(self.is_locked)
184
def lock_write(self):
185
raise NotImplementedError(self.lock_write)
188
raise NotImplementedError(self.lock_read)
191
raise NotImplementedError(self.unlock)
193
def peek_lock_mode(self):
194
"""Return lock mode for the Branch: 'r', 'w' or None"""
195
raise NotImplementedError(self.peek_lock_mode)
197
def get_physical_lock_status(self):
198
raise NotImplementedError(self.get_physical_lock_status)
200
def leave_lock_in_place(self):
201
"""Tell this branch object not to release the physical lock when this
204
If lock_write doesn't return a token, then this method is not supported.
206
self.control_files.leave_in_place()
208
def dont_leave_lock_in_place(self):
209
"""Tell this branch object to release the physical lock when this
210
object is unlocked, even if it didn't originally acquire it.
212
If lock_write doesn't return a token, then this method is not supported.
214
self.control_files.dont_leave_in_place()
216
def abspath(self, name):
217
"""Return absolute filename for something in the branch
219
XXX: Robert Collins 20051017 what is this used for? why is it a branch
220
method and not a tree method.
222
raise NotImplementedError(self.abspath)
224
def bind(self, other):
225
"""Bind the local branch the other branch.
227
:param other: The branch to bind to
230
raise errors.UpgradeRequired(self.base)
233
def fetch(self, from_branch, last_revision=None, pb=None):
234
"""Copy revisions from from_branch into this branch.
236
:param from_branch: Where to copy from.
237
:param last_revision: What revision to stop at (None for at the end
239
:param pb: An optional progress bar to use.
241
Returns the copied revision count and the failed revisions in a tuple:
244
if self.base == from_branch.base:
247
nested_pb = ui.ui_factory.nested_progress_bar()
252
from_branch.lock_read()
254
if last_revision is None:
255
pb.update('get source history')
256
last_revision = from_branch.last_revision()
257
if last_revision is None:
258
last_revision = _mod_revision.NULL_REVISION
259
return self.repository.fetch(from_branch.repository,
260
revision_id=last_revision,
263
if nested_pb is not None:
267
def get_bound_location(self):
268
"""Return the URL of the branch we are bound to.
270
Older format branches cannot bind, please be sure to use a metadir
275
def get_old_bound_location(self):
276
"""Return the URL of the branch we used to be bound to
278
raise errors.UpgradeRequired(self.base)
280
def get_commit_builder(self, parents, config=None, timestamp=None,
281
timezone=None, committer=None, revprops=None,
283
"""Obtain a CommitBuilder for this branch.
285
:param parents: Revision ids of the parents of the new revision.
286
:param config: Optional configuration to use.
287
:param timestamp: Optional timestamp recorded for commit.
288
:param timezone: Optional timezone for timestamp.
289
:param committer: Optional committer to set for commit.
290
:param revprops: Optional dictionary of revision properties.
291
:param revision_id: Optional revision id.
295
config = self.get_config()
297
return self.repository.get_commit_builder(self, parents, config,
298
timestamp, timezone, committer, revprops, revision_id)
300
def get_master_branch(self):
301
"""Return the branch we are bound to.
303
:return: Either a Branch, or None
307
def get_revision_delta(self, revno):
308
"""Return the delta for one revision.
310
The delta is relative to its mainline predecessor, or the
311
empty tree for revision 1.
313
assert isinstance(revno, int)
314
rh = self.revision_history()
315
if not (1 <= revno <= len(rh)):
316
raise InvalidRevisionNumber(revno)
317
return self.repository.get_revision_delta(rh[revno-1])
319
@deprecated_method(zero_sixteen)
320
def get_root_id(self):
321
"""Return the id of this branches root
323
Deprecated: branches don't have root ids-- trees do.
324
Use basis_tree().get_root_id() instead.
326
raise NotImplementedError(self.get_root_id)
328
def print_file(self, file, revision_id):
329
"""Print `file` to stdout."""
330
raise NotImplementedError(self.print_file)
332
def append_revision(self, *revision_ids):
333
raise NotImplementedError(self.append_revision)
335
def set_revision_history(self, rev_history):
336
raise NotImplementedError(self.set_revision_history)
338
def _cache_revision_history(self, rev_history):
339
"""Set the cached revision history to rev_history.
341
The revision_history method will use this cache to avoid regenerating
342
the revision history.
344
This API is semi-public; it only for use by subclasses, all other code
345
should consider it to be private.
347
self._revision_history_cache = rev_history
349
def _cache_revision_id_to_revno(self, revision_id_to_revno):
350
"""Set the cached revision_id => revno map to revision_id_to_revno.
352
This API is semi-public; it only for use by subclasses, all other code
353
should consider it to be private.
355
self._revision_id_to_revno_cache = revision_id_to_revno
357
def _clear_cached_state(self):
358
"""Clear any cached data on this branch, e.g. cached revision history.
360
This means the next call to revision_history will need to call
361
_gen_revision_history.
363
This API is semi-public; it only for use by subclasses, all other code
364
should consider it to be private.
366
self._revision_history_cache = None
367
self._revision_id_to_revno_cache = None
369
def _gen_revision_history(self):
370
"""Return sequence of revision hashes on to this branch.
372
Unlike revision_history, this method always regenerates or rereads the
373
revision history, i.e. it does not cache the result, so repeated calls
376
Concrete subclasses should override this instead of revision_history so
377
that subclasses do not need to deal with caching logic.
379
This API is semi-public; it only for use by subclasses, all other code
380
should consider it to be private.
382
raise NotImplementedError(self._gen_revision_history)
385
def revision_history(self):
386
"""Return sequence of revision hashes on to this branch.
388
This method will cache the revision history for as long as it is safe to
391
if self._revision_history_cache is not None:
392
history = self._revision_history_cache
394
history = self._gen_revision_history()
395
self._cache_revision_history(history)
399
"""Return current revision number for this branch.
401
That is equivalent to the number of revisions committed to
404
return len(self.revision_history())
407
"""Older format branches cannot bind or unbind."""
408
raise errors.UpgradeRequired(self.base)
410
def set_append_revisions_only(self, enabled):
411
"""Older format branches are never restricted to append-only"""
412
raise errors.UpgradeRequired(self.base)
414
def last_revision(self):
415
"""Return last revision id, or None"""
416
ph = self.revision_history()
422
def last_revision_info(self):
423
"""Return information about the last revision.
425
:return: A tuple (revno, last_revision_id).
427
rh = self.revision_history()
430
return (revno, rh[-1])
432
return (0, _mod_revision.NULL_REVISION)
434
def missing_revisions(self, other, stop_revision=None):
435
"""Return a list of new revisions that would perfectly fit.
437
If self and other have not diverged, return a list of the revisions
438
present in other, but missing from self.
440
self_history = self.revision_history()
441
self_len = len(self_history)
442
other_history = other.revision_history()
443
other_len = len(other_history)
444
common_index = min(self_len, other_len) -1
445
if common_index >= 0 and \
446
self_history[common_index] != other_history[common_index]:
447
raise DivergedBranches(self, other)
449
if stop_revision is None:
450
stop_revision = other_len
452
assert isinstance(stop_revision, int)
453
if stop_revision > other_len:
454
raise errors.NoSuchRevision(self, stop_revision)
455
return other_history[self_len:stop_revision]
457
def update_revisions(self, other, stop_revision=None):
458
"""Pull in new perfect-fit revisions.
460
:param other: Another Branch to pull from
461
:param stop_revision: Updated until the given revision
464
raise NotImplementedError(self.update_revisions)
467
def revision_id_to_dotted_revno(self, revision_id):
468
"""Given a revision id, return its dotted revno."""
469
if revision_id in (None, _mod_revision.NULL_REVISION):
471
revision_id = osutils.safe_revision_id(revision_id)
473
revision_id_to_revno = self.get_revision_id_to_revno_map()
474
if revision_id not in revision_id_to_revno:
475
raise errors.NoSuchRevision(self, revision_id)
476
return revision_id_to_revno[revision_id]
478
def revision_id_to_revno(self, revision_id):
479
"""Given a revision id, return its revno"""
480
if revision_id is None:
482
revision_id = osutils.safe_revision_id(revision_id)
483
history = self.revision_history()
485
return history.index(revision_id) + 1
487
raise errors.NoSuchRevision(self, revision_id)
489
def get_rev_id(self, revno, history=None):
490
"""Find the revision id of the specified revno."""
494
history = self.revision_history()
495
if revno <= 0 or revno > len(history):
496
raise errors.NoSuchRevision(self, revno)
497
return history[revno - 1]
499
def pull(self, source, overwrite=False, stop_revision=None):
500
"""Mirror source into this branch.
502
This branch is considered to be 'local', having low latency.
504
:returns: PullResult instance
506
raise NotImplementedError(self.pull)
508
def push(self, target, overwrite=False, stop_revision=None):
509
"""Mirror this branch into target.
511
This branch is considered to be 'local', having low latency.
513
raise NotImplementedError(self.push)
515
def basis_tree(self):
516
"""Return `Tree` object for last revision."""
517
return self.repository.revision_tree(self.last_revision())
519
def rename_one(self, from_rel, to_rel):
522
This can change the directory or the filename or both.
524
raise NotImplementedError(self.rename_one)
526
def move(self, from_paths, to_name):
529
to_name must exist as a versioned directory.
531
If to_name exists and is a directory, the files are moved into
532
it, keeping their old names. If it is a directory,
534
Note that to_name is only the last component of the new name;
535
this doesn't change the directory.
537
This returns a list of (from_path, to_path) pairs for each
540
raise NotImplementedError(self.move)
542
def get_parent(self):
543
"""Return the parent location of the branch.
545
This is the default location for push/pull/missing. The usual
546
pattern is that the user can override it by specifying a
549
raise NotImplementedError(self.get_parent)
551
def _set_config_location(self, name, url, config=None,
552
make_relative=False):
554
config = self.get_config()
558
url = urlutils.relative_url(self.base, url)
559
config.set_user_option(name, url)
561
def _get_config_location(self, name, config=None):
563
config = self.get_config()
564
location = config.get_user_option(name)
569
def get_submit_branch(self):
570
"""Return the submit location of the branch.
572
This is the default location for bundle. The usual
573
pattern is that the user can override it by specifying a
576
return self.get_config().get_user_option('submit_branch')
578
def set_submit_branch(self, location):
579
"""Return the submit location of the branch.
581
This is the default location for bundle. The usual
582
pattern is that the user can override it by specifying a
585
self.get_config().set_user_option('submit_branch', location)
587
def get_public_branch(self):
588
"""Return the public location of the branch.
590
This is is used by merge directives.
592
return self._get_config_location('public_branch')
594
def set_public_branch(self, location):
595
"""Return the submit location of the branch.
597
This is the default location for bundle. The usual
598
pattern is that the user can override it by specifying a
601
self._set_config_location('public_branch', location)
603
def get_push_location(self):
604
"""Return the None or the location to push this branch to."""
605
raise NotImplementedError(self.get_push_location)
607
def set_push_location(self, location):
608
"""Set a new push location for this branch."""
609
raise NotImplementedError(self.set_push_location)
611
def set_parent(self, url):
612
raise NotImplementedError(self.set_parent)
616
"""Synchronise this branch with the master branch if any.
618
:return: None or the last_revision pivoted out during the update.
622
def check_revno(self, revno):
624
Check whether a revno corresponds to any revision.
625
Zero (the NULL revision) is considered valid.
628
self.check_real_revno(revno)
630
def check_real_revno(self, revno):
632
Check whether a revno corresponds to a real revision.
633
Zero (the NULL revision) is considered invalid
635
if revno < 1 or revno > self.revno():
636
raise InvalidRevisionNumber(revno)
639
def clone(self, to_bzrdir, revision_id=None):
640
"""Clone this branch into to_bzrdir preserving all semantic values.
642
revision_id: if not None, the revision history in the new branch will
643
be truncated to end with revision_id.
645
result = self._format.initialize(to_bzrdir)
646
self.copy_content_into(result, revision_id=revision_id)
650
def sprout(self, to_bzrdir, revision_id=None):
651
"""Create a new line of development from the branch, into to_bzrdir.
653
revision_id: if not None, the revision history in the new branch will
654
be truncated to end with revision_id.
656
result = self._format.initialize(to_bzrdir)
657
self.copy_content_into(result, revision_id=revision_id)
658
result.set_parent(self.bzrdir.root_transport.base)
661
def _synchronize_history(self, destination, revision_id):
662
"""Synchronize last revision and revision history between branches.
664
This version is most efficient when the destination is also a
665
BzrBranch5, but works for BzrBranch6 as long as the revision
666
history is the true lefthand parent history, and all of the revisions
667
are in the destination's repository. If not, set_revision_history
670
:param destination: The branch to copy the history into
671
:param revision_id: The revision-id to truncate history at. May
672
be None to copy complete history.
674
new_history = self.revision_history()
675
if revision_id is not None:
676
revision_id = osutils.safe_revision_id(revision_id)
678
new_history = new_history[:new_history.index(revision_id) + 1]
680
rev = self.repository.get_revision(revision_id)
681
new_history = rev.get_history(self.repository)[1:]
682
destination.set_revision_history(new_history)
685
def copy_content_into(self, destination, revision_id=None):
686
"""Copy the content of self into destination.
688
revision_id: if not None, the revision history in the new branch will
689
be truncated to end with revision_id.
691
self._synchronize_history(destination, revision_id)
693
parent = self.get_parent()
694
except errors.InaccessibleParent, e:
695
mutter('parent was not accessible to copy: %s', e)
698
destination.set_parent(parent)
699
self.tags.merge_to(destination.tags)
703
"""Check consistency of the branch.
705
In particular this checks that revisions given in the revision-history
706
do actually match up in the revision graph, and that they're all
707
present in the repository.
709
Callers will typically also want to check the repository.
711
:return: A BranchCheckResult.
713
mainline_parent_id = None
714
for revision_id in self.revision_history():
716
revision = self.repository.get_revision(revision_id)
717
except errors.NoSuchRevision, e:
718
raise errors.BzrCheckError("mainline revision {%s} not in repository"
720
# In general the first entry on the revision history has no parents.
721
# But it's not illegal for it to have parents listed; this can happen
722
# in imports from Arch when the parents weren't reachable.
723
if mainline_parent_id is not None:
724
if mainline_parent_id not in revision.parent_ids:
725
raise errors.BzrCheckError("previous revision {%s} not listed among "
727
% (mainline_parent_id, revision_id))
728
mainline_parent_id = revision_id
729
return BranchCheckResult(self)
731
def _get_checkout_format(self):
732
"""Return the most suitable metadir for a checkout of this branch.
733
Weaves are used if this branch's repostory uses weaves.
735
if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
736
from bzrlib.repofmt import weaverepo
737
format = bzrdir.BzrDirMetaFormat1()
738
format.repository_format = weaverepo.RepositoryFormat7()
740
format = self.repository.bzrdir.checkout_metadir()
741
format.set_branch_format(self._format)
744
def create_checkout(self, to_location, revision_id=None,
746
"""Create a checkout of a branch.
748
:param to_location: The url to produce the checkout at
749
:param revision_id: The revision to check out
750
:param lightweight: If True, produce a lightweight checkout, otherwise,
751
produce a bound branch (heavyweight checkout)
752
:return: The tree of the created checkout
754
t = transport.get_transport(to_location)
757
except errors.FileExists:
760
format = self._get_checkout_format()
761
checkout = format.initialize_on_transport(t)
762
BranchReferenceFormat().initialize(checkout, self)
764
format = self._get_checkout_format()
765
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
766
to_location, force_new_tree=False, format=format)
767
checkout = checkout_branch.bzrdir
768
checkout_branch.bind(self)
769
# pull up to the specified revision_id to set the initial
770
# branch tip correctly, and seed it with history.
771
checkout_branch.pull(self, stop_revision=revision_id)
772
tree = checkout.create_workingtree(revision_id)
773
basis_tree = tree.basis_tree()
774
basis_tree.lock_read()
776
for path, file_id in basis_tree.iter_references():
777
reference_parent = self.reference_parent(file_id, path)
778
reference_parent.create_checkout(tree.abspath(path),
779
basis_tree.get_reference_revision(file_id, path),
785
def reference_parent(self, file_id, path):
786
"""Return the parent branch for a tree-reference file_id
787
:param file_id: The file_id of the tree reference
788
:param path: The path of the file_id in the tree
789
:return: A branch associated with the file_id
791
# FIXME should provide multiple branches, based on config
792
return Branch.open(self.bzrdir.root_transport.clone(path).base)
794
def supports_tags(self):
795
return self._format.supports_tags()
798
class BranchFormat(object):
799
"""An encapsulation of the initialization and open routines for a format.
801
Formats provide three things:
802
* An initialization routine,
806
Formats are placed in an dict by their format string for reference
807
during branch opening. Its not required that these be instances, they
808
can be classes themselves with class methods - it simply depends on
809
whether state is needed for a given format or not.
811
Once a format is deprecated, just deprecate the initialize and open
812
methods on the format class. Do not deprecate the object, as the
813
object will be created every time regardless.
816
_default_format = None
817
"""The default format used for new branches."""
820
"""The known formats."""
823
def find_format(klass, a_bzrdir):
824
"""Return the format for the branch object in a_bzrdir."""
826
transport = a_bzrdir.get_branch_transport(None)
827
format_string = transport.get("format").read()
828
return klass._formats[format_string]
830
raise NotBranchError(path=transport.base)
832
raise errors.UnknownFormatError(format=format_string)
835
def get_default_format(klass):
836
"""Return the current default format."""
837
return klass._default_format
839
def get_format_string(self):
840
"""Return the ASCII format string that identifies this format."""
841
raise NotImplementedError(self.get_format_string)
843
def get_format_description(self):
844
"""Return the short format description for this format."""
845
raise NotImplementedError(self.get_format_description)
847
def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
849
"""Initialize a branch in a bzrdir, with specified files
851
:param a_bzrdir: The bzrdir to initialize the branch in
852
:param utf8_files: The files to create as a list of
853
(filename, content) tuples
854
:param set_format: If True, set the format with
855
self.get_format_string. (BzrBranch4 has its format set
857
:return: a branch in this format
859
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
860
branch_transport = a_bzrdir.get_branch_transport(self)
862
'metadir': ('lock', lockdir.LockDir),
863
'branch4': ('branch-lock', lockable_files.TransportLock),
865
lock_name, lock_class = lock_map[lock_type]
866
control_files = lockable_files.LockableFiles(branch_transport,
867
lock_name, lock_class)
868
control_files.create_lock()
869
control_files.lock_write()
871
control_files.put_utf8('format', self.get_format_string())
873
for file, content in utf8_files:
874
control_files.put_utf8(file, content)
876
control_files.unlock()
877
return self.open(a_bzrdir, _found=True)
879
def initialize(self, a_bzrdir):
880
"""Create a branch of this format in a_bzrdir."""
881
raise NotImplementedError(self.initialize)
883
def is_supported(self):
884
"""Is this format supported?
886
Supported formats can be initialized and opened.
887
Unsupported formats may not support initialization or committing or
888
some other features depending on the reason for not being supported.
892
def open(self, a_bzrdir, _found=False):
893
"""Return the branch object for a_bzrdir
895
_found is a private parameter, do not use it. It is used to indicate
896
if format probing has already be done.
898
raise NotImplementedError(self.open)
901
def register_format(klass, format):
902
klass._formats[format.get_format_string()] = format
905
def set_default_format(klass, format):
906
klass._default_format = format
909
def unregister_format(klass, format):
910
assert klass._formats[format.get_format_string()] is format
911
del klass._formats[format.get_format_string()]
914
return self.get_format_string().rstrip()
916
def supports_tags(self):
917
"""True if this format supports tags stored in the branch"""
918
return False # by default
920
# XXX: Probably doesn't really belong here -- mbp 20070212
921
def _initialize_control_files(self, a_bzrdir, utf8_files, lock_filename,
923
branch_transport = a_bzrdir.get_branch_transport(self)
924
control_files = lockable_files.LockableFiles(branch_transport,
925
lock_filename, lock_class)
926
control_files.create_lock()
927
control_files.lock_write()
929
for filename, content in utf8_files:
930
control_files.put_utf8(filename, content)
932
control_files.unlock()
935
class BranchHooks(Hooks):
936
"""A dictionary mapping hook name to a list of callables for branch hooks.
938
e.g. ['set_rh'] Is the list of items to be called when the
939
set_revision_history function is invoked.
943
"""Create the default hooks.
945
These are all empty initially, because by default nothing should get
949
# Introduced in 0.15:
950
# invoked whenever the revision history has been set
951
# with set_revision_history. The api signature is
952
# (branch, revision_history), and the branch will
955
# invoked after a push operation completes.
956
# the api signature is
958
# containing the members
959
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
960
# where local is the local branch or None, master is the target
961
# master branch, and the rest should be self explanatory. The source
962
# is read locked and the target branches write locked. Source will
963
# be the local low-latency branch.
964
self['post_push'] = []
965
# invoked after a pull operation completes.
966
# the api signature is
968
# containing the members
969
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
970
# where local is the local branch or None, master is the target
971
# master branch, and the rest should be self explanatory. The source
972
# is read locked and the target branches write locked. The local
973
# branch is the low-latency branch.
974
self['post_pull'] = []
975
# invoked after a commit operation completes.
976
# the api signature is
977
# (local, master, old_revno, old_revid, new_revno, new_revid)
978
# old_revid is NULL_REVISION for the first commit to a branch.
979
self['post_commit'] = []
980
# invoked after a uncommit operation completes.
981
# the api signature is
982
# (local, master, old_revno, old_revid, new_revno, new_revid) where
983
# local is the local branch or None, master is the target branch,
984
# and an empty branch recieves new_revno of 0, new_revid of None.
985
self['post_uncommit'] = []
988
# install the default hooks into the Branch class.
989
Branch.hooks = BranchHooks()
992
class BzrBranchFormat4(BranchFormat):
993
"""Bzr branch format 4.
996
- a revision-history file.
997
- a branch-lock lock file [ to be shared with the bzrdir ]
1000
def get_format_description(self):
1001
"""See BranchFormat.get_format_description()."""
1002
return "Branch format 4"
1004
def initialize(self, a_bzrdir):
1005
"""Create a branch of this format in a_bzrdir."""
1006
utf8_files = [('revision-history', ''),
1007
('branch-name', ''),
1009
return self._initialize_helper(a_bzrdir, utf8_files,
1010
lock_type='branch4', set_format=False)
1013
super(BzrBranchFormat4, self).__init__()
1014
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1016
def open(self, a_bzrdir, _found=False):
1017
"""Return the branch object for a_bzrdir
1019
_found is a private parameter, do not use it. It is used to indicate
1020
if format probing has already be done.
1023
# we are being called directly and must probe.
1024
raise NotImplementedError
1025
return BzrBranch(_format=self,
1026
_control_files=a_bzrdir._control_files,
1028
_repository=a_bzrdir.open_repository())
1031
return "Bazaar-NG branch format 4"
1034
class BzrBranchFormat5(BranchFormat):
1035
"""Bzr branch format 5.
1038
- a revision-history file.
1040
- a lock dir guarding the branch itself
1041
- all of this stored in a branch/ subdirectory
1042
- works with shared repositories.
1044
This format is new in bzr 0.8.
1047
def get_format_string(self):
1048
"""See BranchFormat.get_format_string()."""
1049
return "Bazaar-NG branch format 5\n"
1051
def get_format_description(self):
1052
"""See BranchFormat.get_format_description()."""
1053
return "Branch format 5"
1055
def initialize(self, a_bzrdir):
1056
"""Create a branch of this format in a_bzrdir."""
1057
utf8_files = [('revision-history', ''),
1058
('branch-name', ''),
1060
return self._initialize_helper(a_bzrdir, utf8_files)
1063
super(BzrBranchFormat5, self).__init__()
1064
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1066
def open(self, a_bzrdir, _found=False):
1067
"""Return the branch object for a_bzrdir
1069
_found is a private parameter, do not use it. It is used to indicate
1070
if format probing has already be done.
1073
format = BranchFormat.find_format(a_bzrdir)
1074
assert format.__class__ == self.__class__
1075
transport = a_bzrdir.get_branch_transport(None)
1076
control_files = lockable_files.LockableFiles(transport, 'lock',
1078
return BzrBranch5(_format=self,
1079
_control_files=control_files,
1081
_repository=a_bzrdir.find_repository())
1084
class BzrBranchFormat6(BzrBranchFormat5):
1085
"""Branch format with last-revision
1087
Unlike previous formats, this has no explicit revision history. Instead,
1088
this just stores the last-revision, and the left-hand history leading
1089
up to there is the history.
1091
This format was introduced in bzr 0.15
1094
def get_format_string(self):
1095
"""See BranchFormat.get_format_string()."""
1096
return "Bazaar Branch Format 6 (bzr 0.15)\n"
1098
def get_format_description(self):
1099
"""See BranchFormat.get_format_description()."""
1100
return "Branch format 6"
1102
def initialize(self, a_bzrdir):
1103
"""Create a branch of this format in a_bzrdir."""
1104
utf8_files = [('last-revision', '0 null:\n'),
1105
('branch-name', ''),
1106
('branch.conf', ''),
1109
return self._initialize_helper(a_bzrdir, utf8_files)
1111
def open(self, a_bzrdir, _found=False):
1112
"""Return the branch object for a_bzrdir
1114
_found is a private parameter, do not use it. It is used to indicate
1115
if format probing has already be done.
1118
format = BranchFormat.find_format(a_bzrdir)
1119
assert format.__class__ == self.__class__
1120
transport = a_bzrdir.get_branch_transport(None)
1121
control_files = lockable_files.LockableFiles(transport, 'lock',
1123
return BzrBranch6(_format=self,
1124
_control_files=control_files,
1126
_repository=a_bzrdir.find_repository())
1128
def supports_tags(self):
1132
class BranchReferenceFormat(BranchFormat):
1133
"""Bzr branch reference format.
1135
Branch references are used in implementing checkouts, they
1136
act as an alias to the real branch which is at some other url.
1143
def get_format_string(self):
1144
"""See BranchFormat.get_format_string()."""
1145
return "Bazaar-NG Branch Reference Format 1\n"
1147
def get_format_description(self):
1148
"""See BranchFormat.get_format_description()."""
1149
return "Checkout reference format 1"
1151
def initialize(self, a_bzrdir, target_branch=None):
1152
"""Create a branch of this format in a_bzrdir."""
1153
if target_branch is None:
1154
# this format does not implement branch itself, thus the implicit
1155
# creation contract must see it as uninitializable
1156
raise errors.UninitializableFormat(self)
1157
mutter('creating branch reference in %s', a_bzrdir.transport.base)
1158
branch_transport = a_bzrdir.get_branch_transport(self)
1159
branch_transport.put_bytes('location',
1160
target_branch.bzrdir.root_transport.base)
1161
branch_transport.put_bytes('format', self.get_format_string())
1162
return self.open(a_bzrdir, _found=True)
1165
super(BranchReferenceFormat, self).__init__()
1166
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1168
def _make_reference_clone_function(format, a_branch):
1169
"""Create a clone() routine for a branch dynamically."""
1170
def clone(to_bzrdir, revision_id=None):
1171
"""See Branch.clone()."""
1172
return format.initialize(to_bzrdir, a_branch)
1173
# cannot obey revision_id limits when cloning a reference ...
1174
# FIXME RBC 20060210 either nuke revision_id for clone, or
1175
# emit some sort of warning/error to the caller ?!
1178
def open(self, a_bzrdir, _found=False):
1179
"""Return the branch that the branch reference in a_bzrdir points at.
1181
_found is a private parameter, do not use it. It is used to indicate
1182
if format probing has already be done.
1185
format = BranchFormat.find_format(a_bzrdir)
1186
assert format.__class__ == self.__class__
1187
transport = a_bzrdir.get_branch_transport(None)
1188
real_bzrdir = bzrdir.BzrDir.open(transport.get('location').read())
1189
result = real_bzrdir.open_branch()
1190
# this changes the behaviour of result.clone to create a new reference
1191
# rather than a copy of the content of the branch.
1192
# I did not use a proxy object because that needs much more extensive
1193
# testing, and we are only changing one behaviour at the moment.
1194
# If we decide to alter more behaviours - i.e. the implicit nickname
1195
# then this should be refactored to introduce a tested proxy branch
1196
# and a subclass of that for use in overriding clone() and ....
1198
result.clone = self._make_reference_clone_function(result)
1202
# formats which have no format string are not discoverable
1203
# and not independently creatable, so are not registered.
1204
__default_format = BzrBranchFormat5()
1205
BranchFormat.register_format(__default_format)
1206
BranchFormat.register_format(BranchReferenceFormat())
1207
BranchFormat.register_format(BzrBranchFormat6())
1208
BranchFormat.set_default_format(__default_format)
1209
_legacy_formats = [BzrBranchFormat4(),
1212
class BzrBranch(Branch):
1213
"""A branch stored in the actual filesystem.
1215
Note that it's "local" in the context of the filesystem; it doesn't
1216
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1217
it's writable, and can be accessed via the normal filesystem API.
1220
def __init__(self, _format=None,
1221
_control_files=None, a_bzrdir=None, _repository=None):
1222
"""Create new branch object at a particular location."""
1223
Branch.__init__(self)
1224
if a_bzrdir is None:
1225
raise ValueError('a_bzrdir must be supplied')
1227
self.bzrdir = a_bzrdir
1228
# self._transport used to point to the directory containing the
1229
# control directory, but was not used - now it's just the transport
1230
# for the branch control files. mbp 20070212
1231
self._base = self.bzrdir.transport.clone('..').base
1232
self._format = _format
1233
if _control_files is None:
1234
raise ValueError('BzrBranch _control_files is None')
1235
self.control_files = _control_files
1236
self._transport = _control_files._transport
1237
self.repository = _repository
1240
return '%s(%r)' % (self.__class__.__name__, self.base)
1244
def _get_base(self):
1245
"""Returns the directory containing the control directory."""
1248
base = property(_get_base, doc="The URL for the root of this branch.")
1250
def abspath(self, name):
1251
"""See Branch.abspath."""
1252
return self.control_files._transport.abspath(name)
1255
@deprecated_method(zero_sixteen)
1257
def get_root_id(self):
1258
"""See Branch.get_root_id."""
1259
tree = self.repository.revision_tree(self.last_revision())
1260
return tree.inventory.root.file_id
1262
def is_locked(self):
1263
return self.control_files.is_locked()
1265
def lock_write(self, token=None):
1266
repo_token = self.repository.lock_write()
1268
token = self.control_files.lock_write(token=token)
1270
self.repository.unlock()
1274
def lock_read(self):
1275
self.repository.lock_read()
1277
self.control_files.lock_read()
1279
self.repository.unlock()
1283
# TODO: test for failed two phase locks. This is known broken.
1285
self.control_files.unlock()
1287
self.repository.unlock()
1288
if not self.control_files.is_locked():
1289
# we just released the lock
1290
self._clear_cached_state()
1292
def peek_lock_mode(self):
1293
if self.control_files._lock_count == 0:
1296
return self.control_files._lock_mode
1298
def get_physical_lock_status(self):
1299
return self.control_files.get_physical_lock_status()
1302
def print_file(self, file, revision_id):
1303
"""See Branch.print_file."""
1304
return self.repository.print_file(file, revision_id)
1307
def append_revision(self, *revision_ids):
1308
"""See Branch.append_revision."""
1309
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1310
for revision_id in revision_ids:
1311
_mod_revision.check_not_reserved_id(revision_id)
1312
mutter("add {%s} to revision-history" % revision_id)
1313
rev_history = self.revision_history()
1314
rev_history.extend(revision_ids)
1315
self.set_revision_history(rev_history)
1317
def _write_revision_history(self, history):
1318
"""Factored out of set_revision_history.
1320
This performs the actual writing to disk.
1321
It is intended to be called by BzrBranch5.set_revision_history."""
1322
self.control_files.put_bytes(
1323
'revision-history', '\n'.join(history))
1326
def set_revision_history(self, rev_history):
1327
"""See Branch.set_revision_history."""
1328
rev_history = [osutils.safe_revision_id(r) for r in rev_history]
1329
self._clear_cached_state()
1330
self._write_revision_history(rev_history)
1331
self._cache_revision_history(rev_history)
1332
for hook in Branch.hooks['set_rh']:
1333
hook(self, rev_history)
1336
def set_last_revision_info(self, revno, revision_id):
1337
revision_id = osutils.safe_revision_id(revision_id)
1338
history = self._lefthand_history(revision_id)
1339
assert len(history) == revno, '%d != %d' % (len(history), revno)
1340
self.set_revision_history(history)
1342
def _gen_revision_history(self):
1343
history = self.control_files.get('revision-history').read().split('\n')
1344
if history[-1:] == ['']:
1345
# There shouldn't be a trailing newline, but just in case.
1350
def get_revision_id_to_revno_map(self):
1351
"""Return the revision_id => dotted revno map.
1353
This will be regenerated on demand, but will be cached.
1355
:return: A dictionary mapping revision_id => dotted revno.
1356
This dictionary should not be modified by the caller.
1358
if self._revision_id_to_revno_cache is not None:
1359
mapping = self._revision_id_to_revno_cache
1361
mapping = self._gen_revno_map()
1362
self._cache_revision_id_to_revno(mapping)
1363
# TODO: jam 20070417 Since this is being cached, should we be returning
1365
# I would rather not, and instead just declare that users should not
1366
# modify the return value.
1369
def _gen_revno_map(self):
1370
"""Generate a mapping from revision ids to dotted revnos.
1372
:return: A dict mapping revision_ids => dotted revnos
1374
last_revision = self.last_revision()
1375
revision_graph = self.repository.get_revision_graph(last_revision)
1376
merge_sorted_revisions = tsort.merge_sort(
1380
generate_revno=True)
1381
revision_id_to_revno = dict((rev_id, revno)
1382
for seq_num, rev_id, depth, revno, end_of_merge
1383
in merge_sorted_revisions)
1384
return revision_id_to_revno
1386
def _lefthand_history(self, revision_id, last_rev=None,
1388
# stop_revision must be a descendant of last_revision
1389
stop_graph = self.repository.get_revision_graph(revision_id)
1390
if last_rev is not None and last_rev not in stop_graph:
1391
# our previous tip is not merged into stop_revision
1392
raise errors.DivergedBranches(self, other_branch)
1393
# make a new revision history from the graph
1394
current_rev_id = revision_id
1396
while current_rev_id not in (None, _mod_revision.NULL_REVISION):
1397
new_history.append(current_rev_id)
1398
current_rev_id_parents = stop_graph[current_rev_id]
1400
current_rev_id = current_rev_id_parents[0]
1402
current_rev_id = None
1403
new_history.reverse()
1407
def generate_revision_history(self, revision_id, last_rev=None,
1409
"""Create a new revision history that will finish with revision_id.
1411
:param revision_id: the new tip to use.
1412
:param last_rev: The previous last_revision. If not None, then this
1413
must be a ancestory of revision_id, or DivergedBranches is raised.
1414
:param other_branch: The other branch that DivergedBranches should
1415
raise with respect to.
1417
revision_id = osutils.safe_revision_id(revision_id)
1418
self.set_revision_history(self._lefthand_history(revision_id,
1419
last_rev, other_branch))
1422
def update_revisions(self, other, stop_revision=None):
1423
"""See Branch.update_revisions."""
1426
if stop_revision is None:
1427
stop_revision = other.last_revision()
1428
if stop_revision is None:
1429
# if there are no commits, we're done.
1432
stop_revision = osutils.safe_revision_id(stop_revision)
1433
# whats the current last revision, before we fetch [and change it
1435
last_rev = self.last_revision()
1436
# we fetch here regardless of whether we need to so that we pickup
1438
self.fetch(other, stop_revision)
1439
my_ancestry = self.repository.get_ancestry(last_rev)
1440
if stop_revision in my_ancestry:
1441
# last_revision is a descendant of stop_revision
1443
self.generate_revision_history(stop_revision, last_rev=last_rev,
1448
def basis_tree(self):
1449
"""See Branch.basis_tree."""
1450
return self.repository.revision_tree(self.last_revision())
1452
@deprecated_method(zero_eight)
1453
def working_tree(self):
1454
"""Create a Working tree object for this branch."""
1456
from bzrlib.transport.local import LocalTransport
1457
if (self.base.find('://') != -1 or
1458
not isinstance(self._transport, LocalTransport)):
1459
raise NoWorkingTree(self.base)
1460
return self.bzrdir.open_workingtree()
1463
def pull(self, source, overwrite=False, stop_revision=None,
1464
_hook_master=None, _run_hooks=True):
1467
:param _hook_master: Private parameter - set the branch to
1468
be supplied as the master to push hooks.
1469
:param _run_hooks: Private parameter - allow disabling of
1470
hooks, used when pushing to a master branch.
1472
result = PullResult()
1473
result.source_branch = source
1474
result.target_branch = self
1477
result.old_revno, result.old_revid = self.last_revision_info()
1479
self.update_revisions(source, stop_revision)
1480
except DivergedBranches:
1484
if stop_revision is None:
1485
stop_revision = source.last_revision()
1486
self.generate_revision_history(stop_revision)
1487
result.tag_conflicts = source.tags.merge_to(self.tags)
1488
result.new_revno, result.new_revid = self.last_revision_info()
1490
result.master_branch = _hook_master
1491
result.local_branch = self
1493
result.master_branch = self
1494
result.local_branch = None
1496
for hook in Branch.hooks['post_pull']:
1502
def _get_parent_location(self):
1503
_locs = ['parent', 'pull', 'x-pull']
1506
return self.control_files.get(l).read().strip('\n')
1512
def push(self, target, overwrite=False, stop_revision=None,
1513
_hook_master=None, _run_hooks=True):
1516
:param _hook_master: Private parameter - set the branch to
1517
be supplied as the master to push hooks.
1518
:param _run_hooks: Private parameter - allow disabling of
1519
hooks, used when pushing to a master branch.
1521
result = PushResult()
1522
result.source_branch = self
1523
result.target_branch = target
1526
result.old_revno, result.old_revid = target.last_revision_info()
1528
target.update_revisions(self, stop_revision)
1529
except DivergedBranches:
1533
target.set_revision_history(self.revision_history())
1534
result.tag_conflicts = self.tags.merge_to(target.tags)
1535
result.new_revno, result.new_revid = target.last_revision_info()
1537
result.master_branch = _hook_master
1538
result.local_branch = target
1540
result.master_branch = target
1541
result.local_branch = None
1543
for hook in Branch.hooks['post_push']:
1549
def get_parent(self):
1550
"""See Branch.get_parent."""
1552
assert self.base[-1] == '/'
1553
parent = self._get_parent_location()
1556
# This is an old-format absolute path to a local branch
1557
# turn it into a url
1558
if parent.startswith('/'):
1559
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1561
return urlutils.join(self.base[:-1], parent)
1562
except errors.InvalidURLJoin, e:
1563
raise errors.InaccessibleParent(parent, self.base)
1565
def get_push_location(self):
1566
"""See Branch.get_push_location."""
1567
push_loc = self.get_config().get_user_option('push_location')
1570
def set_push_location(self, location):
1571
"""See Branch.set_push_location."""
1572
self.get_config().set_user_option(
1573
'push_location', location,
1574
store=_mod_config.STORE_LOCATION_NORECURSE)
1577
def set_parent(self, url):
1578
"""See Branch.set_parent."""
1579
# TODO: Maybe delete old location files?
1580
# URLs should never be unicode, even on the local fs,
1581
# FIXUP this and get_parent in a future branch format bump:
1582
# read and rewrite the file, and have the new format code read
1583
# using .get not .get_utf8. RBC 20060125
1585
if isinstance(url, unicode):
1587
url = url.encode('ascii')
1588
except UnicodeEncodeError:
1589
raise errors.InvalidURL(url,
1590
"Urls must be 7-bit ascii, "
1591
"use bzrlib.urlutils.escape")
1592
url = urlutils.relative_url(self.base, url)
1593
self._set_parent_location(url)
1595
def _set_parent_location(self, url):
1597
self.control_files._transport.delete('parent')
1599
assert isinstance(url, str)
1600
self.control_files.put_bytes('parent', url + '\n')
1602
@deprecated_function(zero_nine)
1603
def tree_config(self):
1604
"""DEPRECATED; call get_config instead.
1605
TreeConfig has become part of BranchConfig."""
1606
return TreeConfig(self)
1609
class BzrBranch5(BzrBranch):
1610
"""A format 5 branch. This supports new features over plan branches.
1612
It has support for a master_branch which is the data for bound branches.
1620
super(BzrBranch5, self).__init__(_format=_format,
1621
_control_files=_control_files,
1623
_repository=_repository)
1626
def pull(self, source, overwrite=False, stop_revision=None,
1628
"""Extends branch.pull to be bound branch aware.
1630
:param _run_hooks: Private parameter used to force hook running
1631
off during bound branch double-pushing.
1633
bound_location = self.get_bound_location()
1634
master_branch = None
1635
if bound_location and source.base != bound_location:
1636
# not pulling from master, so we need to update master.
1637
master_branch = self.get_master_branch()
1638
master_branch.lock_write()
1641
# pull from source into master.
1642
master_branch.pull(source, overwrite, stop_revision,
1644
return super(BzrBranch5, self).pull(source, overwrite,
1645
stop_revision, _hook_master=master_branch,
1646
_run_hooks=_run_hooks)
1649
master_branch.unlock()
1652
def push(self, target, overwrite=False, stop_revision=None):
1653
"""Updates branch.push to be bound branch aware."""
1654
bound_location = target.get_bound_location()
1655
master_branch = None
1656
if bound_location and target.base != bound_location:
1657
# not pushing to master, so we need to update master.
1658
master_branch = target.get_master_branch()
1659
master_branch.lock_write()
1662
# push into the master from this branch.
1663
super(BzrBranch5, self).push(master_branch, overwrite,
1664
stop_revision, _run_hooks=False)
1665
# and push into the target branch from this. Note that we push from
1666
# this branch again, because its considered the highest bandwidth
1668
return super(BzrBranch5, self).push(target, overwrite,
1669
stop_revision, _hook_master=master_branch)
1672
master_branch.unlock()
1674
def get_bound_location(self):
1676
return self.control_files.get_utf8('bound').read()[:-1]
1677
except errors.NoSuchFile:
1681
def get_master_branch(self):
1682
"""Return the branch we are bound to.
1684
:return: Either a Branch, or None
1686
This could memoise the branch, but if thats done
1687
it must be revalidated on each new lock.
1688
So for now we just don't memoise it.
1689
# RBC 20060304 review this decision.
1691
bound_loc = self.get_bound_location()
1695
return Branch.open(bound_loc)
1696
except (errors.NotBranchError, errors.ConnectionError), e:
1697
raise errors.BoundBranchConnectionFailure(
1701
def set_bound_location(self, location):
1702
"""Set the target where this branch is bound to.
1704
:param location: URL to the target branch
1707
self.control_files.put_utf8('bound', location+'\n')
1710
self.control_files._transport.delete('bound')
1716
def bind(self, other):
1717
"""Bind this branch to the branch other.
1719
This does not push or pull data between the branches, though it does
1720
check for divergence to raise an error when the branches are not
1721
either the same, or one a prefix of the other. That behaviour may not
1722
be useful, so that check may be removed in future.
1724
:param other: The branch to bind to
1727
# TODO: jam 20051230 Consider checking if the target is bound
1728
# It is debatable whether you should be able to bind to
1729
# a branch which is itself bound.
1730
# Committing is obviously forbidden,
1731
# but binding itself may not be.
1732
# Since we *have* to check at commit time, we don't
1733
# *need* to check here
1735
# we want to raise diverged if:
1736
# last_rev is not in the other_last_rev history, AND
1737
# other_last_rev is not in our history, and do it without pulling
1739
last_rev = self.last_revision()
1740
if last_rev is not None:
1743
other_last_rev = other.last_revision()
1744
if other_last_rev is not None:
1745
# neither branch is new, we have to do some work to
1746
# ascertain diversion.
1747
remote_graph = other.repository.get_revision_graph(
1749
local_graph = self.repository.get_revision_graph(last_rev)
1750
if (last_rev not in remote_graph and
1751
other_last_rev not in local_graph):
1752
raise errors.DivergedBranches(self, other)
1755
self.set_bound_location(other.base)
1759
"""If bound, unbind"""
1760
return self.set_bound_location(None)
1764
"""Synchronise this branch with the master branch if any.
1766
:return: None or the last_revision that was pivoted out during the
1769
master = self.get_master_branch()
1770
if master is not None:
1771
old_tip = self.last_revision()
1772
self.pull(master, overwrite=True)
1773
if old_tip in self.repository.get_ancestry(self.last_revision()):
1779
class BzrBranchExperimental(BzrBranch5):
1780
"""Bzr experimental branch format
1783
- a revision-history file.
1785
- a lock dir guarding the branch itself
1786
- all of this stored in a branch/ subdirectory
1787
- works with shared repositories.
1788
- a tag dictionary in the branch
1790
This format is new in bzr 0.15, but shouldn't be used for real data,
1793
This class acts as it's own BranchFormat.
1796
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1799
def get_format_string(cls):
1800
"""See BranchFormat.get_format_string()."""
1801
return "Bazaar-NG branch format experimental\n"
1804
def get_format_description(cls):
1805
"""See BranchFormat.get_format_description()."""
1806
return "Experimental branch format"
1809
def _initialize_control_files(cls, a_bzrdir, utf8_files, lock_filename,
1811
branch_transport = a_bzrdir.get_branch_transport(cls)
1812
control_files = lockable_files.LockableFiles(branch_transport,
1813
lock_filename, lock_class)
1814
control_files.create_lock()
1815
control_files.lock_write()
1817
for filename, content in utf8_files:
1818
control_files.put_utf8(filename, content)
1820
control_files.unlock()
1823
def initialize(cls, a_bzrdir):
1824
"""Create a branch of this format in a_bzrdir."""
1825
utf8_files = [('format', cls.get_format_string()),
1826
('revision-history', ''),
1827
('branch-name', ''),
1830
cls._initialize_control_files(a_bzrdir, utf8_files,
1831
'lock', lockdir.LockDir)
1832
return cls.open(a_bzrdir, _found=True)
1835
def open(cls, a_bzrdir, _found=False):
1836
"""Return the branch object for a_bzrdir
1838
_found is a private parameter, do not use it. It is used to indicate
1839
if format probing has already be done.
1842
format = BranchFormat.find_format(a_bzrdir)
1843
assert format.__class__ == cls
1844
transport = a_bzrdir.get_branch_transport(None)
1845
control_files = lockable_files.LockableFiles(transport, 'lock',
1847
return cls(_format=cls,
1848
_control_files=control_files,
1850
_repository=a_bzrdir.find_repository())
1853
def is_supported(cls):
1856
def _make_tags(self):
1857
return BasicTags(self)
1860
def supports_tags(cls):
1864
BranchFormat.register_format(BzrBranchExperimental)
1867
class BzrBranch6(BzrBranch5):
1870
def last_revision_info(self):
1871
revision_string = self.control_files.get('last-revision').read()
1872
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
1873
revision_id = cache_utf8.get_cached_utf8(revision_id)
1875
return revno, revision_id
1877
def last_revision(self):
1878
"""Return last revision id, or None"""
1879
revision_id = self.last_revision_info()[1]
1880
if revision_id == _mod_revision.NULL_REVISION:
1884
def _write_last_revision_info(self, revno, revision_id):
1885
"""Simply write out the revision id, with no checks.
1887
Use set_last_revision_info to perform this safely.
1889
Does not update the revision_history cache.
1890
Intended to be called by set_last_revision_info and
1891
_write_revision_history.
1893
if revision_id is None:
1894
revision_id = 'null:'
1895
out_string = '%d %s\n' % (revno, revision_id)
1896
self.control_files.put_bytes('last-revision', out_string)
1899
def set_last_revision_info(self, revno, revision_id):
1900
revision_id = osutils.safe_revision_id(revision_id)
1901
if self._get_append_revisions_only():
1902
self._check_history_violation(revision_id)
1903
self._write_last_revision_info(revno, revision_id)
1904
self._clear_cached_state()
1906
def _check_history_violation(self, revision_id):
1907
last_revision = self.last_revision()
1908
if last_revision is None:
1910
if last_revision not in self._lefthand_history(revision_id):
1911
raise errors.AppendRevisionsOnlyViolation(self.base)
1913
def _gen_revision_history(self):
1914
"""Generate the revision history from last revision
1916
history = list(self.repository.iter_reverse_revision_history(
1917
self.last_revision()))
1921
def _write_revision_history(self, history):
1922
"""Factored out of set_revision_history.
1924
This performs the actual writing to disk, with format-specific checks.
1925
It is intended to be called by BzrBranch5.set_revision_history.
1927
if len(history) == 0:
1928
last_revision = 'null:'
1930
if history != self._lefthand_history(history[-1]):
1931
raise errors.NotLefthandHistory(history)
1932
last_revision = history[-1]
1933
if self._get_append_revisions_only():
1934
self._check_history_violation(last_revision)
1935
self._write_last_revision_info(len(history), last_revision)
1938
def append_revision(self, *revision_ids):
1939
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1940
if len(revision_ids) == 0:
1942
prev_revno, prev_revision = self.last_revision_info()
1943
for revision in self.repository.get_revisions(revision_ids):
1944
if prev_revision == _mod_revision.NULL_REVISION:
1945
if revision.parent_ids != []:
1946
raise errors.NotLeftParentDescendant(self, prev_revision,
1947
revision.revision_id)
1949
if revision.parent_ids[0] != prev_revision:
1950
raise errors.NotLeftParentDescendant(self, prev_revision,
1951
revision.revision_id)
1952
prev_revision = revision.revision_id
1953
self.set_last_revision_info(prev_revno + len(revision_ids),
1957
def _set_parent_location(self, url):
1958
"""Set the parent branch"""
1959
self._set_config_location('parent_location', url, make_relative=True)
1962
def _get_parent_location(self):
1963
"""Set the parent branch"""
1964
return self._get_config_location('parent_location')
1966
def set_push_location(self, location):
1967
"""See Branch.set_push_location."""
1968
self._set_config_location('push_location', location)
1970
def set_bound_location(self, location):
1971
"""See Branch.set_push_location."""
1973
config = self.get_config()
1974
if location is None:
1975
if config.get_user_option('bound') != 'True':
1978
config.set_user_option('bound', 'False')
1981
self._set_config_location('bound_location', location,
1983
config.set_user_option('bound', 'True')
1986
def _get_bound_location(self, bound):
1987
"""Return the bound location in the config file.
1989
Return None if the bound parameter does not match"""
1990
config = self.get_config()
1991
config_bound = (config.get_user_option('bound') == 'True')
1992
if config_bound != bound:
1994
return self._get_config_location('bound_location', config=config)
1996
def get_bound_location(self):
1997
"""See Branch.set_push_location."""
1998
return self._get_bound_location(True)
2000
def get_old_bound_location(self):
2001
"""See Branch.get_old_bound_location"""
2002
return self._get_bound_location(False)
2004
def set_append_revisions_only(self, enabled):
2009
self.get_config().set_user_option('append_revisions_only', value)
2011
def _get_append_revisions_only(self):
2012
value = self.get_config().get_user_option('append_revisions_only')
2013
return value == 'True'
2015
def _synchronize_history(self, destination, revision_id):
2016
"""Synchronize last revision and revision history between branches.
2018
This version is most efficient when the destination is also a
2019
BzrBranch6, but works for BzrBranch5, as long as the destination's
2020
repository contains all the lefthand ancestors of the intended
2021
last_revision. If not, set_last_revision_info will fail.
2023
:param destination: The branch to copy the history into
2024
:param revision_id: The revision-id to truncate history at. May
2025
be None to copy complete history.
2027
if revision_id is None:
2028
revno, revision_id = self.last_revision_info()
2030
revno = self.revision_id_to_revno(revision_id)
2031
destination.set_last_revision_info(revno, revision_id)
2033
def _make_tags(self):
2034
return BasicTags(self)
2037
class BranchTestProviderAdapter(object):
2038
"""A tool to generate a suite testing multiple branch formats at once.
2040
This is done by copying the test once for each transport and injecting
2041
the transport_server, transport_readonly_server, and branch_format
2042
classes into each copy. Each copy is also given a new id() to make it
2046
def __init__(self, transport_server, transport_readonly_server, formats):
2047
self._transport_server = transport_server
2048
self._transport_readonly_server = transport_readonly_server
2049
self._formats = formats
2051
def adapt(self, test):
2052
result = TestSuite()
2053
for branch_format, bzrdir_format in self._formats:
2054
new_test = deepcopy(test)
2055
new_test.transport_server = self._transport_server
2056
new_test.transport_readonly_server = self._transport_readonly_server
2057
new_test.bzrdir_format = bzrdir_format
2058
new_test.branch_format = branch_format
2059
def make_new_test_id():
2060
# the format can be either a class or an instance
2061
name = getattr(branch_format, '__name__',
2062
branch_format.__class__.__name__)
2063
new_id = "%s(%s)" % (new_test.id(), name)
2064
return lambda: new_id
2065
new_test.id = make_new_test_id()
2066
result.addTest(new_test)
2070
######################################################################
2071
# results of operations
2074
class _Result(object):
2076
def _show_tag_conficts(self, to_file):
2077
if not getattr(self, 'tag_conflicts', None):
2079
to_file.write('Conflicting tags:\n')
2080
for name, value1, value2 in self.tag_conflicts:
2081
to_file.write(' %s\n' % (name, ))
2084
class PullResult(_Result):
2085
"""Result of a Branch.pull operation.
2087
:ivar old_revno: Revision number before pull.
2088
:ivar new_revno: Revision number after pull.
2089
:ivar old_revid: Tip revision id before pull.
2090
:ivar new_revid: Tip revision id after pull.
2091
:ivar source_branch: Source (local) branch object.
2092
:ivar master_branch: Master branch of the target, or None.
2093
:ivar target_branch: Target/destination branch object.
2097
# DEPRECATED: pull used to return the change in revno
2098
return self.new_revno - self.old_revno
2100
def report(self, to_file):
2101
if self.old_revid == self.new_revid:
2102
to_file.write('No revisions to pull.\n')
2104
to_file.write('Now on revision %d.\n' % self.new_revno)
2105
self._show_tag_conficts(to_file)
2108
class PushResult(_Result):
2109
"""Result of a Branch.push operation.
2111
:ivar old_revno: Revision number before push.
2112
:ivar new_revno: Revision number after push.
2113
:ivar old_revid: Tip revision id before push.
2114
:ivar new_revid: Tip revision id after push.
2115
:ivar source_branch: Source branch object.
2116
:ivar master_branch: Master branch of the target, or None.
2117
:ivar target_branch: Target/destination branch object.
2121
# DEPRECATED: push used to return the change in revno
2122
return self.new_revno - self.old_revno
2124
def report(self, to_file):
2125
"""Write a human-readable description of the result."""
2126
if self.old_revid == self.new_revid:
2127
to_file.write('No new revisions to push.\n')
2129
to_file.write('Pushed up to revision %d.\n' % self.new_revno)
2130
self._show_tag_conficts(to_file)
2133
class BranchCheckResult(object):
2134
"""Results of checking branch consistency.
2139
def __init__(self, branch):
2140
self.branch = branch
2142
def report_results(self, verbose):
2143
"""Report the check results via trace.note.
2145
:param verbose: Requests more detailed display of what was checked,
2148
note('checked branch %s format %s',
2150
self.branch._format)
2153
class Converter5to6(object):
2154
"""Perform an in-place upgrade of format 5 to format 6"""
2156
def convert(self, branch):
2157
# Data for 5 and 6 can peacefully coexist.
2158
format = BzrBranchFormat6()
2159
new_branch = format.open(branch.bzrdir, _found=True)
2161
# Copy source data into target
2162
new_branch.set_last_revision_info(*branch.last_revision_info())
2163
new_branch.set_parent(branch.get_parent())
2164
new_branch.set_bound_location(branch.get_bound_location())
2165
new_branch.set_push_location(branch.get_push_location())
2167
# New branch has no tags by default
2168
new_branch.tags._set_tag_dict({})
2170
# Copying done; now update target format
2171
new_branch.control_files.put_utf8('format',
2172
format.get_format_string())
2174
# Clean up old files
2175
new_branch.control_files._transport.delete('revision-history')
2177
branch.set_parent(None)
2180
branch.set_bound_location(None)