120
128
Basically we keep looking up until we find the control directory or
121
129
run into the root. If there isn't one, raises NotBranchError.
122
If there is one and it is either an unrecognised format or an unsupported
123
format, UnknownFormatError or UnsupportedFormatError are raised.
124
If there is one, it is returned, along with the unused portion of url.
126
control, relpath = bzrdir.BzrDir.open_containing(url)
127
return control.open_branch(), relpath
131
t = get_transport(url)
135
except NotBranchError:
137
new_t = t.clone('..')
138
if new_t.base == t.base:
139
# reached the root, whatever that may be
140
raise NotBranchError('%s is not in a branch' % url)
130
@deprecated_function(zero_eight)
131
144
def initialize(base):
132
"""Create a new working tree and branch, rooted at 'base' (url)
134
NOTE: This will soon be deprecated in favour of creation
137
return bzrdir.BzrDir.create_standalone_workingtree(base).branch
145
"""Create a new branch, rooted at 'base' (url)"""
146
t = get_transport(base)
147
return _Branch(t, init=True)
139
149
def setup_caching(self, cache_root):
140
150
"""Subclasses that care about caching should override this, and set
141
151
up cached stores located under cache_root.
143
# seems to be unused, 2006-01-13 mbp
144
warn('%s is deprecated' % self.setup_caching)
145
153
self.cache_root = cache_root
148
cfg = self.tree_config()
149
return cfg.get_option(u"nickname", default=self.base.split('/')[-2])
151
def _set_nick(self, nick):
152
cfg = self.tree_config()
153
cfg.set_option(nick, "nickname")
154
assert cfg.get_option("nickname") == nick
156
nick = property(_get_nick, _set_nick)
159
raise NotImplementedError('is_locked is abstract')
156
class _Branch(Branch):
157
"""A branch stored in the actual filesystem.
159
Note that it's "local" in the context of the filesystem; it doesn't
160
really matter if it's on an nfs/smb/afs/coda/... share, as long as
161
it's writable, and can be accessed via the normal filesystem API.
167
If _lock_mode is true, a positive count of the number of times the
171
Lock object from bzrlib.lock.
173
# We actually expect this class to be somewhat short-lived; part of its
174
# purpose is to try to isolate what bits of the branch logic are tied to
175
# filesystem access, so that in a later step, we can extricate them to
176
# a separarte ("storage") class.
180
_inventory_weave = None
182
# Map some sort of prefix into a namespace
183
# stuff like "revno:10", "revid:", etc.
184
# This should match a prefix with a function which accepts
185
REVISION_NAMESPACES = {}
187
def push_stores(self, branch_to):
188
"""Copy the content of this branches store to branch_to."""
189
if (self._branch_format != branch_to._branch_format
190
or self._branch_format != 4):
191
from bzrlib.fetch import greedy_fetch
192
mutter("falling back to fetch logic to push between %s(%s) and %s(%s)",
193
self, self._branch_format, branch_to, branch_to._branch_format)
194
greedy_fetch(to_branch=branch_to, from_branch=self,
195
revision=self.last_revision())
198
store_pairs = ((self.text_store, branch_to.text_store),
199
(self.inventory_store, branch_to.inventory_store),
200
(self.revision_store, branch_to.revision_store))
202
for from_store, to_store in store_pairs:
203
copy_all(from_store, to_store)
204
except UnlistableStore:
205
raise UnlistableBranch(from_store)
207
def __init__(self, transport, init=False,
208
relax_version_check=False):
209
"""Create new branch object at a particular location.
211
transport -- A Transport object, defining how to access files.
212
(If a string, transport.transport() will be used to
213
create a Transport object)
215
init -- If True, create new control files in a previously
216
unversioned directory. If False, the branch must already
219
relax_version_check -- If true, the usual check for the branch
220
version is not applied. This is intended only for
221
upgrade/recovery type use; it's not guaranteed that
222
all operations will work on old format branches.
224
In the test suite, creation of new trees is tested using the
225
`ScratchBranch` class.
227
assert isinstance(transport, Transport), \
228
"%r is not a Transport" % transport
229
self._transport = transport
232
self._check_format(relax_version_check)
234
def get_store(name, compressed=True, prefixed=False):
235
# FIXME: This approach of assuming stores are all entirely compressed
236
# or entirely uncompressed is tidy, but breaks upgrade from
237
# some existing branches where there's a mixture; we probably
238
# still want the option to look for both.
239
relpath = self._rel_controlfilename(name)
241
store = CompressedTextStore(self._transport.clone(relpath),
244
store = TextStore(self._transport.clone(relpath),
246
#if self._transport.should_cache():
247
# cache_path = os.path.join(self.cache_root, name)
248
# os.mkdir(cache_path)
249
# store = bzrlib.store.CachedStore(store, cache_path)
251
def get_weave(name, prefixed=False):
252
relpath = self._rel_controlfilename(name)
253
ws = WeaveStore(self._transport.clone(relpath), prefixed=prefixed)
254
if self._transport.should_cache():
255
ws.enable_cache = True
258
if self._branch_format == 4:
259
self.inventory_store = get_store('inventory-store')
260
self.text_store = get_store('text-store')
261
self.revision_store = get_store('revision-store')
262
elif self._branch_format == 5:
263
self.control_weaves = get_weave([])
264
self.weave_store = get_weave('weaves')
265
self.revision_store = get_store('revision-store', compressed=False)
266
elif self._branch_format == 6:
267
self.control_weaves = get_weave([])
268
self.weave_store = get_weave('weaves', prefixed=True)
269
self.revision_store = get_store('revision-store', compressed=False,
271
self._transaction = None
274
return '%s(%r)' % (self.__class__.__name__, self._transport.base)
281
if self._lock_mode or self._lock:
282
# XXX: This should show something every time, and be suitable for
283
# headless operation and embedding
284
warn("branch %r was not explicitly unlocked" % self)
287
# TODO: It might be best to do this somewhere else,
288
# but it is nice for a Branch object to automatically
289
# cache it's information.
290
# Alternatively, we could have the Transport objects cache requests
291
# See the earlier discussion about how major objects (like Branch)
292
# should never expect their __del__ function to run.
293
if hasattr(self, 'cache_root') and self.cache_root is not None:
296
shutil.rmtree(self.cache_root)
299
self.cache_root = None
303
return self._transport.base
306
base = property(_get_base)
308
def _finish_transaction(self):
309
"""Exit the current transaction."""
310
if self._transaction is None:
311
raise errors.LockError('Branch %s is not in a transaction' %
313
transaction = self._transaction
314
self._transaction = None
317
def get_transaction(self):
318
"""Return the current active transaction.
320
If no transaction is active, this returns a passthrough object
321
for which all data is immedaitely flushed and no caching happens.
323
if self._transaction is None:
324
return transactions.PassThroughTransaction()
326
return self._transaction
328
def _set_transaction(self, new_transaction):
329
"""Set a new active transaction."""
330
if self._transaction is not None:
331
raise errors.LockError('Branch %s is in a transaction already.' %
333
self._transaction = new_transaction
161
335
def lock_write(self):
162
raise NotImplementedError('lock_write is abstract')
336
mutter("lock write: %s (%s)", self, self._lock_count)
337
# TODO: Upgrade locking to support using a Transport,
338
# and potentially a remote locking protocol
340
if self._lock_mode != 'w':
341
raise LockError("can't upgrade to a write lock from %r" %
343
self._lock_count += 1
345
self._lock = self._transport.lock_write(
346
self._rel_controlfilename('branch-lock'))
347
self._lock_mode = 'w'
349
self._set_transaction(transactions.PassThroughTransaction())
164
351
def lock_read(self):
165
raise NotImplementedError('lock_read is abstract')
352
mutter("lock read: %s (%s)", self, self._lock_count)
354
assert self._lock_mode in ('r', 'w'), \
355
"invalid lock mode %r" % self._lock_mode
356
self._lock_count += 1
358
self._lock = self._transport.lock_read(
359
self._rel_controlfilename('branch-lock'))
360
self._lock_mode = 'r'
362
self._set_transaction(transactions.ReadOnlyTransaction())
363
# 5K may be excessive, but hey, its a knob.
364
self.get_transaction().set_cache_size(5000)
167
366
def unlock(self):
168
raise NotImplementedError('unlock is abstract')
170
def peek_lock_mode(self):
171
"""Return lock mode for the Branch: 'r', 'w' or None"""
172
raise NotImplementedError(self.peek_lock_mode)
174
def get_physical_lock_status(self):
175
raise NotImplementedError('get_physical_lock_status is abstract')
367
mutter("unlock: %s (%s)", self, self._lock_count)
368
if not self._lock_mode:
369
raise LockError('branch %r is not locked' % (self))
371
if self._lock_count > 1:
372
self._lock_count -= 1
374
self._finish_transaction()
377
self._lock_mode = self._lock_count = None
177
379
def abspath(self, name):
178
"""Return absolute filename for something in the branch
180
XXX: Robert Collins 20051017 what is this used for? why is it a branch
181
method and not a tree method.
183
raise NotImplementedError('abspath is abstract')
185
def bind(self, other):
186
"""Bind the local branch the other branch.
188
:param other: The branch to bind to
191
raise errors.UpgradeRequired(self.base)
194
def fetch(self, from_branch, last_revision=None, pb=None):
195
"""Copy revisions from from_branch into this branch.
197
:param from_branch: Where to copy from.
198
:param last_revision: What revision to stop at (None for at the end
200
:param pb: An optional progress bar to use.
202
Returns the copied revision count and the failed revisions in a tuple:
205
if self.base == from_branch.base:
208
nested_pb = bzrlib.ui.ui_factory.nested_progress_bar()
380
"""Return absolute filename for something in the branch"""
381
return self._transport.abspath(name)
383
def relpath(self, path):
384
"""Return path relative to this branch of something inside it.
386
Raises an error if path is not in this branch."""
387
return self._transport.relpath(path)
390
def _rel_controlfilename(self, file_or_path):
391
if isinstance(file_or_path, basestring):
392
file_or_path = [file_or_path]
393
return [bzrlib.BZRDIR] + file_or_path
395
def controlfilename(self, file_or_path):
396
"""Return location relative to branch."""
397
return self._transport.abspath(self._rel_controlfilename(file_or_path))
400
def controlfile(self, file_or_path, mode='r'):
401
"""Open a control file for this branch.
403
There are two classes of file in the control directory: text
404
and binary. binary files are untranslated byte streams. Text
405
control files are stored with Unix newlines and in UTF-8, even
406
if the platform or locale defaults are different.
408
Controlfiles should almost never be opened in write mode but
409
rather should be atomically copied and replaced using atomicfile.
413
relpath = self._rel_controlfilename(file_or_path)
414
#TODO: codecs.open() buffers linewise, so it was overloaded with
415
# a much larger buffer, do we need to do the same for getreader/getwriter?
417
return self._transport.get(relpath)
419
raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
421
return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
423
raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
213
from_branch.lock_read()
215
if last_revision is None:
216
pb.update('get source history')
217
from_history = from_branch.revision_history()
219
last_revision = from_history[-1]
425
raise BzrError("invalid controlfile mode %r" % mode)
427
def put_controlfile(self, path, f, encode=True):
428
"""Write an entry as a controlfile.
430
:param path: The path to put the file, relative to the .bzr control
432
:param f: A file-like or string object whose contents should be copied.
433
:param encode: If true, encode the contents as utf-8
435
self.put_controlfiles([(path, f)], encode=encode)
437
def put_controlfiles(self, files, encode=True):
438
"""Write several entries as controlfiles.
440
:param files: A list of [(path, file)] pairs, where the path is the directory
441
underneath the bzr control directory
442
:param encode: If true, encode the contents as utf-8
446
for path, f in files:
448
if isinstance(f, basestring):
449
f = f.encode('utf-8', 'replace')
221
# no history in the source branch
222
last_revision = NULL_REVISION
223
return self.repository.fetch(from_branch.repository,
224
revision_id=last_revision,
227
if nested_pb is not None:
231
def get_bound_location(self):
232
"""Return the URL of the branch we are bound to.
234
Older format branches cannot bind, please be sure to use a metadir
239
def get_master_branch(self):
240
"""Return the branch we are bound to.
451
f = codecs.getwriter('utf-8')(f, errors='replace')
452
path = self._rel_controlfilename(path)
453
ctrl_files.append((path, f))
454
self._transport.put_multi(ctrl_files)
456
def _make_control(self):
457
from bzrlib.inventory import Inventory
458
from bzrlib.weavefile import write_weave_v5
459
from bzrlib.weave import Weave
242
:return: Either a Branch, or None
461
# Create an empty inventory
463
# if we want per-tree root ids then this is the place to set
464
# them; they're not needed for now and so ommitted for
466
bzrlib.xml5.serializer_v5.write_inventory(Inventory(), sio)
467
empty_inv = sio.getvalue()
469
bzrlib.weavefile.write_weave_v5(Weave(), sio)
470
empty_weave = sio.getvalue()
472
dirs = [[], 'revision-store', 'weaves']
474
"This is a Bazaar-NG control directory.\n"
475
"Do not change any files in this directory.\n"),
476
('branch-format', BZR_BRANCH_FORMAT_6),
477
('revision-history', ''),
480
('pending-merges', ''),
481
('inventory', empty_inv),
482
('inventory.weave', empty_weave),
483
('ancestry.weave', empty_weave)
485
cfn = self._rel_controlfilename
486
self._transport.mkdir_multi([cfn(d) for d in dirs])
487
self.put_controlfiles(files)
488
mutter('created control directory in ' + self._transport.base)
490
def _check_format(self, relax_version_check):
491
"""Check this branch format is supported.
493
The format level is stored, as an integer, in
494
self._branch_format for code that needs to check it later.
496
In the future, we might need different in-memory Branch
497
classes to support downlevel branches. But not yet.
500
fmt = self.controlfile('branch-format', 'r').read()
502
raise NotBranchError(self.base)
503
mutter("got branch format %r", fmt)
504
if fmt == BZR_BRANCH_FORMAT_6:
505
self._branch_format = 6
506
elif fmt == BZR_BRANCH_FORMAT_5:
507
self._branch_format = 5
508
elif fmt == BZR_BRANCH_FORMAT_4:
509
self._branch_format = 4
511
if (not relax_version_check
512
and self._branch_format not in (5, 6)):
513
raise errors.UnsupportedFormatError(
514
'sorry, branch format %r not supported' % fmt,
515
['use a different bzr version',
516
'or remove the .bzr directory'
517
' and "bzr init" again'])
246
519
def get_root_id(self):
247
520
"""Return the id of this branches root"""
248
raise NotImplementedError('get_root_id is abstract')
250
def print_file(self, file, revision_id):
521
inv = self.read_working_inventory()
522
return inv.root.file_id
524
def set_root_id(self, file_id):
525
inv = self.read_working_inventory()
526
orig_root_id = inv.root.file_id
527
del inv._byid[inv.root.file_id]
528
inv.root.file_id = file_id
529
inv._byid[inv.root.file_id] = inv.root
532
if entry.parent_id in (None, orig_root_id):
533
entry.parent_id = inv.root.file_id
534
self._write_inventory(inv)
536
def read_working_inventory(self):
537
"""Read the working inventory."""
540
# ElementTree does its own conversion from UTF-8, so open in
542
f = self.controlfile('inventory', 'rb')
543
return bzrlib.xml5.serializer_v5.read_inventory(f)
548
def _write_inventory(self, inv):
549
"""Update the working inventory.
551
That is to say, the inventory describing changes underway, that
552
will be committed to the next revision.
554
from cStringIO import StringIO
558
bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
560
# Transport handles atomicity
561
self.put_controlfile('inventory', sio)
565
mutter('wrote working inventory')
567
inventory = property(read_working_inventory, _write_inventory, None,
568
"""Inventory for the working copy.""")
570
def add(self, files, ids=None):
571
"""Make files versioned.
573
Note that the command line normally calls smart_add instead,
574
which can automatically recurse.
576
This puts the files in the Added state, so that they will be
577
recorded by the next commit.
580
List of paths to add, relative to the base of the tree.
583
If set, use these instead of automatically generated ids.
584
Must be the same length as the list of files, but may
585
contain None for ids that are to be autogenerated.
587
TODO: Perhaps have an option to add the ids even if the files do
590
TODO: Perhaps yield the ids and paths as they're added.
592
# TODO: Re-adding a file that is removed in the working copy
593
# should probably put it back with the previous ID.
594
if isinstance(files, basestring):
595
assert(ids is None or isinstance(ids, basestring))
601
ids = [None] * len(files)
603
assert(len(ids) == len(files))
607
inv = self.read_working_inventory()
608
for f,file_id in zip(files, ids):
609
if is_control_file(f):
610
raise BzrError("cannot add control file %s" % quotefn(f))
615
raise BzrError("cannot add top-level %r" % f)
617
fullpath = os.path.normpath(self.abspath(f))
620
kind = file_kind(fullpath)
622
# maybe something better?
623
raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
625
if not InventoryEntry.versionable_kind(kind):
626
raise BzrError('cannot add: not a versionable file ('
627
'i.e. regular file, symlink or directory): %s' % quotefn(f))
630
file_id = gen_file_id(f)
631
inv.add_path(f, kind=kind, file_id=file_id)
633
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
635
self._write_inventory(inv)
640
def print_file(self, file, revno):
251
641
"""Print `file` to stdout."""
252
raise NotImplementedError('print_file is abstract')
644
tree = self.revision_tree(self.get_rev_id(revno))
645
# use inventory as it was in that revision
646
file_id = tree.inventory.path2id(file)
648
raise BzrError("%r is not present in revision %s" % (file, revno))
649
tree.print_file(file_id)
654
def remove(self, files, verbose=False):
655
"""Mark nominated files for removal from the inventory.
657
This does not remove their text. This does not run on
659
TODO: Refuse to remove modified files unless --force is given?
661
TODO: Do something useful with directories.
663
TODO: Should this remove the text or not? Tough call; not
664
removing may be useful and the user can just use use rm, and
665
is the opposite of add. Removing it is consistent with most
666
other tools. Maybe an option.
668
## TODO: Normalize names
669
## TODO: Remove nested loops; better scalability
670
if isinstance(files, basestring):
676
tree = self.working_tree()
679
# do this before any modifications
683
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
684
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
686
# having remove it, it must be either ignored or unknown
687
if tree.is_ignored(f):
691
show_status(new_status, inv[fid].kind, quotefn(f))
694
self._write_inventory(inv)
698
# FIXME: this doesn't need to be a branch method
699
def set_inventory(self, new_inventory_list):
700
from bzrlib.inventory import Inventory, InventoryEntry
701
inv = Inventory(self.get_root_id())
702
for path, file_id, parent, kind in new_inventory_list:
703
name = os.path.basename(path)
706
# fixme, there should be a factory function inv,add_??
707
if kind == 'directory':
708
inv.add(inventory.InventoryDirectory(file_id, name, parent))
710
inv.add(inventory.InventoryFile(file_id, name, parent))
711
elif kind == 'symlink':
712
inv.add(inventory.InventoryLink(file_id, name, parent))
714
raise BzrError("unknown kind %r" % kind)
715
self._write_inventory(inv)
718
"""Return all unknown files.
720
These are files in the working directory that are not versioned or
721
control files or ignored.
723
>>> b = ScratchBranch(files=['foo', 'foo~'])
724
>>> list(b.unknowns())
727
>>> list(b.unknowns())
730
>>> list(b.unknowns())
733
return self.working_tree().unknowns()
254
736
def append_revision(self, *revision_ids):
255
raise NotImplementedError('append_revision is abstract')
257
def set_revision_history(self, rev_history):
258
raise NotImplementedError('set_revision_history is abstract')
737
for revision_id in revision_ids:
738
mutter("add {%s} to revision-history" % revision_id)
741
rev_history = self.revision_history()
742
rev_history.extend(revision_ids)
743
self.put_controlfile('revision-history', '\n'.join(rev_history))
747
def has_revision(self, revision_id):
748
"""True if this branch has a copy of the revision.
750
This does not necessarily imply the revision is merge
751
or on the mainline."""
752
return (revision_id is None
753
or revision_id in self.revision_store)
755
def get_revision_xml_file(self, revision_id):
756
"""Return XML file object for revision object."""
757
if not revision_id or not isinstance(revision_id, basestring):
758
raise InvalidRevisionId(revision_id)
763
return self.revision_store[revision_id]
764
except (IndexError, KeyError):
765
raise bzrlib.errors.NoSuchRevision(self, revision_id)
770
get_revision_xml = get_revision_xml_file
772
def get_revision_xml(self, revision_id):
773
return self.get_revision_xml_file(revision_id).read()
776
def get_revision(self, revision_id):
777
"""Return the Revision object for a named revision"""
778
xml_file = self.get_revision_xml_file(revision_id)
781
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
782
except SyntaxError, e:
783
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
787
assert r.revision_id == revision_id
790
def get_revision_delta(self, revno):
791
"""Return the delta for one revision.
793
The delta is relative to its mainline predecessor, or the
794
empty tree for revision 1.
796
assert isinstance(revno, int)
797
rh = self.revision_history()
798
if not (1 <= revno <= len(rh)):
799
raise InvalidRevisionNumber(revno)
801
# revno is 1-based; list is 0-based
803
new_tree = self.revision_tree(rh[revno-1])
805
old_tree = EmptyTree()
807
old_tree = self.revision_tree(rh[revno-2])
809
return compare_trees(old_tree, new_tree)
811
def get_revision_sha1(self, revision_id):
812
"""Hash the stored value of a revision, and return it."""
813
# In the future, revision entries will be signed. At that
814
# point, it is probably best *not* to include the signature
815
# in the revision hash. Because that lets you re-sign
816
# the revision, (add signatures/remove signatures) and still
817
# have all hash pointers stay consistent.
818
# But for now, just hash the contents.
819
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
821
def get_ancestry(self, revision_id):
822
"""Return a list of revision-ids integrated by a revision.
824
This currently returns a list, but the ordering is not guaranteed:
827
if revision_id is None:
829
w = self.get_inventory_weave()
830
return [None] + map(w.idx_to_name,
831
w.inclusions([w.lookup(revision_id)]))
833
def get_inventory_weave(self):
834
return self.control_weaves.get_weave('inventory',
835
self.get_transaction())
837
def get_inventory(self, revision_id):
838
"""Get Inventory object by hash."""
839
xml = self.get_inventory_xml(revision_id)
840
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
842
def get_inventory_xml(self, revision_id):
843
"""Get inventory XML as a file object."""
845
assert isinstance(revision_id, basestring), type(revision_id)
846
iw = self.get_inventory_weave()
847
return iw.get_text(iw.lookup(revision_id))
849
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
851
def get_inventory_sha1(self, revision_id):
852
"""Return the sha1 hash of the inventory entry
854
return self.get_revision(revision_id).inventory_sha1
856
def get_revision_inventory(self, revision_id):
857
"""Return inventory of a past revision."""
858
# TODO: Unify this with get_inventory()
859
# bzr 0.0.6 and later imposes the constraint that the inventory_id
860
# must be the same as its revision, so this is trivial.
861
if revision_id == None:
862
return Inventory(self.get_root_id())
864
return self.get_inventory(revision_id)
260
866
def revision_history(self):
261
867
"""Return sequence of revision hashes on to this branch."""
262
raise NotImplementedError('revision_history is abstract')
870
transaction = self.get_transaction()
871
history = transaction.map.find_revision_history()
872
if history is not None:
873
mutter("cache hit for revision-history in %s", self)
875
history = [l.rstrip('\r\n') for l in
876
self.controlfile('revision-history', 'r').readlines()]
877
transaction.map.add_revision_history(history)
878
# this call is disabled because revision_history is
879
# not really an object yet, and the transaction is for objects.
880
# transaction.register_clean(history, precious=True)
885
def common_ancestor(self, other, self_revno=None, other_revno=None):
887
>>> from bzrlib.commit import commit
888
>>> sb = ScratchBranch(files=['foo', 'foo~'])
889
>>> sb.common_ancestor(sb) == (None, None)
891
>>> commit(sb, "Committing first revision", verbose=False)
892
>>> sb.common_ancestor(sb)[0]
894
>>> clone = sb.clone()
895
>>> commit(sb, "Committing second revision", verbose=False)
896
>>> sb.common_ancestor(sb)[0]
898
>>> sb.common_ancestor(clone)[0]
900
>>> commit(clone, "Committing divergent second revision",
902
>>> sb.common_ancestor(clone)[0]
904
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
906
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
908
>>> clone2 = sb.clone()
909
>>> sb.common_ancestor(clone2)[0]
911
>>> sb.common_ancestor(clone2, self_revno=1)[0]
913
>>> sb.common_ancestor(clone2, other_revno=1)[0]
916
my_history = self.revision_history()
917
other_history = other.revision_history()
918
if self_revno is None:
919
self_revno = len(my_history)
920
if other_revno is None:
921
other_revno = len(other_history)
922
indices = range(min((self_revno, other_revno)))
925
if my_history[r] == other_history[r]:
926
return r+1, my_history[r]
265
931
"""Return current revision number for this branch.
436
1318
if revno < 1 or revno > self.revno():
437
1319
raise InvalidRevisionNumber(revno)
440
def clone(self, *args, **kwargs):
441
"""Clone this branch into to_bzrdir preserving all semantic values.
443
revision_id: if not None, the revision history in the new branch will
444
be truncated to end with revision_id.
446
# for API compatability, until 0.8 releases we provide the old api:
447
# def clone(self, to_location, revision=None, basis_branch=None, to_branch_format=None):
448
# after 0.8 releases, the *args and **kwargs should be changed:
449
# def clone(self, to_bzrdir, revision_id=None):
450
if (kwargs.get('to_location', None) or
451
kwargs.get('revision', None) or
452
kwargs.get('basis_branch', None) or
453
(len(args) and isinstance(args[0], basestring))):
454
# backwards compatability api:
455
warn("Branch.clone() has been deprecated for BzrDir.clone() from"
456
" bzrlib 0.8.", DeprecationWarning, stacklevel=3)
459
basis_branch = args[2]
461
basis_branch = kwargs.get('basis_branch', None)
463
basis = basis_branch.bzrdir
468
revision_id = args[1]
470
revision_id = kwargs.get('revision', None)
475
# no default to raise if not provided.
476
url = kwargs.get('to_location')
477
return self.bzrdir.clone(url,
478
revision_id=revision_id,
479
basis=basis).open_branch()
481
# generate args by hand
483
revision_id = args[1]
485
revision_id = kwargs.get('revision_id', None)
489
# no default to raise if not provided.
490
to_bzrdir = kwargs.get('to_bzrdir')
491
result = self._format.initialize(to_bzrdir)
492
self.copy_content_into(result, revision_id=revision_id)
496
def sprout(self, to_bzrdir, revision_id=None):
497
"""Create a new line of development from the branch, into to_bzrdir.
499
revision_id: if not None, the revision history in the new branch will
500
be truncated to end with revision_id.
502
result = self._format.initialize(to_bzrdir)
503
self.copy_content_into(result, revision_id=revision_id)
504
result.set_parent(self.bzrdir.root_transport.base)
508
def copy_content_into(self, destination, revision_id=None):
509
"""Copy the content of self into destination.
511
revision_id: if not None, the revision history in the new branch will
512
be truncated to end with revision_id.
514
new_history = self.revision_history()
515
if revision_id is not None:
517
new_history = new_history[:new_history.index(revision_id) + 1]
519
rev = self.repository.get_revision(revision_id)
520
new_history = rev.get_history(self.repository)[1:]
521
destination.set_revision_history(new_history)
522
parent = self.get_parent()
524
destination.set_parent(parent)
527
class BranchFormat(object):
528
"""An encapsulation of the initialization and open routines for a format.
530
Formats provide three things:
531
* An initialization routine,
535
Formats are placed in an dict by their format string for reference
536
during branch opening. Its not required that these be instances, they
537
can be classes themselves with class methods - it simply depends on
538
whether state is needed for a given format or not.
540
Once a format is deprecated, just deprecate the initialize and open
541
methods on the format class. Do not deprecate the object, as the
542
object will be created every time regardless.
545
_default_format = None
546
"""The default format used for new branches."""
549
"""The known formats."""
552
def find_format(klass, a_bzrdir):
553
"""Return the format for the branch object in a_bzrdir."""
555
transport = a_bzrdir.get_branch_transport(None)
556
format_string = transport.get("format").read()
557
return klass._formats[format_string]
559
raise NotBranchError(path=transport.base)
561
raise errors.UnknownFormatError(format_string)
564
def get_default_format(klass):
565
"""Return the current default format."""
566
return klass._default_format
568
def get_format_string(self):
569
"""Return the ASCII format string that identifies this format."""
570
raise NotImplementedError(self.get_format_string)
572
def get_format_description(self):
573
"""Return the short format description for this format."""
574
raise NotImplementedError(self.get_format_string)
576
def initialize(self, a_bzrdir):
577
"""Create a branch of this format in a_bzrdir."""
578
raise NotImplementedError(self.initialized)
580
def is_supported(self):
581
"""Is this format supported?
583
Supported formats can be initialized and opened.
584
Unsupported formats may not support initialization or committing or
585
some other features depending on the reason for not being supported.
589
def open(self, a_bzrdir, _found=False):
590
"""Return the branch object for a_bzrdir
592
_found is a private parameter, do not use it. It is used to indicate
593
if format probing has already be done.
595
raise NotImplementedError(self.open)
598
def register_format(klass, format):
599
klass._formats[format.get_format_string()] = format
602
def set_default_format(klass, format):
603
klass._default_format = format
606
def unregister_format(klass, format):
607
assert klass._formats[format.get_format_string()] is format
608
del klass._formats[format.get_format_string()]
611
return self.get_format_string().rstrip()
614
class BzrBranchFormat4(BranchFormat):
615
"""Bzr branch format 4.
618
- a revision-history file.
619
- a branch-lock lock file [ to be shared with the bzrdir ]
622
def get_format_description(self):
623
"""See BranchFormat.get_format_description()."""
624
return "Branch format 4"
626
def initialize(self, a_bzrdir):
627
"""Create a branch of this format in a_bzrdir."""
628
mutter('creating branch in %s', a_bzrdir.transport.base)
629
branch_transport = a_bzrdir.get_branch_transport(self)
630
utf8_files = [('revision-history', ''),
633
control_files = LockableFiles(branch_transport, 'branch-lock',
635
control_files.create_lock()
636
control_files.lock_write()
638
for file, content in utf8_files:
639
control_files.put_utf8(file, content)
641
control_files.unlock()
642
return self.open(a_bzrdir, _found=True)
645
super(BzrBranchFormat4, self).__init__()
646
self._matchingbzrdir = bzrdir.BzrDirFormat6()
648
def open(self, a_bzrdir, _found=False):
649
"""Return the branch object for a_bzrdir
651
_found is a private parameter, do not use it. It is used to indicate
652
if format probing has already be done.
655
# we are being called directly and must probe.
656
raise NotImplementedError
657
return BzrBranch(_format=self,
658
_control_files=a_bzrdir._control_files,
660
_repository=a_bzrdir.open_repository())
663
return "Bazaar-NG branch format 4"
666
class BzrBranchFormat5(BranchFormat):
667
"""Bzr branch format 5.
670
- a revision-history file.
672
- a lock dir guarding the branch itself
673
- all of this stored in a branch/ subdirectory
674
- works with shared repositories.
676
This format is new in bzr 0.8.
679
def get_format_string(self):
680
"""See BranchFormat.get_format_string()."""
681
return "Bazaar-NG branch format 5\n"
683
def get_format_description(self):
684
"""See BranchFormat.get_format_description()."""
685
return "Branch format 5"
687
def initialize(self, a_bzrdir):
688
"""Create a branch of this format in a_bzrdir."""
689
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
690
branch_transport = a_bzrdir.get_branch_transport(self)
691
utf8_files = [('revision-history', ''),
694
control_files = LockableFiles(branch_transport, 'lock', LockDir)
695
control_files.create_lock()
696
control_files.lock_write()
697
control_files.put_utf8('format', self.get_format_string())
699
for file, content in utf8_files:
700
control_files.put_utf8(file, content)
702
control_files.unlock()
703
return self.open(a_bzrdir, _found=True, )
706
super(BzrBranchFormat5, self).__init__()
707
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
709
def open(self, a_bzrdir, _found=False):
710
"""Return the branch object for a_bzrdir
712
_found is a private parameter, do not use it. It is used to indicate
713
if format probing has already be done.
716
format = BranchFormat.find_format(a_bzrdir)
717
assert format.__class__ == self.__class__
718
transport = a_bzrdir.get_branch_transport(None)
719
control_files = LockableFiles(transport, 'lock', LockDir)
720
return BzrBranch5(_format=self,
721
_control_files=control_files,
723
_repository=a_bzrdir.find_repository())
726
return "Bazaar-NG Metadir branch format 5"
729
class BranchReferenceFormat(BranchFormat):
730
"""Bzr branch reference format.
732
Branch references are used in implementing checkouts, they
733
act as an alias to the real branch which is at some other url.
740
def get_format_string(self):
741
"""See BranchFormat.get_format_string()."""
742
return "Bazaar-NG Branch Reference Format 1\n"
744
def get_format_description(self):
745
"""See BranchFormat.get_format_description()."""
746
return "Checkout reference format 1"
748
def initialize(self, a_bzrdir, target_branch=None):
749
"""Create a branch of this format in a_bzrdir."""
750
if target_branch is None:
751
# this format does not implement branch itself, thus the implicit
752
# creation contract must see it as uninitializable
753
raise errors.UninitializableFormat(self)
754
mutter('creating branch reference in %s', a_bzrdir.transport.base)
755
branch_transport = a_bzrdir.get_branch_transport(self)
756
# FIXME rbc 20060209 one j-a-ms encoding branch lands this str() cast is not needed.
757
branch_transport.put('location', StringIO(str(target_branch.bzrdir.root_transport.base)))
758
branch_transport.put('format', StringIO(self.get_format_string()))
759
return self.open(a_bzrdir, _found=True)
762
super(BranchReferenceFormat, self).__init__()
763
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
765
def _make_reference_clone_function(format, a_branch):
766
"""Create a clone() routine for a branch dynamically."""
767
def clone(to_bzrdir, revision_id=None):
768
"""See Branch.clone()."""
769
return format.initialize(to_bzrdir, a_branch)
770
# cannot obey revision_id limits when cloning a reference ...
771
# FIXME RBC 20060210 either nuke revision_id for clone, or
772
# emit some sort of warning/error to the caller ?!
775
def open(self, a_bzrdir, _found=False):
776
"""Return the branch that the branch reference in a_bzrdir points at.
778
_found is a private parameter, do not use it. It is used to indicate
779
if format probing has already be done.
782
format = BranchFormat.find_format(a_bzrdir)
783
assert format.__class__ == self.__class__
784
transport = a_bzrdir.get_branch_transport(None)
785
real_bzrdir = bzrdir.BzrDir.open(transport.get('location').read())
786
result = real_bzrdir.open_branch()
787
# this changes the behaviour of result.clone to create a new reference
788
# rather than a copy of the content of the branch.
789
# I did not use a proxy object because that needs much more extensive
790
# testing, and we are only changing one behaviour at the moment.
791
# If we decide to alter more behaviours - i.e. the implicit nickname
792
# then this should be refactored to introduce a tested proxy branch
793
# and a subclass of that for use in overriding clone() and ....
795
result.clone = self._make_reference_clone_function(result)
799
# formats which have no format string are not discoverable
800
# and not independently creatable, so are not registered.
801
__default_format = BzrBranchFormat5()
802
BranchFormat.register_format(__default_format)
803
BranchFormat.register_format(BranchReferenceFormat())
804
BranchFormat.set_default_format(__default_format)
805
_legacy_formats = [BzrBranchFormat4(),
808
class BzrBranch(Branch):
809
"""A branch stored in the actual filesystem.
811
Note that it's "local" in the context of the filesystem; it doesn't
812
really matter if it's on an nfs/smb/afs/coda/... share, as long as
813
it's writable, and can be accessed via the normal filesystem API.
1325
class ScratchBranch(_Branch):
1326
"""Special test class: a branch that cleans up after itself.
1328
>>> b = ScratchBranch()
1336
def __init__(self, files=[], dirs=[], base=None):
1337
"""Make a test branch.
1339
This creates a temporary directory and runs init-tree in it.
1341
If any files are listed, they are created in the working copy.
1343
from tempfile import mkdtemp
1348
if isinstance(base, basestring):
1349
base = get_transport(base)
1350
_Branch.__init__(self, base, init=init)
1352
self._transport.mkdir(d)
1355
self._transport.put(f, 'content of %s' % f)
1360
>>> orig = ScratchBranch(files=["file1", "file2"])
1361
>>> clone = orig.clone()
1362
>>> if os.name != 'nt':
1363
... os.path.samefile(orig.base, clone.base)
1365
... orig.base == clone.base
1368
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1371
from shutil import copytree
1372
from tempfile import mkdtemp
1375
copytree(self.base, base, symlinks=True)
1376
return ScratchBranch(base=base)
1382
"""Destroy the test branch, removing the scratch directory."""
1383
from shutil import rmtree
1386
mutter("delete ScratchBranch %s" % self.base)
1389
# Work around for shutil.rmtree failing on Windows when
1390
# readonly files are encountered
1391
mutter("hit exception in destroying ScratchBranch: %s" % e)
1392
for root, dirs, files in os.walk(self.base, topdown=False):
1394
os.chmod(os.path.join(root, name), 0700)
1396
self._transport = None
816
def __init__(self, transport=DEPRECATED_PARAMETER, init=DEPRECATED_PARAMETER,
817
relax_version_check=DEPRECATED_PARAMETER, _format=None,
818
_control_files=None, a_bzrdir=None, _repository=None):
819
"""Create new branch object at a particular location.
821
transport -- A Transport object, defining how to access files.
823
init -- If True, create new control files in a previously
824
unversioned directory. If False, the branch must already
827
relax_version_check -- If true, the usual check for the branch
828
version is not applied. This is intended only for
829
upgrade/recovery type use; it's not guaranteed that
830
all operations will work on old format branches.
833
self.bzrdir = bzrdir.BzrDir.open(transport.base)
835
self.bzrdir = a_bzrdir
836
self._transport = self.bzrdir.transport.clone('..')
837
self._base = self._transport.base
838
self._format = _format
839
if _control_files is None:
840
raise BzrBadParameterMissing('_control_files')
841
self.control_files = _control_files
842
if deprecated_passed(init):
843
warn("BzrBranch.__init__(..., init=XXX): The init parameter is "
844
"deprecated as of bzr 0.8. Please use Branch.create().",
848
# this is slower than before deprecation, oh well never mind.
850
self._initialize(transport.base)
851
self._check_format(_format)
852
if deprecated_passed(relax_version_check):
853
warn("BzrBranch.__init__(..., relax_version_check=XXX_: The "
854
"relax_version_check parameter is deprecated as of bzr 0.8. "
855
"Please use BzrDir.open_downlevel, or a BzrBranchFormat's "
859
if (not relax_version_check
860
and not self._format.is_supported()):
861
raise errors.UnsupportedFormatError(
862
'sorry, branch format %r not supported' % fmt,
863
['use a different bzr version',
864
'or remove the .bzr directory'
865
' and "bzr init" again'])
866
if deprecated_passed(transport):
867
warn("BzrBranch.__init__(transport=XXX...): The transport "
868
"parameter is deprecated as of bzr 0.8. "
869
"Please use Branch.open, or bzrdir.open_branch().",
872
self.repository = _repository
875
return '%s(%r)' % (self.__class__.__name__, self.base)
880
# TODO: It might be best to do this somewhere else,
881
# but it is nice for a Branch object to automatically
882
# cache it's information.
883
# Alternatively, we could have the Transport objects cache requests
884
# See the earlier discussion about how major objects (like Branch)
885
# should never expect their __del__ function to run.
886
# XXX: cache_root seems to be unused, 2006-01-13 mbp
887
if hasattr(self, 'cache_root') and self.cache_root is not None:
889
shutil.rmtree(self.cache_root)
892
self.cache_root = None
897
base = property(_get_base, doc="The URL for the root of this branch.")
899
def _finish_transaction(self):
900
"""Exit the current transaction."""
901
return self.control_files._finish_transaction()
903
def get_transaction(self):
904
"""Return the current active transaction.
906
If no transaction is active, this returns a passthrough object
907
for which all data is immediately flushed and no caching happens.
909
# this is an explicit function so that we can do tricky stuff
910
# when the storage in rev_storage is elsewhere.
911
# we probably need to hook the two 'lock a location' and
912
# 'have a transaction' together more delicately, so that
913
# we can have two locks (branch and storage) and one transaction
914
# ... and finishing the transaction unlocks both, but unlocking
915
# does not. - RBC 20051121
916
return self.control_files.get_transaction()
918
def _set_transaction(self, transaction):
919
"""Set a new active transaction."""
920
return self.control_files._set_transaction(transaction)
922
def abspath(self, name):
923
"""See Branch.abspath."""
924
return self.control_files._transport.abspath(name)
926
def _check_format(self, format):
927
"""Identify the branch format if needed.
929
The format is stored as a reference to the format object in
930
self._format for code that needs to check it later.
932
The format parameter is either None or the branch format class
933
used to open this branch.
935
FIXME: DELETE THIS METHOD when pre 0.8 support is removed.
938
format = BzrBranchFormat.find_format(self.bzrdir)
939
self._format = format
940
mutter("got branch format %s", self._format)
943
def get_root_id(self):
944
"""See Branch.get_root_id."""
945
tree = self.repository.revision_tree(self.last_revision())
946
return tree.inventory.root.file_id
949
return self.control_files.is_locked()
951
def lock_write(self):
952
# TODO: test for failed two phase locks. This is known broken.
953
self.control_files.lock_write()
954
self.repository.lock_write()
957
# TODO: test for failed two phase locks. This is known broken.
958
self.control_files.lock_read()
959
self.repository.lock_read()
962
# TODO: test for failed two phase locks. This is known broken.
963
self.repository.unlock()
964
self.control_files.unlock()
966
def peek_lock_mode(self):
967
if self.control_files._lock_count == 0:
970
return self.control_files._lock_mode
972
def get_physical_lock_status(self):
973
return self.control_files.get_physical_lock_status()
976
def print_file(self, file, revision_id):
977
"""See Branch.print_file."""
978
return self.repository.print_file(file, revision_id)
981
def append_revision(self, *revision_ids):
982
"""See Branch.append_revision."""
983
for revision_id in revision_ids:
984
mutter("add {%s} to revision-history" % revision_id)
985
rev_history = self.revision_history()
986
rev_history.extend(revision_ids)
987
self.set_revision_history(rev_history)
990
def set_revision_history(self, rev_history):
991
"""See Branch.set_revision_history."""
992
self.control_files.put_utf8(
993
'revision-history', '\n'.join(rev_history))
994
transaction = self.get_transaction()
995
history = transaction.map.find_revision_history()
996
if history is not None:
997
# update the revision history in the identity map.
998
history[:] = list(rev_history)
999
# this call is disabled because revision_history is
1000
# not really an object yet, and the transaction is for objects.
1001
# transaction.register_dirty(history)
1003
transaction.map.add_revision_history(rev_history)
1004
# this call is disabled because revision_history is
1005
# not really an object yet, and the transaction is for objects.
1006
# transaction.register_clean(history)
1008
def get_revision_delta(self, revno):
1009
"""Return the delta for one revision.
1011
The delta is relative to its mainline predecessor, or the
1012
empty tree for revision 1.
1014
assert isinstance(revno, int)
1015
rh = self.revision_history()
1016
if not (1 <= revno <= len(rh)):
1017
raise InvalidRevisionNumber(revno)
1019
# revno is 1-based; list is 0-based
1021
new_tree = self.repository.revision_tree(rh[revno-1])
1023
old_tree = EmptyTree()
1025
old_tree = self.repository.revision_tree(rh[revno-2])
1026
return compare_trees(old_tree, new_tree)
1029
def revision_history(self):
1030
"""See Branch.revision_history."""
1031
transaction = self.get_transaction()
1032
history = transaction.map.find_revision_history()
1033
if history is not None:
1034
mutter("cache hit for revision-history in %s", self)
1035
return list(history)
1036
history = [l.rstrip('\r\n') for l in
1037
self.control_files.get_utf8('revision-history').readlines()]
1038
transaction.map.add_revision_history(history)
1039
# this call is disabled because revision_history is
1040
# not really an object yet, and the transaction is for objects.
1041
# transaction.register_clean(history, precious=True)
1042
return list(history)
1045
def update_revisions(self, other, stop_revision=None):
1046
"""See Branch.update_revisions."""
1049
if stop_revision is None:
1050
stop_revision = other.last_revision()
1051
if stop_revision is None:
1052
# if there are no commits, we're done.
1054
# whats the current last revision, before we fetch [and change it
1056
last_rev = self.last_revision()
1057
# we fetch here regardless of whether we need to so that we pickup
1059
self.fetch(other, stop_revision)
1060
my_ancestry = self.repository.get_ancestry(last_rev)
1061
if stop_revision in my_ancestry:
1062
# last_revision is a descendant of stop_revision
1064
# stop_revision must be a descendant of last_revision
1065
stop_graph = self.repository.get_revision_graph(stop_revision)
1066
if last_rev is not None and last_rev not in stop_graph:
1067
# our previous tip is not merged into stop_revision
1068
raise errors.DivergedBranches(self, other)
1069
# make a new revision history from the graph
1070
current_rev_id = stop_revision
1072
while current_rev_id not in (None, NULL_REVISION):
1073
new_history.append(current_rev_id)
1074
current_rev_id_parents = stop_graph[current_rev_id]
1076
current_rev_id = current_rev_id_parents[0]
1078
current_rev_id = None
1079
new_history.reverse()
1080
self.set_revision_history(new_history)
1084
@deprecated_method(zero_eight)
1085
def pullable_revisions(self, other, stop_revision):
1086
"""Please use bzrlib.missing instead."""
1087
other_revno = other.revision_id_to_revno(stop_revision)
1089
return self.missing_revisions(other, other_revno)
1090
except DivergedBranches, e:
1092
pullable_revs = get_intervening_revisions(self.last_revision(),
1095
assert self.last_revision() not in pullable_revs
1096
return pullable_revs
1097
except bzrlib.errors.NotAncestor:
1098
if is_ancestor(self.last_revision(), stop_revision, self):
1103
def basis_tree(self):
1104
"""See Branch.basis_tree."""
1105
return self.repository.revision_tree(self.last_revision())
1107
@deprecated_method(zero_eight)
1108
def working_tree(self):
1109
"""Create a Working tree object for this branch."""
1110
from bzrlib.workingtree import WorkingTree
1111
from bzrlib.transport.local import LocalTransport
1112
if (self.base.find('://') != -1 or
1113
not isinstance(self._transport, LocalTransport)):
1114
raise NoWorkingTree(self.base)
1115
return self.bzrdir.open_workingtree()
1118
def pull(self, source, overwrite=False, stop_revision=None):
1119
"""See Branch.pull."""
1122
old_count = len(self.revision_history())
1124
self.update_revisions(source,stop_revision)
1125
except DivergedBranches:
1129
self.set_revision_history(source.revision_history())
1130
new_count = len(self.revision_history())
1131
return new_count - old_count
1135
def get_parent(self):
1136
"""See Branch.get_parent."""
1138
_locs = ['parent', 'pull', 'x-pull']
1141
return self.control_files.get_utf8(l).read().strip('\n')
1146
def get_push_location(self):
1147
"""See Branch.get_push_location."""
1148
config = bzrlib.config.BranchConfig(self)
1149
push_loc = config.get_user_option('push_location')
1152
def set_push_location(self, location):
1153
"""See Branch.set_push_location."""
1154
config = bzrlib.config.LocationConfig(self.base)
1155
config.set_user_option('push_location', location)
1158
def set_parent(self, url):
1159
"""See Branch.set_parent."""
1160
# TODO: Maybe delete old location files?
1161
# URLs should never be unicode, even on the local fs,
1162
# FIXUP this and get_parent in a future branch format bump:
1163
# read and rewrite the file, and have the new format code read
1164
# using .get not .get_utf8. RBC 20060125
1166
self.control_files._transport.delete('parent')
1168
self.control_files.put_utf8('parent', url + '\n')
1170
def tree_config(self):
1171
return TreeConfig(self)
1174
class BzrBranch5(BzrBranch):
1175
"""A format 5 branch. This supports new features over plan branches.
1177
It has support for a master_branch which is the data for bound branches.
1185
super(BzrBranch5, self).__init__(_format=_format,
1186
_control_files=_control_files,
1188
_repository=_repository)
1191
def pull(self, source, overwrite=False, stop_revision=None):
1192
"""Updates branch.pull to be bound branch aware."""
1193
bound_location = self.get_bound_location()
1194
if source.base != bound_location:
1195
# not pulling from master, so we need to update master.
1196
master_branch = self.get_master_branch()
1198
master_branch.pull(source)
1199
source = master_branch
1200
return super(BzrBranch5, self).pull(source, overwrite, stop_revision)
1202
def get_bound_location(self):
1204
return self.control_files.get_utf8('bound').read()[:-1]
1205
except errors.NoSuchFile:
1209
def get_master_branch(self):
1210
"""Return the branch we are bound to.
1212
:return: Either a Branch, or None
1214
This could memoise the branch, but if thats done
1215
it must be revalidated on each new lock.
1216
So for now we just dont memoise it.
1217
# RBC 20060304 review this decision.
1219
bound_loc = self.get_bound_location()
1223
return Branch.open(bound_loc)
1224
except (errors.NotBranchError, errors.ConnectionError), e:
1225
raise errors.BoundBranchConnectionFailure(
1229
def set_bound_location(self, location):
1230
"""Set the target where this branch is bound to.
1232
:param location: URL to the target branch
1235
self.control_files.put_utf8('bound', location+'\n')
1238
self.control_files._transport.delete('bound')
1400
######################################################################
1404
def is_control_file(filename):
1405
## FIXME: better check
1406
filename = os.path.normpath(filename)
1407
while filename != '':
1408
head, tail = os.path.split(filename)
1409
## mutter('check %r for control file' % ((head, tail), ))
1410
if tail == bzrlib.BZRDIR:
1244
def bind(self, other):
1245
"""Bind the local branch the other branch.
1247
:param other: The branch to bind to
1250
# TODO: jam 20051230 Consider checking if the target is bound
1251
# It is debatable whether you should be able to bind to
1252
# a branch which is itself bound.
1253
# Committing is obviously forbidden,
1254
# but binding itself may not be.
1255
# Since we *have* to check at commit time, we don't
1256
# *need* to check here
1259
# we are now equal to or a suffix of other.
1261
# Since we have 'pulled' from the remote location,
1262
# now we should try to pull in the opposite direction
1263
# in case the local tree has more revisions than the
1265
# There may be a different check you could do here
1266
# rather than actually trying to install revisions remotely.
1267
# TODO: capture an exception which indicates the remote branch
1269
# If it is up-to-date, this probably should not be a failure
1271
# lock other for write so the revision-history syncing cannot race
1275
# if this does not error, other now has the same last rev we do
1276
# it can only error if the pull from other was concurrent with
1277
# a commit to other from someone else.
1279
# until we ditch revision-history, we need to sync them up:
1280
self.set_revision_history(other.revision_history())
1281
# now other and self are up to date with each other and have the
1282
# same revision-history.
1286
self.set_bound_location(other.base)
1290
"""If bound, unbind"""
1291
return self.set_bound_location(None)
1295
"""Synchronise this branch with the master branch if any.
1297
:return: None or the last_revision that was pivoted out during the
1300
master = self.get_master_branch()
1301
if master is not None:
1302
old_tip = self.last_revision()
1303
self.pull(master, overwrite=True)
1304
if old_tip in self.repository.get_ancestry(self.last_revision()):
1310
class BranchTestProviderAdapter(object):
1311
"""A tool to generate a suite testing multiple branch formats at once.
1313
This is done by copying the test once for each transport and injecting
1314
the transport_server, transport_readonly_server, and branch_format
1315
classes into each copy. Each copy is also given a new id() to make it
1319
def __init__(self, transport_server, transport_readonly_server, formats):
1320
self._transport_server = transport_server
1321
self._transport_readonly_server = transport_readonly_server
1322
self._formats = formats
1324
def adapt(self, test):
1325
result = TestSuite()
1326
for branch_format, bzrdir_format in self._formats:
1327
new_test = deepcopy(test)
1328
new_test.transport_server = self._transport_server
1329
new_test.transport_readonly_server = self._transport_readonly_server
1330
new_test.bzrdir_format = bzrdir_format
1331
new_test.branch_format = branch_format
1332
def make_new_test_id():
1333
new_id = "%s(%s)" % (new_test.id(), branch_format.__class__.__name__)
1334
return lambda: new_id
1335
new_test.id = make_new_test_id()
1336
result.addTest(new_test)
1340
######################################################################
1344
@deprecated_function(zero_eight)
1345
def ScratchBranch(*args, **kwargs):
1346
"""See bzrlib.bzrdir.ScratchDir."""
1347
d = ScratchDir(*args, **kwargs)
1348
return d.open_branch()
1351
@deprecated_function(zero_eight)
1352
def is_control_file(*args, **kwargs):
1353
"""See bzrlib.workingtree.is_control_file."""
1354
return bzrlib.workingtree.is_control_file(*args, **kwargs)
1412
if filename == head:
1419
def gen_file_id(name):
1420
"""Return new file id.
1422
This should probably generate proper UUIDs, but for the moment we
1423
cope with just randomness because running uuidgen every time is
1426
from binascii import hexlify
1427
from time import time
1429
# get last component
1430
idx = name.rfind('/')
1432
name = name[idx+1 : ]
1433
idx = name.rfind('\\')
1435
name = name[idx+1 : ]
1437
# make it not a hidden file
1438
name = name.lstrip('.')
1440
# remove any wierd characters; we don't escape them but rather
1441
# just pull them out
1442
name = re.sub(r'[^\w.]', '', name)
1444
s = hexlify(rand_bytes(8))
1445
return '-'.join((name, compact_date(time()), s))
1449
"""Return a new tree-root file id."""
1450
return gen_file_id('TREE_ROOT')