23
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
25
25
sha_file, appendpath, file_kind
26
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
27
28
import bzrlib.errors
28
29
from bzrlib.textui import show_status
29
30
from bzrlib.revision import Revision
30
from bzrlib.xml import unpack_xml
31
31
from bzrlib.delta import compare_trees
32
32
from bzrlib.tree import EmptyTree, RevisionTree
34
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
35
39
## TODO: Maybe include checks for common corruption of newlines, etc?
251
258
self._lock = None
252
259
self._lock_mode = self._lock_count = None
255
261
def abspath(self, name):
256
262
"""Return absolute filename for something in the branch"""
257
263
return os.path.join(self.base, name)
260
265
def relpath(self, path):
261
266
"""Return path relative to this branch of something inside it.
263
268
Raises an error if path is not in this branch."""
264
269
return _relpath(self.base, path)
267
271
def controlfilename(self, file_or_path):
268
272
"""Return location relative to branch."""
269
273
if isinstance(file_or_path, basestring):
357
362
def read_working_inventory(self):
358
363
"""Read the working inventory."""
359
364
from bzrlib.inventory import Inventory
360
from bzrlib.xml import unpack_xml
361
from time import time
365
367
# ElementTree does its own conversion from UTF-8, so open in
367
inv = unpack_xml(Inventory,
368
self.controlfile('inventory', 'rb'))
369
mutter("loaded inventory of %d items in %f"
370
% (len(inv), time() - before))
369
f = self.controlfile('inventory', 'rb')
370
return bzrlib.xml.serializer_v4.read_inventory(f)
400
398
"""Inventory for the working copy.""")
403
def add(self, files, verbose=False, ids=None):
401
def add(self, files, ids=None):
404
402
"""Make files versioned.
406
Note that the command line normally calls smart_add instead.
404
Note that the command line normally calls smart_add instead,
405
which can automatically recurse.
408
407
This puts the files in the Added state, so that they will be
409
408
recorded by the next commit.
595
586
return self.revision_store[revision_id]
597
raise bzrlib.errors.NoSuchRevision(revision_id)
588
raise bzrlib.errors.NoSuchRevision(self, revision_id)
594
get_revision_xml = get_revision_xml_file
602
597
def get_revision(self, revision_id):
603
598
"""Return the Revision object for a named revision"""
604
xml_file = self.get_revision_xml(revision_id)
599
xml_file = self.get_revision_xml_file(revision_id)
607
r = unpack_xml(Revision, xml_file)
602
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
608
603
except SyntaxError, e:
609
604
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
655
650
parameter which can be either an integer revno or a
657
652
from bzrlib.inventory import Inventory
658
from bzrlib.xml import unpack_xml
660
return unpack_xml(Inventory, self.inventory_store[inventory_id])
654
f = self.get_inventory_xml_file(inventory_id)
655
return bzrlib.xml.serializer_v4.read_inventory(f)
658
def get_inventory_xml(self, inventory_id):
659
"""Get inventory XML as a file object."""
660
return self.inventory_store[inventory_id]
662
get_inventory_xml_file = get_inventory_xml
663
665
def get_inventory_sha1(self, inventory_id):
664
666
"""Return the sha1 hash of the inventory entry
666
return sha_file(self.inventory_store[inventory_id])
668
return sha_file(self.get_inventory_xml(inventory_id))
669
671
def get_revision_inventory(self, revision_id):
794
796
if stop_revision is None:
795
797
stop_revision = other_len
796
798
elif stop_revision > other_len:
797
raise NoSuchRevision(self, stop_revision)
799
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
799
801
return other_history[self_len:stop_revision]
802
804
def update_revisions(self, other, stop_revision=None):
803
805
"""Pull in all new revisions from other branch.
805
>>> from bzrlib.commit import commit
806
>>> bzrlib.trace.silent = True
807
>>> br1 = ScratchBranch(files=['foo', 'bar'])
810
>>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
811
>>> br2 = ScratchBranch()
812
>>> br2.update_revisions(br1)
816
>>> br2.revision_history()
818
>>> br2.update_revisions(br1)
822
>>> br1.text_store.total_size() == br2.text_store.total_size()
825
from bzrlib.progress import ProgressBar
807
from bzrlib.fetch import greedy_fetch
808
from bzrlib.revision import get_intervening_revisions
810
pb = bzrlib.ui.ui_factory.progress_bar()
829
811
pb.update('comparing histories')
830
revision_ids = self.missing_revisions(other, stop_revision)
814
revision_ids = self.missing_revisions(other, stop_revision)
815
except DivergedBranches, e:
817
if stop_revision is None:
818
end_revision = other.last_patch()
819
revision_ids = get_intervening_revisions(self.last_patch(),
821
assert self.last_patch() not in revision_ids
822
except bzrlib.errors.NotAncestor:
825
if len(revision_ids) > 0:
826
count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
829
self.append_revision(*revision_ids)
830
## note("Added %d revisions." % count)
833
def install_revisions(self, other, revision_ids, pb):
832
834
if hasattr(other.revision_store, "prefetch"):
833
835
other.revision_store.prefetch(revision_ids)
834
836
if hasattr(other.inventory_store, "prefetch"):
835
inventory_ids = [other.get_revision(r).inventory_id
836
for r in revision_ids]
838
for rev_id in revision_ids:
840
revision = other.get_revision(rev_id).inventory_id
841
inventory_ids.append(revision)
842
except bzrlib.errors.NoSuchRevision:
837
844
other.inventory_store.prefetch(inventory_ids)
847
pb = bzrlib.ui.ui_factory.progress_bar()
840
850
needed_texts = set()
842
for rev_id in revision_ids:
844
pb.update('fetching revision', i, len(revision_ids))
845
rev = other.get_revision(rev_id)
854
for i, rev_id in enumerate(revision_ids):
855
pb.update('fetching revision', i+1, len(revision_ids))
857
rev = other.get_revision(rev_id)
858
except bzrlib.errors.NoSuchRevision:
846
862
revisions.append(rev)
847
863
inv = other.get_inventory(str(rev.inventory_id))
848
864
for key, entry in inv.iter_entries():
856
count = self.text_store.copy_multi(other.text_store, needed_texts)
857
print "Added %d texts." % count
872
count, cp_fail = self.text_store.copy_multi(other.text_store,
874
#print "Added %d texts." % count
858
875
inventory_ids = [ f.inventory_id for f in revisions ]
859
count = self.inventory_store.copy_multi(other.inventory_store,
861
print "Added %d inventories." % count
876
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
878
#print "Added %d inventories." % count
862
879
revision_ids = [ f.revision_id for f in revisions]
863
count = self.revision_store.copy_multi(other.revision_store,
865
for revision_id in revision_ids:
866
self.append_revision(revision_id)
867
print "Added %d revisions." % count
881
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
884
assert len(cp_fail) == 0
885
return count, failures
870
888
def commit(self, *args, **kw):
871
889
from bzrlib.commit import commit
872
890
commit(self, *args, **kw)
875
893
def lookup_revision(self, revision):
876
894
"""Return the revision identifier for a given revision information."""
877
revno, info = self.get_revision_info(revision)
895
revno, info = self._get_revision_info(revision)
899
def revision_id_to_revno(self, revision_id):
900
"""Given a revision id, return its revno"""
901
history = self.revision_history()
903
return history.index(revision_id) + 1
905
raise bzrlib.errors.NoSuchRevision(self, revision_id)
880
908
def get_revision_info(self, revision):
881
909
"""Return (revno, revision id) for revision identifier.
885
913
revision can also be a string, in which case it is parsed for something like
886
914
'date:' or 'revid:' etc.
916
revno, rev_id = self._get_revision_info(revision)
918
raise bzrlib.errors.NoSuchRevision(self, revision)
921
def get_rev_id(self, revno, history=None):
922
"""Find the revision id of the specified revno."""
926
history = self.revision_history()
927
elif revno <= 0 or revno > len(history):
928
raise bzrlib.errors.NoSuchRevision(self, revno)
929
return history[revno - 1]
931
def _get_revision_info(self, revision):
932
"""Return (revno, revision id) for revision specifier.
934
revision can be an integer, in which case it is assumed to be revno
935
(though this will translate negative values into positive ones)
936
revision can also be a string, in which case it is parsed for something
937
like 'date:' or 'revid:' etc.
939
A revid is always returned. If it is None, the specifier referred to
940
the null revision. If the revid does not occur in the revision
941
history, revno will be None.
888
944
if revision is None:
895
951
revs = self.revision_history()
896
952
if isinstance(revision, int):
899
# Mabye we should do this first, but we don't need it if revision == 0
901
954
revno = len(revs) + revision + 1
957
rev_id = self.get_rev_id(revno, revs)
904
958
elif isinstance(revision, basestring):
905
959
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
960
if revision.startswith(prefix):
907
revno = func(self, revs, revision)
961
result = func(self, revs, revision)
963
revno, rev_id = result
966
rev_id = self.get_rev_id(revno, revs)
910
raise BzrError('No namespace registered for string: %r' % revision)
969
raise BzrError('No namespace registered for string: %r' %
972
raise TypeError('Unhandled revision type %s' % revision)
912
if revno is None or revno <= 0 or revno > len(revs):
913
raise BzrError("no such revision %s" % revision)
914
return revno, revs[revno-1]
976
raise bzrlib.errors.NoSuchRevision(self, revision)
916
979
def _namespace_revno(self, revs, revision):
917
980
"""Lookup a revision by revision number"""
918
981
assert revision.startswith('revno:')
920
return int(revision[6:])
983
return (int(revision[6:]),)
921
984
except ValueError:
923
986
REVISION_NAMESPACES['revno:'] = _namespace_revno
925
988
def _namespace_revid(self, revs, revision):
926
989
assert revision.startswith('revid:')
990
rev_id = revision[len('revid:'):]
928
return revs.index(revision[6:]) + 1
992
return revs.index(rev_id) + 1, rev_id
929
993
except ValueError:
931
995
REVISION_NAMESPACES['revid:'] = _namespace_revid
933
997
def _namespace_last(self, revs, revision):
1335
def get_parent(self):
1336
"""Return the parent location of the branch.
1338
This is the default location for push/pull/missing. The usual
1339
pattern is that the user can override it by specifying a
1343
_locs = ['parent', 'pull', 'x-pull']
1346
return self.controlfile(l, 'r').read().strip('\n')
1348
if e.errno != errno.ENOENT:
1353
def set_parent(self, url):
1354
# TODO: Maybe delete old location files?
1355
from bzrlib.atomicfile import AtomicFile
1358
f = AtomicFile(self.controlfilename('parent'))
1367
def check_revno(self, revno):
1369
Check whether a revno corresponds to any revision.
1370
Zero (the NULL revision) is considered valid.
1373
self.check_real_revno(revno)
1375
def check_real_revno(self, revno):
1377
Check whether a revno corresponds to a real revision.
1378
Zero (the NULL revision) is considered invalid
1380
if revno < 1 or revno > self.revno():
1381
raise InvalidRevisionNumber(revno)
1268
1386
class ScratchBranch(Branch):
1269
1387
"""Special test class: a branch that cleans up after itself.
1386
1506
"""Return a new tree-root file id."""
1387
1507
return gen_file_id('TREE_ROOT')
1510
def pull_loc(branch):
1511
# TODO: Should perhaps just make attribute be 'base' in
1512
# RemoteBranch and Branch?
1513
if hasattr(branch, "baseurl"):
1514
return branch.baseurl
1519
def copy_branch(branch_from, to_location, revision=None):
1520
"""Copy branch_from into the existing directory to_location.
1523
If not None, only revisions up to this point will be copied.
1524
The head of the new branch will be that revision.
1527
The name of a local directory that exists but is empty.
1529
from bzrlib.merge import merge
1530
from bzrlib.branch import Branch
1532
assert isinstance(branch_from, Branch)
1533
assert isinstance(to_location, basestring)
1535
br_to = Branch(to_location, init=True)
1536
br_to.set_root_id(branch_from.get_root_id())
1537
if revision is None:
1538
revno = branch_from.revno()
1540
revno, rev_id = branch_from.get_revision_info(revision)
1541
br_to.update_revisions(branch_from, stop_revision=revno)
1542
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1543
check_clean=False, ignore_zero=True)
1545
from_location = pull_loc(branch_from)
1546
br_to.set_parent(pull_loc(branch_from))