23
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
25
25
sha_file, appendpath, file_kind
27
26
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
28
27
import bzrlib.errors
29
28
from bzrlib.textui import show_status
30
29
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
33
from bzrlib.progress import ProgressBar
38
36
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
39
37
## TODO: Maybe include checks for common corruption of newlines, etc?
258
256
self._lock = None
259
257
self._lock_mode = self._lock_count = None
261
260
def abspath(self, name):
262
261
"""Return absolute filename for something in the branch"""
263
262
return os.path.join(self.base, name)
265
265
def relpath(self, path):
266
266
"""Return path relative to this branch of something inside it.
268
268
Raises an error if path is not in this branch."""
269
269
return _relpath(self.base, path)
271
272
def controlfilename(self, file_or_path):
272
273
"""Return location relative to branch."""
273
274
if isinstance(file_or_path, basestring):
336
339
# on Windows from Linux and so on. I think it might be better
337
340
# to always make all internal files in unix format.
338
341
fmt = self.controlfile('branch-format', 'r').read()
339
fmt = fmt.replace('\r\n', '\n')
342
fmt.replace('\r\n', '')
340
343
if fmt != BZR_BRANCH_FORMAT:
341
344
raise BzrError('sorry, branch format %r not supported' % fmt,
342
345
['use a different bzr version',
362
365
def read_working_inventory(self):
363
366
"""Read the working inventory."""
364
367
from bzrlib.inventory import Inventory
368
from bzrlib.xml import unpack_xml
369
from time import time
367
373
# ElementTree does its own conversion from UTF-8, so open in
369
f = self.controlfile('inventory', 'rb')
370
return bzrlib.xml.serializer_v4.read_inventory(f)
375
inv = unpack_xml(Inventory,
376
self.controlfile('inventory', 'rb'))
377
mutter("loaded inventory of %d items in %f"
378
% (len(inv), time() - before))
398
408
"""Inventory for the working copy.""")
401
def add(self, files, ids=None):
411
def add(self, files, verbose=False, ids=None):
402
412
"""Make files versioned.
404
Note that the command line normally calls smart_add instead,
405
which can automatically recurse.
414
Note that the command line normally calls smart_add instead.
407
416
This puts the files in the Added state, so that they will be
408
417
recorded by the next commit.
586
603
return self.revision_store[revision_id]
588
605
raise bzrlib.errors.NoSuchRevision(self, revision_id)
594
get_revision_xml = get_revision_xml_file
597
610
def get_revision(self, revision_id):
598
611
"""Return the Revision object for a named revision"""
599
xml_file = self.get_revision_xml_file(revision_id)
612
xml_file = self.get_revision_xml(revision_id)
602
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
615
r = unpack_xml(Revision, xml_file)
603
616
except SyntaxError, e:
604
617
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
650
663
parameter which can be either an integer revno or a
652
665
from bzrlib.inventory import Inventory
666
from bzrlib.xml import unpack_xml
654
f = self.get_inventory_xml_file(inventory_id)
655
return bzrlib.xml.serializer_v4.read_inventory(f)
668
return unpack_xml(Inventory, self.get_inventory_xml(inventory_id))
658
671
def get_inventory_xml(self, inventory_id):
659
672
"""Get inventory XML as a file object."""
660
673
return self.inventory_store[inventory_id]
662
get_inventory_xml_file = get_inventory_xml
665
676
def get_inventory_sha1(self, inventory_id):
796
807
if stop_revision is None:
797
808
stop_revision = other_len
798
809
elif stop_revision > other_len:
799
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
810
raise NoSuchRevision(self, stop_revision)
801
812
return other_history[self_len:stop_revision]
804
815
def update_revisions(self, other, stop_revision=None):
805
816
"""Pull in all new revisions from other branch.
818
>>> from bzrlib.commit import commit
819
>>> bzrlib.trace.silent = True
820
>>> br1 = ScratchBranch(files=['foo', 'bar'])
823
>>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
824
>>> br2 = ScratchBranch()
825
>>> br2.update_revisions(br1)
829
>>> br2.revision_history()
831
>>> br2.update_revisions(br1)
835
>>> br1.text_store.total_size() == br2.text_store.total_size()
807
from bzrlib.fetch import greedy_fetch
808
from bzrlib.revision import get_intervening_revisions
810
pb = bzrlib.ui.ui_factory.progress_bar()
811
839
pb.update('comparing histories')
812
if stop_revision is None:
813
other_revision = other.last_patch()
815
other_revision = other.lookup_revision(stop_revision)
816
count = greedy_fetch(self, other, other_revision, pb)[0]
818
revision_ids = self.missing_revisions(other, stop_revision)
819
except DivergedBranches, e:
821
revision_ids = get_intervening_revisions(self.last_patch(),
822
other_revision, self)
823
assert self.last_patch() not in revision_ids
824
except bzrlib.errors.NotAncestor:
840
revision_ids = self.missing_revisions(other, stop_revision)
841
count, failures = self.install_revisions(other, revision_ids, pb=pb)
827
842
self.append_revision(*revision_ids)
830
def install_revisions(self, other, revision_ids, pb):
843
print "Added %d revisions." % count
844
assert len(failures) == 0
846
def install_revisions(self, other, revision_ids, pb=None):
831
849
if hasattr(other.revision_store, "prefetch"):
832
850
other.revision_store.prefetch(revision_ids)
833
851
if hasattr(other.inventory_store, "prefetch"):
835
for rev_id in revision_ids:
837
revision = other.get_revision(rev_id).inventory_id
838
inventory_ids.append(revision)
839
except bzrlib.errors.NoSuchRevision:
852
inventory_ids = [other.get_revision(r).inventory_id
853
for r in revision_ids]
841
854
other.inventory_store.prefetch(inventory_ids)
844
pb = bzrlib.ui.ui_factory.progress_bar()
847
857
needed_texts = set()
851
860
for i, rev_id in enumerate(revision_ids):
852
861
pb.update('fetching revision', i+1, len(revision_ids))
869
877
count, cp_fail = self.text_store.copy_multi(other.text_store,
871
#print "Added %d texts." % count
879
print "Added %d texts." % count
872
880
inventory_ids = [ f.inventory_id for f in revisions ]
873
881
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
875
#print "Added %d inventories." % count
883
print "Added %d inventories." % count
876
884
revision_ids = [ f.revision_id for f in revisions]
878
885
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
880
887
permit_failure=True)
881
888
assert len(cp_fail) == 0
882
889
return count, failures
885
891
def commit(self, *args, **kw):
886
892
from bzrlib.commit import commit
887
893
commit(self, *args, **kw)
890
896
def lookup_revision(self, revision):
891
897
"""Return the revision identifier for a given revision information."""
892
revno, info = self._get_revision_info(revision)
898
revno, info = self.get_revision_info(revision)
896
def revision_id_to_revno(self, revision_id):
897
"""Given a revision id, return its revno"""
898
history = self.revision_history()
900
return history.index(revision_id) + 1
902
raise bzrlib.errors.NoSuchRevision(self, revision_id)
905
901
def get_revision_info(self, revision):
906
902
"""Return (revno, revision id) for revision identifier.
910
906
revision can also be a string, in which case it is parsed for something like
911
907
'date:' or 'revid:' etc.
913
revno, rev_id = self._get_revision_info(revision)
915
raise bzrlib.errors.NoSuchRevision(self, revision)
918
def get_rev_id(self, revno, history=None):
919
"""Find the revision id of the specified revno."""
923
history = self.revision_history()
924
elif revno <= 0 or revno > len(history):
925
raise bzrlib.errors.NoSuchRevision(self, revno)
926
return history[revno - 1]
928
def _get_revision_info(self, revision):
929
"""Return (revno, revision id) for revision specifier.
931
revision can be an integer, in which case it is assumed to be revno
932
(though this will translate negative values into positive ones)
933
revision can also be a string, in which case it is parsed for something
934
like 'date:' or 'revid:' etc.
936
A revid is always returned. If it is None, the specifier referred to
937
the null revision. If the revid does not occur in the revision
938
history, revno will be None.
941
909
if revision is None:
948
916
revs = self.revision_history()
949
917
if isinstance(revision, int):
920
# Mabye we should do this first, but we don't need it if revision == 0
951
922
revno = len(revs) + revision + 1
954
rev_id = self.get_rev_id(revno, revs)
955
925
elif isinstance(revision, basestring):
956
926
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
957
927
if revision.startswith(prefix):
958
result = func(self, revs, revision)
960
revno, rev_id = result
963
rev_id = self.get_rev_id(revno, revs)
928
revno = func(self, revs, revision)
966
raise BzrError('No namespace registered for string: %r' %
969
raise TypeError('Unhandled revision type %s' % revision)
931
raise BzrError('No namespace registered for string: %r' % revision)
973
raise bzrlib.errors.NoSuchRevision(self, revision)
933
if revno is None or revno <= 0 or revno > len(revs):
934
raise BzrError("no such revision %s" % revision)
935
return revno, revs[revno-1]
976
937
def _namespace_revno(self, revs, revision):
977
938
"""Lookup a revision by revision number"""
978
939
assert revision.startswith('revno:')
980
return (int(revision[6:]),)
941
return int(revision[6:])
981
942
except ValueError:
983
944
REVISION_NAMESPACES['revno:'] = _namespace_revno
985
946
def _namespace_revid(self, revs, revision):
986
947
assert revision.startswith('revid:')
987
rev_id = revision[len('revid:'):]
989
return revs.index(rev_id) + 1, rev_id
949
return revs.index(revision[6:]) + 1
990
950
except ValueError:
992
952
REVISION_NAMESPACES['revid:'] = _namespace_revid
994
954
def _namespace_last(self, revs, revision):
1081
1041
# TODO: Handle timezone.
1082
1042
dt = datetime.datetime.fromtimestamp(r.timestamp)
1083
1043
if first >= dt and (last is None or dt >= last):
1086
1046
for i in range(len(revs)):
1087
1047
r = self.get_revision(revs[i])
1088
1048
# TODO: Handle timezone.
1089
1049
dt = datetime.datetime.fromtimestamp(r.timestamp)
1090
1050
if first <= dt and (last is None or dt <= last):
1092
1052
REVISION_NAMESPACES['date:'] = _namespace_date
1095
def _namespace_ancestor(self, revs, revision):
1096
from revision import common_ancestor, MultipleRevisionSources
1097
other_branch = find_branch(_trim_namespace('ancestor', revision))
1098
revision_a = self.last_patch()
1099
revision_b = other_branch.last_patch()
1100
for r, b in ((revision_a, self), (revision_b, other_branch)):
1102
raise bzrlib.errors.NoCommits(b)
1103
revision_source = MultipleRevisionSources(self, other_branch)
1104
result = common_ancestor(revision_a, revision_b, revision_source)
1106
revno = self.revision_id_to_revno(result)
1107
except bzrlib.errors.NoSuchRevision:
1112
REVISION_NAMESPACES['ancestor:'] = _namespace_ancestor
1114
1054
def revision_tree(self, revision_id):
1115
1055
"""Return Tree for a revision on this branch.
1352
def get_parent(self):
1353
"""Return the parent location of the branch.
1355
This is the default location for push/pull/missing. The usual
1356
pattern is that the user can override it by specifying a
1360
_locs = ['parent', 'pull', 'x-pull']
1363
return self.controlfile(l, 'r').read().strip('\n')
1365
if e.errno != errno.ENOENT:
1370
def set_parent(self, url):
1371
# TODO: Maybe delete old location files?
1372
from bzrlib.atomicfile import AtomicFile
1375
f = AtomicFile(self.controlfilename('parent'))
1384
def check_revno(self, revno):
1386
Check whether a revno corresponds to any revision.
1387
Zero (the NULL revision) is considered valid.
1390
self.check_real_revno(revno)
1392
def check_real_revno(self, revno):
1394
Check whether a revno corresponds to a real revision.
1395
Zero (the NULL revision) is considered invalid
1397
if revno < 1 or revno > self.revno():
1398
raise InvalidRevisionNumber(revno)
1403
1289
class ScratchBranch(Branch):
1404
1290
"""Special test class: a branch that cleans up after itself.
1523
1407
"""Return a new tree-root file id."""
1524
1408
return gen_file_id('TREE_ROOT')
1527
def pull_loc(branch):
1528
# TODO: Should perhaps just make attribute be 'base' in
1529
# RemoteBranch and Branch?
1530
if hasattr(branch, "baseurl"):
1531
return branch.baseurl
1536
def copy_branch(branch_from, to_location, revision=None):
1537
"""Copy branch_from into the existing directory to_location.
1540
If not None, only revisions up to this point will be copied.
1541
The head of the new branch will be that revision.
1544
The name of a local directory that exists but is empty.
1546
from bzrlib.merge import merge
1547
from bzrlib.branch import Branch
1549
assert isinstance(branch_from, Branch)
1550
assert isinstance(to_location, basestring)
1552
br_to = Branch(to_location, init=True)
1553
br_to.set_root_id(branch_from.get_root_id())
1554
if revision is None:
1555
revno = branch_from.revno()
1557
revno, rev_id = branch_from.get_revision_info(revision)
1558
br_to.update_revisions(branch_from, stop_revision=revno)
1559
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1560
check_clean=False, ignore_zero=True)
1562
from_location = pull_loc(branch_from)
1563
br_to.set_parent(pull_loc(branch_from))
1566
def _trim_namespace(namespace, spec):
1567
full_namespace = namespace + ':'
1568
assert spec.startswith(full_namespace)
1569
return spec[len(full_namespace):]