15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
21
from bzrlib.trace import mutter, note
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
22
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, splitpath, \
25
23
sha_file, appendpath, file_kind
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
29
from bzrlib.textui import show_status
30
from bzrlib.revision import Revision
31
from bzrlib.delta import compare_trees
32
from bzrlib.tree import EmptyTree, RevisionTree
24
from bzrlib.errors import BzrError
38
26
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
39
27
## TODO: Maybe include checks for common corruption of newlines, etc?
42
# TODO: Some operations like log might retrieve the same revisions
43
# repeatedly to calculate deltas. We could perhaps have a weakref
44
# cache in memory to make this faster.
46
# TODO: please move the revision-string syntax stuff out of the branch
47
# object; it's clutter
50
31
def find_branch(f, **args):
51
32
if f and (f.startswith('http://') or f.startswith('https://')):
258
247
self._lock = None
259
248
self._lock_mode = self._lock_count = None
261
251
def abspath(self, name):
262
252
"""Return absolute filename for something in the branch"""
263
253
return os.path.join(self.base, name)
265
256
def relpath(self, path):
266
257
"""Return path relative to this branch of something inside it.
268
259
Raises an error if path is not in this branch."""
269
260
return _relpath(self.base, path)
271
263
def controlfilename(self, file_or_path):
272
264
"""Return location relative to branch."""
273
265
if isinstance(file_or_path, basestring):
362
353
def read_working_inventory(self):
363
354
"""Read the working inventory."""
364
355
from bzrlib.inventory import Inventory
356
from bzrlib.xml import unpack_xml
357
from time import time
367
361
# 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)
363
inv = unpack_xml(Inventory,
364
self.controlfile('inventory', 'rb'))
365
mutter("loaded inventory of %d items in %f"
366
% (len(inv), time() - before))
398
396
"""Inventory for the working copy.""")
401
def add(self, files, ids=None):
399
def add(self, files, verbose=False, ids=None):
402
400
"""Make files versioned.
404
Note that the command line normally calls smart_add instead,
405
which can automatically recurse.
402
Note that the command line normally calls smart_add instead.
407
404
This puts the files in the Added state, so that they will be
408
405
recorded by the next commit.
418
415
TODO: Perhaps have an option to add the ids even if the files do
421
TODO: Perhaps yield the ids and paths as they're added.
418
TODO: Perhaps return the ids of the files? But then again it
419
is easy to retrieve them if they're needed.
421
TODO: Adding a directory should optionally recurse down and
422
add all non-ignored children. Perhaps do that in a
425
from bzrlib.textui import show_status
423
426
# TODO: Re-adding a file that is removed in the working copy
424
427
# should probably put it back with the previous ID.
425
428
if isinstance(files, basestring):
578
def get_revision_xml_file(self, revision_id):
579
"""Return XML file object for revision object."""
580
if not revision_id or not isinstance(revision_id, basestring):
581
raise InvalidRevisionId(revision_id)
586
return self.revision_store[revision_id]
588
raise bzrlib.errors.NoSuchRevision(self, revision_id)
594
get_revision_xml = get_revision_xml_file
597
585
def get_revision(self, revision_id):
598
586
"""Return the Revision object for a named revision"""
599
xml_file = self.get_revision_xml_file(revision_id)
587
from bzrlib.revision import Revision
588
from bzrlib.xml import unpack_xml
602
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
603
except SyntaxError, e:
604
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
592
if not revision_id or not isinstance(revision_id, basestring):
593
raise ValueError('invalid revision-id: %r' % revision_id)
594
r = unpack_xml(Revision, self.revision_store[revision_id])
608
598
assert r.revision_id == revision_id
612
def get_revision_delta(self, revno):
613
"""Return the delta for one revision.
615
The delta is relative to its mainline predecessor, or the
616
empty tree for revision 1.
618
assert isinstance(revno, int)
619
rh = self.revision_history()
620
if not (1 <= revno <= len(rh)):
621
raise InvalidRevisionNumber(revno)
623
# revno is 1-based; list is 0-based
625
new_tree = self.revision_tree(rh[revno-1])
627
old_tree = EmptyTree()
629
old_tree = self.revision_tree(rh[revno-2])
631
return compare_trees(old_tree, new_tree)
635
602
def get_revision_sha1(self, revision_id):
650
617
parameter which can be either an integer revno or a
652
619
from bzrlib.inventory import Inventory
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
620
from bzrlib.xml import unpack_xml
622
return unpack_xml(Inventory, self.inventory_store[inventory_id])
665
625
def get_inventory_sha1(self, inventory_id):
666
626
"""Return the sha1 hash of the inventory entry
668
return sha_file(self.get_inventory_xml(inventory_id))
628
return sha_file(self.inventory_store[inventory_id])
671
631
def get_revision_inventory(self, revision_id):
737
697
return r+1, my_history[r]
738
698
return None, None
700
def enum_history(self, direction):
701
"""Return (revno, revision_id) for history of branch.
704
'forward' is from earliest to latest
705
'reverse' is from latest to earliest
707
rh = self.revision_history()
708
if direction == 'forward':
713
elif direction == 'reverse':
719
raise ValueError('invalid history direction', direction)
742
723
"""Return current revision number for this branch.
796
777
if stop_revision is None:
797
778
stop_revision = other_len
798
779
elif stop_revision > other_len:
799
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
780
raise NoSuchRevision(self, stop_revision)
801
782
return other_history[self_len:stop_revision]
804
785
def update_revisions(self, other, stop_revision=None):
805
786
"""Pull in all new revisions from other branch.
788
>>> from bzrlib.commit import commit
789
>>> bzrlib.trace.silent = True
790
>>> br1 = ScratchBranch(files=['foo', 'bar'])
793
>>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
794
>>> br2 = ScratchBranch()
795
>>> br2.update_revisions(br1)
799
>>> br2.revision_history()
801
>>> br2.update_revisions(br1)
805
>>> 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()
808
from bzrlib.progress import ProgressBar
812
from sets import Set as set
811
816
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:
827
self.append_revision(*revision_ids)
830
def install_revisions(self, other, revision_ids, pb):
817
revision_ids = self.missing_revisions(other, stop_revision)
831
819
if hasattr(other.revision_store, "prefetch"):
832
820
other.revision_store.prefetch(revision_ids)
833
821
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:
822
inventory_ids = [other.get_revision(r).inventory_id
823
for r in revision_ids]
841
824
other.inventory_store.prefetch(inventory_ids)
844
pb = bzrlib.ui.ui_factory.progress_bar()
847
827
needed_texts = set()
851
for i, rev_id in enumerate(revision_ids):
852
pb.update('fetching revision', i+1, len(revision_ids))
854
rev = other.get_revision(rev_id)
855
except bzrlib.errors.NoSuchRevision:
829
for rev_id in revision_ids:
831
pb.update('fetching revision', i, len(revision_ids))
832
rev = other.get_revision(rev_id)
859
833
revisions.append(rev)
860
834
inv = other.get_inventory(str(rev.inventory_id))
861
835
for key, entry in inv.iter_entries():
869
count, cp_fail = self.text_store.copy_multi(other.text_store,
871
#print "Added %d texts." % count
843
count = self.text_store.copy_multi(other.text_store, needed_texts)
844
print "Added %d texts." % count
872
845
inventory_ids = [ f.inventory_id for f in revisions ]
873
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
875
#print "Added %d inventories." % count
846
count = self.inventory_store.copy_multi(other.inventory_store,
848
print "Added %d inventories." % count
876
849
revision_ids = [ f.revision_id for f in revisions]
878
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
881
assert len(cp_fail) == 0
882
return count, failures
850
count = self.revision_store.copy_multi(other.revision_store,
852
for revision_id in revision_ids:
853
self.append_revision(revision_id)
854
print "Added %d revisions." % count
885
857
def commit(self, *args, **kw):
886
858
from bzrlib.commit import commit
887
859
commit(self, *args, **kw)
890
862
def lookup_revision(self, revision):
891
863
"""Return the revision identifier for a given revision information."""
892
revno, info = self._get_revision_info(revision)
864
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
867
def get_revision_info(self, revision):
906
868
"""Return (revno, revision id) for revision identifier.
910
872
revision can also be a string, in which case it is parsed for something like
911
873
'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
875
if revision is None:
948
882
revs = self.revision_history()
949
883
if isinstance(revision, int):
886
# Mabye we should do this first, but we don't need it if revision == 0
951
888
revno = len(revs) + revision + 1
954
rev_id = self.get_rev_id(revno, revs)
955
891
elif isinstance(revision, basestring):
956
892
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
957
893
if revision.startswith(prefix):
958
result = func(self, revs, revision)
960
revno, rev_id = result
963
rev_id = self.get_rev_id(revno, revs)
894
revno = func(self, revs, revision)
966
raise BzrError('No namespace registered for string: %r' %
969
raise TypeError('Unhandled revision type %s' % revision)
897
raise BzrError('No namespace registered for string: %r' % revision)
973
raise bzrlib.errors.NoSuchRevision(self, revision)
899
if revno is None or revno <= 0 or revno > len(revs):
900
raise BzrError("no such revision %s" % revision)
901
return revno, revs[revno-1]
976
903
def _namespace_revno(self, revs, revision):
977
904
"""Lookup a revision by revision number"""
978
905
assert revision.startswith('revno:')
980
return (int(revision[6:]),)
907
return int(revision[6:])
981
908
except ValueError:
983
910
REVISION_NAMESPACES['revno:'] = _namespace_revno
985
912
def _namespace_revid(self, revs, revision):
986
913
assert revision.startswith('revid:')
987
rev_id = revision[len('revid:'):]
989
return revs.index(rev_id) + 1, rev_id
915
return revs.index(revision[6:]) + 1
990
916
except ValueError:
992
918
REVISION_NAMESPACES['revid:'] = _namespace_revid
994
920
def _namespace_last(self, revs, revision):
1081
1007
# TODO: Handle timezone.
1082
1008
dt = datetime.datetime.fromtimestamp(r.timestamp)
1083
1009
if first >= dt and (last is None or dt >= last):
1086
1012
for i in range(len(revs)):
1087
1013
r = self.get_revision(revs[i])
1088
1014
# TODO: Handle timezone.
1089
1015
dt = datetime.datetime.fromtimestamp(r.timestamp)
1090
1016
if first <= dt and (last is None or dt <= last):
1092
1018
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
1020
def revision_tree(self, revision_id):
1115
1021
"""Return Tree for a revision on this branch.
1117
1023
`revision_id` may be None for the null revision, in which case
1118
1024
an `EmptyTree` is returned."""
1025
from bzrlib.tree import EmptyTree, RevisionTree
1119
1026
# TODO: refactor this to use an existing revision object
1120
1027
# so we don't need to read it in twice.
1121
1028
if revision_id == None:
1029
return EmptyTree(self.get_root_id())
1124
1031
inv = self.get_revision_inventory(revision_id)
1125
1032
return RevisionTree(self.text_store, inv)
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
1257
class ScratchBranch(Branch):
1404
1258
"""Special test class: a branch that cleans up after itself.
1523
1375
"""Return a new tree-root file id."""
1524
1376
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):]