36
36
UnlistableBranch, NoSuchFile, NotVersionedError,
38
38
from bzrlib.textui import show_status
39
from bzrlib.revision import (Revision, is_ancestor, get_intervening_revisions,
39
from bzrlib.config import TreeConfig
40
from bzrlib.decorators import needs_read_lock, needs_write_lock
42
41
from bzrlib.delta import compare_trees
43
from bzrlib.tree import EmptyTree, RevisionTree
42
import bzrlib.inventory as inventory
44
43
from bzrlib.inventory import Inventory
44
from bzrlib.lockable_files import LockableFiles
45
from bzrlib.revision import (Revision, is_ancestor, get_intervening_revisions)
46
from bzrlib.repository import Repository
45
47
from bzrlib.store import copy_all
46
from bzrlib.store.text import TextStore
47
from bzrlib.store.weave import WeaveStore
48
from bzrlib.testament import Testament
49
48
import bzrlib.transactions as transactions
50
49
from bzrlib.transport import Transport, get_transport
50
from bzrlib.tree import EmptyTree, RevisionTree
53
from config import TreeConfig
56
55
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
57
56
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
58
57
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
59
## TODO: Maybe include checks for common corruption of newlines, etc?
60
# TODO: Maybe include checks for common corruption of newlines, etc?
62
62
# TODO: Some operations like log might retrieve the same revisions
63
63
# repeatedly to calculate deltas. We could perhaps have a weakref
64
64
# cache in memory to make this faster. In general anything can be
65
# cached in memory between lock and unlock operations.
67
def find_branch(*ignored, **ignored_too):
68
# XXX: leave this here for about one release, then remove it
69
raise NotImplementedError('find_branch() is not supported anymore, '
70
'please use one of the new branch constructors')
73
def needs_read_lock(unbound):
74
"""Decorate unbound to take out and release a read lock."""
75
def decorated(self, *args, **kwargs):
78
return unbound(self, *args, **kwargs)
84
def needs_write_lock(unbound):
85
"""Decorate unbound to take out and release a write lock."""
86
def decorated(self, *args, **kwargs):
89
return unbound(self, *args, **kwargs)
65
# cached in memory between lock and unlock operations. .. nb thats
66
# what the transaction identity map provides
94
69
######################################################################
194
167
raise NotImplementedError('abspath is abstract')
196
def controlfilename(self, file_or_path):
197
"""Return location relative to branch."""
198
raise NotImplementedError('controlfilename is abstract')
200
def controlfile(self, file_or_path, mode='r'):
201
"""Open a control file for this branch.
203
There are two classes of file in the control directory: text
204
and binary. binary files are untranslated byte streams. Text
205
control files are stored with Unix newlines and in UTF-8, even
206
if the platform or locale defaults are different.
208
Controlfiles should almost never be opened in write mode but
209
rather should be atomically copied and replaced using atomicfile.
211
raise NotImplementedError('controlfile is abstract')
213
def put_controlfile(self, path, f, encode=True):
214
"""Write an entry as a controlfile.
216
:param path: The path to put the file, relative to the .bzr control
218
:param f: A file-like or string object whose contents should be copied.
219
:param encode: If true, encode the contents as utf-8
221
raise NotImplementedError('put_controlfile is abstract')
223
def put_controlfiles(self, files, encode=True):
224
"""Write several entries as controlfiles.
226
:param files: A list of [(path, file)] pairs, where the path is the directory
227
underneath the bzr control directory
228
:param encode: If true, encode the contents as utf-8
230
raise NotImplementedError('put_controlfiles is abstract')
232
169
def get_root_id(self):
233
170
"""Return the id of this branches root"""
234
171
raise NotImplementedError('get_root_id is abstract')
236
def set_root_id(self, file_id):
237
raise NotImplementedError('set_root_id is abstract')
239
173
def print_file(self, file, revision_id):
240
174
"""Print `file` to stdout."""
241
175
raise NotImplementedError('print_file is abstract')
246
180
def set_revision_history(self, rev_history):
247
181
raise NotImplementedError('set_revision_history is abstract')
249
def has_revision(self, revision_id):
250
"""True if this branch has a copy of the revision.
252
This does not necessarily imply the revision is merge
253
or on the mainline."""
254
raise NotImplementedError('has_revision is abstract')
256
def get_revision_xml(self, revision_id):
257
raise NotImplementedError('get_revision_xml is abstract')
259
def get_revision(self, revision_id):
260
"""Return the Revision object for a named revision"""
261
raise NotImplementedError('get_revision is abstract')
263
def get_revision_delta(self, revno):
264
"""Return the delta for one revision.
266
The delta is relative to its mainline predecessor, or the
267
empty tree for revision 1.
269
assert isinstance(revno, int)
270
rh = self.revision_history()
271
if not (1 <= revno <= len(rh)):
272
raise InvalidRevisionNumber(revno)
274
# revno is 1-based; list is 0-based
276
new_tree = self.revision_tree(rh[revno-1])
278
old_tree = EmptyTree()
280
old_tree = self.revision_tree(rh[revno-2])
282
return compare_trees(old_tree, new_tree)
284
def get_revision_sha1(self, revision_id):
285
"""Hash the stored value of a revision, and return it."""
286
raise NotImplementedError('get_revision_sha1 is abstract')
288
def get_ancestry(self, revision_id):
289
"""Return a list of revision-ids integrated by a revision.
291
This currently returns a list, but the ordering is not guaranteed:
294
raise NotImplementedError('get_ancestry is abstract')
296
def get_inventory(self, revision_id):
297
"""Get Inventory object by hash."""
298
raise NotImplementedError('get_inventory is abstract')
300
def get_inventory_xml(self, revision_id):
301
"""Get inventory XML as a file object."""
302
raise NotImplementedError('get_inventory_xml is abstract')
304
def get_inventory_sha1(self, revision_id):
305
"""Return the sha1 hash of the inventory entry."""
306
raise NotImplementedError('get_inventory_sha1 is abstract')
308
def get_revision_inventory(self, revision_id):
309
"""Return inventory of a past revision."""
310
raise NotImplementedError('get_revision_inventory is abstract')
312
183
def revision_history(self):
313
184
"""Return sequence of revision hashes on to this branch."""
314
185
raise NotImplementedError('revision_history is abstract')
487
351
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
488
352
raise NotImplementedError('store_revision_signature is abstract')
354
def clone(self, to_location, revision=None, basis_branch=None, to_branch_type=None):
355
"""Copy this branch into the existing directory to_location.
357
Returns the newly created branch object.
360
If not None, only revisions up to this point will be copied.
361
The head of the new branch will be that revision. Must be a
364
to_location -- The destination directory; must either exist and be
365
empty, or not exist, in which case it is created.
368
A local branch to copy revisions from, related to this branch.
369
This is used when branching from a remote (slow) branch, and we have
370
a local branch that might contain some relevant revisions.
373
Branch type of destination branch
375
# circular import protection
376
from bzrlib.merge import build_working_dir
378
assert isinstance(to_location, basestring)
379
if not bzrlib.osutils.lexists(to_location):
380
os.mkdir(to_location)
381
if to_branch_type is None:
382
to_branch_type = BzrBranch
383
br_to = to_branch_type.initialize(to_location)
384
mutter("copy branch from %s to %s", self, br_to)
385
if basis_branch is not None:
386
basis_branch.push_stores(br_to)
387
br_to.working_tree().set_root_id(self.get_root_id())
389
revision = self.last_revision()
390
br_to.update_revisions(self, stop_revision=revision)
391
br_to.set_parent(self.base)
392
build_working_dir(to_location)
396
def fileid_involved_between_revs(self, from_revid, to_revid):
397
""" This function returns the file_id(s) involved in the
398
changes between the from_revid revision and the to_revid
401
raise NotImplementedError('fileid_involved_between_revs is abstract')
403
def fileid_involved(self, last_revid=None):
404
""" This function returns the file_id(s) involved in the
405
changes up to the revision last_revid
406
If no parametr is passed, then all file_id[s] present in the
407
repository are returned
409
raise NotImplementedError('fileid_involved is abstract')
411
def fileid_involved_by_set(self, changes):
412
""" This function returns the file_id(s) involved in the
413
changes present in the set 'changes'
415
raise NotImplementedError('fileid_involved_by_set is abstract')
417
def fileid_involved_between_revs(self, from_revid, to_revid):
418
""" This function returns the file_id(s) involved in the
419
changes between the from_revid revision and the to_revid
422
raise NotImplementedError('fileid_involved_between_revs is abstract')
424
def fileid_involved(self, last_revid=None):
425
""" This function returns the file_id(s) involved in the
426
changes up to the revision last_revid
427
If no parametr is passed, then all file_id[s] present in the
428
repository are returned
430
raise NotImplementedError('fileid_involved is abstract')
432
def fileid_involved_by_set(self, changes):
433
""" This function returns the file_id(s) involved in the
434
changes present in the set 'changes'
436
raise NotImplementedError('fileid_involved_by_set is abstract')
490
439
class BzrBranch(Branch):
491
440
"""A branch stored in the actual filesystem.
563
496
assert isinstance(transport, Transport), \
564
497
"%r is not a Transport" % transport
565
self._transport = transport
498
# TODO: jam 20060103 We create a clone of this transport at .bzr/
499
# and then we forget about it, should we keep a handle to it?
500
self._base = transport.base
501
self.control_files = LockableFiles(transport.clone(bzrlib.BZRDIR),
567
504
self._make_control()
568
505
self._check_format(relax_version_check)
571
def get_store(name, compressed=True, prefixed=False):
572
relpath = self._rel_controlfilename(unicode(name))
573
store = TextStore(self._transport.clone(relpath),
574
dir_mode=self._dir_mode,
575
file_mode=self._file_mode,
577
compressed=compressed)
580
def get_weave(name, prefixed=False):
581
relpath = self._rel_controlfilename(unicode(name))
582
ws = WeaveStore(self._transport.clone(relpath),
584
dir_mode=self._dir_mode,
585
file_mode=self._file_mode)
586
if self._transport.should_cache():
587
ws.enable_cache = True
590
if self._branch_format == 4:
591
self.inventory_store = get_store('inventory-store')
592
self.text_store = get_store('text-store')
593
self.revision_store = get_store('revision-store')
594
elif self._branch_format == 5:
595
self.control_weaves = get_weave(u'')
596
self.weave_store = get_weave(u'weaves')
597
self.revision_store = get_store(u'revision-store', compressed=False)
598
elif self._branch_format == 6:
599
self.control_weaves = get_weave(u'')
600
self.weave_store = get_weave(u'weaves', prefixed=True)
601
self.revision_store = get_store(u'revision-store', compressed=False,
603
self.revision_store.register_suffix('sig')
604
self._transaction = None
506
self.repository = Repository(transport, self._branch_format)
606
508
def __str__(self):
607
return '%s(%r)' % (self.__class__.__name__, self._transport.base)
509
return '%s(%r)' % (self.__class__.__name__, self.base)
609
511
__repr__ = __str__
611
513
def __del__(self):
612
if self._lock_mode or self._lock:
613
# XXX: This should show something every time, and be suitable for
614
# headless operation and embedding
615
warn("branch %r was not explicitly unlocked" % self)
618
514
# TODO: It might be best to do this somewhere else,
619
515
# but it is nice for a Branch object to automatically
620
516
# cache it's information.
621
517
# Alternatively, we could have the Transport objects cache requests
622
518
# See the earlier discussion about how major objects (like Branch)
623
519
# should never expect their __del__ function to run.
520
# XXX: cache_root seems to be unused, 2006-01-13 mbp
624
521
if hasattr(self, 'cache_root') and self.cache_root is not None:
626
523
shutil.rmtree(self.cache_root)
629
526
self.cache_root = None
631
528
def _get_base(self):
633
return self._transport.base
636
531
base = property(_get_base, doc="The URL for the root of this branch.")
638
533
def _finish_transaction(self):
639
534
"""Exit the current transaction."""
640
if self._transaction is None:
641
raise errors.LockError('Branch %s is not in a transaction' %
643
transaction = self._transaction
644
self._transaction = None
535
return self.control_files._finish_transaction()
647
537
def get_transaction(self):
648
"""See Branch.get_transaction."""
649
if self._transaction is None:
650
return transactions.PassThroughTransaction()
652
return self._transaction
654
def _set_transaction(self, new_transaction):
538
"""Return the current active transaction.
540
If no transaction is active, this returns a passthrough object
541
for which all data is immediately flushed and no caching happens.
543
# this is an explicit function so that we can do tricky stuff
544
# when the storage in rev_storage is elsewhere.
545
# we probably need to hook the two 'lock a location' and
546
# 'have a transaction' together more delicately, so that
547
# we can have two locks (branch and storage) and one transaction
548
# ... and finishing the transaction unlocks both, but unlocking
549
# does not. - RBC 20051121
550
return self.control_files.get_transaction()
552
def _set_transaction(self, transaction):
655
553
"""Set a new active transaction."""
656
if self._transaction is not None:
657
raise errors.LockError('Branch %s is in a transaction already.' %
659
self._transaction = new_transaction
661
def lock_write(self):
662
#mutter("lock write: %s (%s)", self, self._lock_count)
663
# TODO: Upgrade locking to support using a Transport,
664
# and potentially a remote locking protocol
666
if self._lock_mode != 'w':
667
raise LockError("can't upgrade to a write lock from %r" %
669
self._lock_count += 1
671
self._lock = self._transport.lock_write(
672
self._rel_controlfilename('branch-lock'))
673
self._lock_mode = 'w'
675
self._set_transaction(transactions.PassThroughTransaction())
678
#mutter("lock read: %s (%s)", self, self._lock_count)
680
assert self._lock_mode in ('r', 'w'), \
681
"invalid lock mode %r" % self._lock_mode
682
self._lock_count += 1
684
self._lock = self._transport.lock_read(
685
self._rel_controlfilename('branch-lock'))
686
self._lock_mode = 'r'
688
self._set_transaction(transactions.ReadOnlyTransaction())
689
# 5K may be excessive, but hey, its a knob.
690
self.get_transaction().set_cache_size(5000)
693
#mutter("unlock: %s (%s)", self, self._lock_count)
694
if not self._lock_mode:
695
raise LockError('branch %r is not locked' % (self))
697
if self._lock_count > 1:
698
self._lock_count -= 1
700
self._finish_transaction()
703
self._lock_mode = self._lock_count = None
554
return self.control_files._set_transaction(transaction)
705
556
def abspath(self, name):
706
557
"""See Branch.abspath."""
707
return self._transport.abspath(name)
709
def _rel_controlfilename(self, file_or_path):
710
if not isinstance(file_or_path, basestring):
711
file_or_path = u'/'.join(file_or_path)
712
if file_or_path == '':
714
return bzrlib.transport.urlescape(bzrlib.BZRDIR + u'/' + file_or_path)
716
def controlfilename(self, file_or_path):
717
"""See Branch.controlfilename."""
718
return self._transport.abspath(self._rel_controlfilename(file_or_path))
720
def controlfile(self, file_or_path, mode='r'):
721
"""See Branch.controlfile."""
724
relpath = self._rel_controlfilename(file_or_path)
725
#TODO: codecs.open() buffers linewise, so it was overloaded with
726
# a much larger buffer, do we need to do the same for getreader/getwriter?
728
return self._transport.get(relpath)
730
raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
732
# XXX: Do we really want errors='replace'? Perhaps it should be
733
# an error, or at least reported, if there's incorrectly-encoded
734
# data inside a file.
735
# <https://launchpad.net/products/bzr/+bug/3823>
736
return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
738
raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
740
raise BzrError("invalid controlfile mode %r" % mode)
742
def put_controlfile(self, path, f, encode=True):
743
"""See Branch.put_controlfile."""
744
self.put_controlfiles([(path, f)], encode=encode)
746
def put_controlfiles(self, files, encode=True):
747
"""See Branch.put_controlfiles."""
750
for path, f in files:
752
if isinstance(f, basestring):
753
f = f.encode('utf-8', 'replace')
755
f = codecs.getwriter('utf-8')(f, errors='replace')
756
path = self._rel_controlfilename(path)
757
ctrl_files.append((path, f))
758
self._transport.put_multi(ctrl_files, mode=self._file_mode)
760
def _find_modes(self, path=None):
761
"""Determine the appropriate modes for files and directories."""
764
path = self._rel_controlfilename('')
765
st = self._transport.stat(path)
766
except errors.TransportNotPossible:
767
self._dir_mode = 0755
768
self._file_mode = 0644
770
self._dir_mode = st.st_mode & 07777
771
# Remove the sticky and execute bits for files
772
self._file_mode = self._dir_mode & ~07111
773
if not self._set_dir_mode:
774
self._dir_mode = None
775
if not self._set_file_mode:
776
self._file_mode = None
558
return self.control_files._transport.abspath(name)
778
560
def _make_control(self):
779
561
from bzrlib.inventory import Inventory
845
630
def get_root_id(self):
846
631
"""See Branch.get_root_id."""
847
inv = self.get_inventory(self.last_revision())
632
inv = self.repository.get_inventory(self.last_revision())
848
633
return inv.root.file_id
635
def lock_write(self):
636
# TODO: test for failed two phase locks. This is known broken.
637
self.control_files.lock_write()
638
self.repository.lock_write()
641
# TODO: test for failed two phase locks. This is known broken.
642
self.control_files.lock_read()
643
self.repository.lock_read()
646
# TODO: test for failed two phase locks. This is known broken.
647
self.repository.unlock()
648
self.control_files.unlock()
650
def peek_lock_mode(self):
651
if self.control_files._lock_count == 0:
654
return self.control_files._lock_mode
851
657
def print_file(self, file, revision_id):
852
658
"""See Branch.print_file."""
853
tree = self.revision_tree(revision_id)
854
# use inventory as it was in that revision
855
file_id = tree.inventory.path2id(file)
858
revno = self.revision_id_to_revno(revision_id)
859
except errors.NoSuchRevision:
860
# TODO: This should not be BzrError,
861
# but NoSuchFile doesn't fit either
862
raise BzrError('%r is not present in revision %s'
863
% (file, revision_id))
865
raise BzrError('%r is not present in revision %s'
867
tree.print_file(file_id)
659
return self.repository.print_file(file, revision_id)
869
661
@needs_write_lock
870
662
def append_revision(self, *revision_ids):
880
672
"""See Branch.set_revision_history."""
881
673
old_revision = self.last_revision()
882
674
new_revision = rev_history[-1]
883
self.put_controlfile('revision-history', '\n'.join(rev_history))
675
self.control_files.put_utf8(
676
'revision-history', '\n'.join(rev_history))
678
# FIXME: RBC 20051207 this smells wrong, last_revision in the
679
# working tree may be != to last_revision in the branch - so
680
# why is this passing in the branches last_revision ?
885
681
self.working_tree().set_last_revision(new_revision, old_revision)
886
682
except NoWorkingTree:
887
683
mutter('Unable to set_last_revision without a working tree.')
889
def has_revision(self, revision_id):
890
"""See Branch.has_revision."""
891
return (revision_id is None
892
or self.revision_store.has_id(revision_id))
895
def _get_revision_xml_file(self, revision_id):
896
if not revision_id or not isinstance(revision_id, basestring):
897
raise InvalidRevisionId(revision_id=revision_id, branch=self)
899
return self.revision_store.get(revision_id)
900
except (IndexError, KeyError):
901
raise bzrlib.errors.NoSuchRevision(self, revision_id)
903
def get_revision_xml(self, revision_id):
904
"""See Branch.get_revision_xml."""
905
return self._get_revision_xml_file(revision_id).read()
907
def get_revision(self, revision_id):
908
"""See Branch.get_revision."""
909
xml_file = self._get_revision_xml_file(revision_id)
912
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
913
except SyntaxError, e:
914
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
918
assert r.revision_id == revision_id
921
def get_revision_sha1(self, revision_id):
922
"""See Branch.get_revision_sha1."""
923
# In the future, revision entries will be signed. At that
924
# point, it is probably best *not* to include the signature
925
# in the revision hash. Because that lets you re-sign
926
# the revision, (add signatures/remove signatures) and still
927
# have all hash pointers stay consistent.
928
# But for now, just hash the contents.
929
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
931
def get_ancestry(self, revision_id):
932
"""See Branch.get_ancestry."""
933
if revision_id is None:
935
w = self._get_inventory_weave()
936
return [None] + map(w.idx_to_name,
937
w.inclusions([w.lookup(revision_id)]))
939
def _get_inventory_weave(self):
940
return self.control_weaves.get_weave('inventory',
941
self.get_transaction())
943
def get_inventory(self, revision_id):
944
"""See Branch.get_inventory."""
945
xml = self.get_inventory_xml(revision_id)
946
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
948
def get_inventory_xml(self, revision_id):
949
"""See Branch.get_inventory_xml."""
951
assert isinstance(revision_id, basestring), type(revision_id)
952
iw = self._get_inventory_weave()
953
return iw.get_text(iw.lookup(revision_id))
955
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
957
def get_inventory_sha1(self, revision_id):
958
"""See Branch.get_inventory_sha1."""
959
return self.get_revision(revision_id).inventory_sha1
961
def get_revision_inventory(self, revision_id):
962
"""See Branch.get_revision_inventory."""
963
# TODO: Unify this with get_inventory()
964
# bzr 0.0.6 and later imposes the constraint that the inventory_id
965
# must be the same as its revision, so this is trivial.
966
if revision_id == None:
967
# This does not make sense: if there is no revision,
968
# then it is the current tree inventory surely ?!
969
# and thus get_root_id() is something that looks at the last
970
# commit on the branch, and the get_root_id is an inventory check.
971
raise NotImplementedError
972
# return Inventory(self.get_root_id())
685
def get_revision_delta(self, revno):
686
"""Return the delta for one revision.
688
The delta is relative to its mainline predecessor, or the
689
empty tree for revision 1.
691
assert isinstance(revno, int)
692
rh = self.revision_history()
693
if not (1 <= revno <= len(rh)):
694
raise InvalidRevisionNumber(revno)
696
# revno is 1-based; list is 0-based
698
new_tree = self.repository.revision_tree(rh[revno-1])
700
old_tree = EmptyTree()
974
return self.get_inventory(revision_id)
702
old_tree = self.repository.revision_tree(rh[revno-2])
703
return compare_trees(old_tree, new_tree)
977
706
def revision_history(self):
978
707
"""See Branch.revision_history."""
708
# FIXME are transactions bound to control files ? RBC 20051121
979
709
transaction = self.get_transaction()
980
710
history = transaction.map.find_revision_history()
981
711
if history is not None:
982
712
mutter("cache hit for revision-history in %s", self)
983
713
return list(history)
984
714
history = [l.rstrip('\r\n') for l in
985
self.controlfile('revision-history', 'r').readlines()]
715
self.control_files.get_utf8('revision-history').readlines()]
986
716
transaction.map.add_revision_history(history)
987
717
# this call is disabled because revision_history is
988
718
# not really an object yet, and the transaction is for objects.
1024
def revision_tree(self, revision_id):
1025
"""See Branch.revision_tree."""
1026
# TODO: refactor this to use an existing revision object
1027
# so we don't need to read it in twice.
1028
if revision_id == None or revision_id == NULL_REVISION:
1031
inv = self.get_revision_inventory(revision_id)
1032
return RevisionTree(self, inv, revision_id)
1034
755
def basis_tree(self):
1035
756
"""See Branch.basis_tree."""
1037
758
revision_id = self.revision_history()[-1]
759
# FIXME: This is an abstraction violation, the basis tree
760
# here as defined is on the working tree, the method should
761
# be too. The basis tree for a branch can be different than
762
# that for a working tree. RBC 20051207
1038
763
xml = self.working_tree().read_basis_inventory(revision_id)
1039
764
inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
1040
return RevisionTree(self, inv, revision_id)
765
return RevisionTree(self.repository, inv, revision_id)
1041
766
except (IndexError, NoSuchFile, NoWorkingTree), e:
1042
return self.revision_tree(self.last_revision())
767
return self.repository.revision_tree(self.last_revision())
1044
769
def working_tree(self):
1045
770
"""See Branch.working_tree."""
1046
771
from bzrlib.workingtree import WorkingTree
1047
if self._transport.base.find('://') != -1:
772
if self.base.find('://') != -1:
1048
773
raise NoWorkingTree(self.base)
1049
774
return WorkingTree(self.base, branch=self)
1092
817
def set_parent(self, url):
1093
818
"""See Branch.set_parent."""
1094
819
# TODO: Maybe delete old location files?
1095
from bzrlib.atomicfile import AtomicFile
1096
f = AtomicFile(self.controlfilename('parent'), encoding='utf-8')
820
# URLs should never be unicode, even on the local fs,
821
# FIXUP this and get_parent in a future branch format bump:
822
# read and rewrite the file, and have the new format code read
823
# using .get not .get_utf8. RBC 20060125
824
self.control_files.put_utf8('parent', url + '\n')
1103
826
def tree_config(self):
1104
827
return TreeConfig(self)
1106
def sign_revision(self, revision_id, gpg_strategy):
1107
"""See Branch.sign_revision."""
1108
plaintext = Testament.from_revision(self, revision_id).as_short_text()
1109
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
1112
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1113
"""See Branch.store_revision_signature."""
1114
self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)),
829
def _get_truncated_history(self, revision_id):
830
history = self.revision_history()
831
if revision_id is None:
834
idx = history.index(revision_id)
836
raise InvalidRevisionId(revision_id=revision, branch=self)
837
return history[:idx+1]
840
def _clone_weave(self, to_location, revision=None, basis_branch=None):
841
assert isinstance(to_location, basestring)
842
if basis_branch is not None:
843
note("basis_branch is not supported for fast weave copy yet.")
845
history = self._get_truncated_history(revision)
846
if not bzrlib.osutils.lexists(to_location):
847
os.mkdir(to_location)
848
branch_to = Branch.initialize(to_location)
849
mutter("copy branch from %s to %s", self, branch_to)
850
branch_to.working_tree().set_root_id(self.get_root_id())
852
self.repository.copy(branch_to.repository)
854
# must be done *after* history is copied across
855
# FIXME duplicate code with base .clone().
856
# .. would template method be useful here. RBC 20051207
857
branch_to.set_parent(self.base)
858
branch_to.append_revision(*history)
859
# circular import protection
860
from bzrlib.merge import build_working_dir
861
build_working_dir(to_location)
865
def clone(self, to_location, revision=None, basis_branch=None, to_branch_type=None):
866
if to_branch_type is None:
867
to_branch_type = BzrBranch
869
if to_branch_type == BzrBranch \
870
and self.repository.weave_store.listable() \
871
and self.repository.revision_store.listable():
872
return self._clone_weave(to_location, revision, basis_branch)
874
return Branch.clone(self, to_location, revision, basis_branch, to_branch_type)
876
def fileid_involved_between_revs(self, from_revid, to_revid):
877
"""Find file_id(s) which are involved in the changes between revisions.
879
This determines the set of revisions which are involved, and then
880
finds all file ids affected by those revisions.
882
# TODO: jam 20060119 This code assumes that w.inclusions will
883
# always be correct. But because of the presence of ghosts
884
# it is possible to be wrong.
885
# One specific example from Robert Collins:
886
# Two branches, with revisions ABC, and AD
887
# C is a ghost merge of D.
888
# Inclusions doesn't recognize D as an ancestor.
889
# If D is ever merged in the future, the weave
890
# won't be fixed, because AD never saw revision C
891
# to cause a conflict which would force a reweave.
892
w = self.repository.get_inventory_weave()
893
from_set = set(w.inclusions([w.lookup(from_revid)]))
894
to_set = set(w.inclusions([w.lookup(to_revid)]))
895
included = to_set.difference(from_set)
896
changed = map(w.idx_to_name, included)
897
return self._fileid_involved_by_set(changed)
899
def fileid_involved(self, last_revid=None):
900
"""Find all file_ids modified in the ancestry of last_revid.
902
:param last_revid: If None, last_revision() will be used.
904
w = self.repository.get_inventory_weave()
906
changed = set(w._names)
908
included = w.inclusions([w.lookup(last_revid)])
909
changed = map(w.idx_to_name, included)
910
return self._fileid_involved_by_set(changed)
912
def fileid_involved_by_set(self, changes):
913
"""Find all file_ids modified by the set of revisions passed in.
915
:param changes: A set() of revision ids
917
# TODO: jam 20060119 This line does *nothing*, remove it.
918
# or better yet, change _fileid_involved_by_set so
919
# that it takes the inventory weave, rather than
920
# pulling it out by itself.
921
w = self.repository.get_inventory_weave()
922
return self._fileid_involved_by_set(changes)
924
def _fileid_involved_by_set(self, changes):
925
"""Find the set of file-ids affected by the set of revisions.
927
:param changes: A set() of revision ids.
928
:return: A set() of file ids.
930
This peaks at the Weave, interpreting each line, looking to
931
see if it mentions one of the revisions. And if so, includes
932
the file id mentioned.
933
This expects both the Weave format, and the serialization
934
to have a single line per file/directory, and to have
935
fileid="" and revision="" on that line.
937
assert self._branch_format in (5, 6), \
938
"fileid_involved only supported for branches which store inventory as xml"
940
w = self.repository.get_inventory_weave()
942
for line in w._weave:
944
# it is ugly, but it is due to the weave structure
945
if not isinstance(line, basestring): continue
947
start = line.find('file_id="')+9
948
if start < 9: continue
949
end = line.find('"', start)
951
file_id = xml.sax.saxutils.unescape(line[start:end])
953
# check if file_id is already present
954
if file_id in file_ids: continue
956
start = line.find('revision="')+10
957
if start < 10: continue
958
end = line.find('"', start)
960
revision_id = xml.sax.saxutils.unescape(line[start:end])
962
if revision_id in changes:
963
file_ids.add(file_id)
1118
968
class ScratchBranch(BzrBranch):