15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22
from bzrlib.trace import mutter, note
22
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, splitpath, \
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
23
25
sha_file, appendpath, file_kind
24
from bzrlib.errors import BzrError
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
28
DivergedBranches, NotBranchError
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
26
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
27
39
## 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
31
50
def find_branch(f, **args):
32
51
if f and (f.startswith('http://') or f.startswith('https://')):
34
return remotebranch.RemoteBranch(f, **args)
52
from bzrlib.remotebranch import RemoteBranch
53
return RemoteBranch(f, **args)
36
55
return Branch(f, **args)
39
58
def find_cached_branch(f, cache_root, **args):
40
from remotebranch import RemoteBranch
59
from bzrlib.remotebranch import RemoteBranch
41
60
br = find_branch(f, **args)
42
61
def cacheify(br, store_name):
43
from meta_store import CachedStore
62
from bzrlib.meta_store import CachedStore
44
63
cache_path = os.path.join(cache_root, store_name)
45
64
os.mkdir(cache_path)
46
65
new_store = CachedStore(getattr(br, store_name), cache_path)
108
127
head, tail = os.path.split(f)
110
129
# reached the root, whatever that may be
111
raise BzrError('%r is not in a branch' % orig_f)
130
raise NotBranchError('%s is not in a branch' % orig_f)
114
class DivergedBranches(Exception):
115
def __init__(self, branch1, branch2):
116
self.branch1 = branch1
117
self.branch2 = branch2
118
Exception.__init__(self, "These branches have diverged.")
121
class NoSuchRevision(BzrError):
122
def __init__(self, branch, revision):
124
self.revision = revision
125
msg = "Branch %s has no revision %d" % (branch, revision)
126
BzrError.__init__(self, msg)
129
136
######################################################################
247
250
self._lock = None
248
251
self._lock_mode = self._lock_count = None
251
253
def abspath(self, name):
252
254
"""Return absolute filename for something in the branch"""
253
255
return os.path.join(self.base, name)
256
257
def relpath(self, path):
257
258
"""Return path relative to this branch of something inside it.
259
260
Raises an error if path is not in this branch."""
260
261
return _relpath(self.base, path)
263
263
def controlfilename(self, file_or_path):
264
264
"""Return location relative to branch."""
265
265
if isinstance(file_or_path, basestring):
353
354
def read_working_inventory(self):
354
355
"""Read the working inventory."""
355
356
from bzrlib.inventory import Inventory
356
from bzrlib.xml import unpack_xml
357
from time import time
361
359
# ElementTree does its own conversion from UTF-8, so open in
363
inv = unpack_xml(Inventory,
364
self.controlfile('inventory', 'rb'))
365
mutter("loaded inventory of %d items in %f"
366
% (len(inv), time() - before))
361
f = self.controlfile('inventory', 'rb')
362
return bzrlib.xml.serializer_v4.read_inventory(f)
396
390
"""Inventory for the working copy.""")
399
def add(self, files, verbose=False, ids=None):
393
def add(self, files, ids=None):
400
394
"""Make files versioned.
402
Note that the command line normally calls smart_add instead.
396
Note that the command line normally calls smart_add instead,
397
which can automatically recurse.
404
399
This puts the files in the Added state, so that they will be
405
400
recorded by the next commit.
415
410
TODO: Perhaps have an option to add the ids even if the files do
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
413
TODO: Perhaps yield the ids and paths as they're added.
425
from bzrlib.textui import show_status
426
415
# TODO: Re-adding a file that is removed in the working copy
427
416
# should probably put it back with the previous ID.
428
417
if isinstance(files, basestring):
570
def get_revision_xml_file(self, revision_id):
571
"""Return XML file object for revision object."""
572
if not revision_id or not isinstance(revision_id, basestring):
573
raise InvalidRevisionId(revision_id)
578
return self.revision_store[revision_id]
580
raise bzrlib.errors.NoSuchRevision(self, revision_id)
586
get_revision_xml = get_revision_xml_file
585
589
def get_revision(self, revision_id):
586
590
"""Return the Revision object for a named revision"""
587
from bzrlib.revision import Revision
588
from bzrlib.xml import unpack_xml
591
xml_file = self.get_revision_xml_file(revision_id)
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])
594
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
595
except SyntaxError, e:
596
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
598
600
assert r.revision_id == revision_id
604
def get_revision_delta(self, revno):
605
"""Return the delta for one revision.
607
The delta is relative to its mainline predecessor, or the
608
empty tree for revision 1.
610
assert isinstance(revno, int)
611
rh = self.revision_history()
612
if not (1 <= revno <= len(rh)):
613
raise InvalidRevisionNumber(revno)
615
# revno is 1-based; list is 0-based
617
new_tree = self.revision_tree(rh[revno-1])
619
old_tree = EmptyTree()
621
old_tree = self.revision_tree(rh[revno-2])
623
return compare_trees(old_tree, new_tree)
602
627
def get_revision_sha1(self, revision_id):
617
642
parameter which can be either an integer revno or a
619
644
from bzrlib.inventory import Inventory
620
from bzrlib.xml import unpack_xml
622
return unpack_xml(Inventory, self.inventory_store[inventory_id])
646
f = self.get_inventory_xml_file(inventory_id)
647
return bzrlib.xml.serializer_v4.read_inventory(f)
650
def get_inventory_xml(self, inventory_id):
651
"""Get inventory XML as a file object."""
652
return self.inventory_store[inventory_id]
654
get_inventory_xml_file = get_inventory_xml
625
657
def get_inventory_sha1(self, inventory_id):
626
658
"""Return the sha1 hash of the inventory entry
628
return sha_file(self.inventory_store[inventory_id])
660
return sha_file(self.get_inventory_xml(inventory_id))
631
663
def get_revision_inventory(self, revision_id):
656
688
def common_ancestor(self, other, self_revno=None, other_revno=None):
690
>>> from bzrlib.commit import commit
659
691
>>> sb = ScratchBranch(files=['foo', 'foo~'])
660
692
>>> sb.common_ancestor(sb) == (None, None)
662
>>> commit.commit(sb, "Committing first revision", verbose=False)
694
>>> commit(sb, "Committing first revision", verbose=False)
663
695
>>> sb.common_ancestor(sb)[0]
665
697
>>> clone = sb.clone()
666
>>> commit.commit(sb, "Committing second revision", verbose=False)
698
>>> commit(sb, "Committing second revision", verbose=False)
667
699
>>> sb.common_ancestor(sb)[0]
669
701
>>> sb.common_ancestor(clone)[0]
671
>>> commit.commit(clone, "Committing divergent second revision",
703
>>> commit(clone, "Committing divergent second revision",
672
704
... verbose=False)
673
705
>>> sb.common_ancestor(clone)[0]
697
729
return r+1, my_history[r]
698
730
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)
723
734
"""Return current revision number for this branch.
777
788
if stop_revision is None:
778
789
stop_revision = other_len
779
790
elif stop_revision > other_len:
780
raise NoSuchRevision(self, stop_revision)
791
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
782
793
return other_history[self_len:stop_revision]
785
796
def update_revisions(self, other, stop_revision=None):
786
797
"""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()
808
from bzrlib.progress import ProgressBar
799
from bzrlib.fetch import greedy_fetch
800
from bzrlib.revision import get_intervening_revisions
802
pb = bzrlib.ui.ui_factory.progress_bar()
812
803
pb.update('comparing histories')
813
revision_ids = self.missing_revisions(other, stop_revision)
804
if stop_revision is None:
805
other_revision = other.last_patch()
807
other_revision = other.lookup_revision(stop_revision)
808
count = greedy_fetch(self, other, other_revision, pb)[0]
810
revision_ids = self.missing_revisions(other, stop_revision)
811
except DivergedBranches, e:
813
revision_ids = get_intervening_revisions(self.last_patch(),
814
other_revision, self)
815
assert self.last_patch() not in revision_ids
816
except bzrlib.errors.NotAncestor:
819
self.append_revision(*revision_ids)
822
def install_revisions(self, other, revision_ids, pb):
815
823
if hasattr(other.revision_store, "prefetch"):
816
824
other.revision_store.prefetch(revision_ids)
817
825
if hasattr(other.inventory_store, "prefetch"):
818
inventory_ids = [other.get_revision(r).inventory_id
819
for r in revision_ids]
827
for rev_id in revision_ids:
829
revision = other.get_revision(rev_id).inventory_id
830
inventory_ids.append(revision)
831
except bzrlib.errors.NoSuchRevision:
820
833
other.inventory_store.prefetch(inventory_ids)
836
pb = bzrlib.ui.ui_factory.progress_bar()
823
839
needed_texts = set()
825
for rev_id in revision_ids:
827
pb.update('fetching revision', i, len(revision_ids))
828
rev = other.get_revision(rev_id)
843
for i, rev_id in enumerate(revision_ids):
844
pb.update('fetching revision', i+1, len(revision_ids))
846
rev = other.get_revision(rev_id)
847
except bzrlib.errors.NoSuchRevision:
829
851
revisions.append(rev)
830
852
inv = other.get_inventory(str(rev.inventory_id))
831
853
for key, entry in inv.iter_entries():
839
count = self.text_store.copy_multi(other.text_store, needed_texts)
840
print "Added %d texts." % count
861
count, cp_fail = self.text_store.copy_multi(other.text_store,
863
#print "Added %d texts." % count
841
864
inventory_ids = [ f.inventory_id for f in revisions ]
842
count = self.inventory_store.copy_multi(other.inventory_store,
844
print "Added %d inventories." % count
865
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
867
#print "Added %d inventories." % count
845
868
revision_ids = [ f.revision_id for f in revisions]
846
count = self.revision_store.copy_multi(other.revision_store,
848
for revision_id in revision_ids:
849
self.append_revision(revision_id)
850
print "Added %d revisions." % count
870
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
873
assert len(cp_fail) == 0
874
return count, failures
853
877
def commit(self, *args, **kw):
854
878
from bzrlib.commit import commit
855
879
commit(self, *args, **kw)
858
882
def lookup_revision(self, revision):
859
883
"""Return the revision identifier for a given revision information."""
860
revno, info = self.get_revision_info(revision)
884
revno, info = self._get_revision_info(revision)
888
def revision_id_to_revno(self, revision_id):
889
"""Given a revision id, return its revno"""
890
history = self.revision_history()
892
return history.index(revision_id) + 1
894
raise bzrlib.errors.NoSuchRevision(self, revision_id)
863
897
def get_revision_info(self, revision):
864
898
"""Return (revno, revision id) for revision identifier.
868
902
revision can also be a string, in which case it is parsed for something like
869
903
'date:' or 'revid:' etc.
905
revno, rev_id = self._get_revision_info(revision)
907
raise bzrlib.errors.NoSuchRevision(self, revision)
910
def get_rev_id(self, revno, history=None):
911
"""Find the revision id of the specified revno."""
915
history = self.revision_history()
916
elif revno <= 0 or revno > len(history):
917
raise bzrlib.errors.NoSuchRevision(self, revno)
918
return history[revno - 1]
920
def _get_revision_info(self, revision):
921
"""Return (revno, revision id) for revision specifier.
923
revision can be an integer, in which case it is assumed to be revno
924
(though this will translate negative values into positive ones)
925
revision can also be a string, in which case it is parsed for something
926
like 'date:' or 'revid:' etc.
928
A revid is always returned. If it is None, the specifier referred to
929
the null revision. If the revid does not occur in the revision
930
history, revno will be None.
871
933
if revision is None:
878
940
revs = self.revision_history()
879
941
if isinstance(revision, int):
882
# Mabye we should do this first, but we don't need it if revision == 0
884
943
revno = len(revs) + revision + 1
946
rev_id = self.get_rev_id(revno, revs)
887
947
elif isinstance(revision, basestring):
888
948
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
889
949
if revision.startswith(prefix):
890
revno = func(self, revs, revision)
950
result = func(self, revs, revision)
952
revno, rev_id = result
955
rev_id = self.get_rev_id(revno, revs)
893
raise BzrError('No namespace registered for string: %r' % revision)
958
raise BzrError('No namespace registered for string: %r' %
961
raise TypeError('Unhandled revision type %s' % revision)
895
if revno is None or revno <= 0 or revno > len(revs):
896
raise BzrError("no such revision %s" % revision)
897
return revno, revs[revno-1]
965
raise bzrlib.errors.NoSuchRevision(self, revision)
899
968
def _namespace_revno(self, revs, revision):
900
969
"""Lookup a revision by revision number"""
901
970
assert revision.startswith('revno:')
903
return int(revision[6:])
972
return (int(revision[6:]),)
904
973
except ValueError:
906
975
REVISION_NAMESPACES['revno:'] = _namespace_revno
908
977
def _namespace_revid(self, revs, revision):
909
978
assert revision.startswith('revid:')
979
rev_id = revision[len('revid:'):]
911
return revs.index(revision[6:]) + 1
981
return revs.index(rev_id) + 1, rev_id
912
982
except ValueError:
914
984
REVISION_NAMESPACES['revid:'] = _namespace_revid
916
986
def _namespace_last(self, revs, revision):
1003
1073
# TODO: Handle timezone.
1004
1074
dt = datetime.datetime.fromtimestamp(r.timestamp)
1005
1075
if first >= dt and (last is None or dt >= last):
1008
1078
for i in range(len(revs)):
1009
1079
r = self.get_revision(revs[i])
1010
1080
# TODO: Handle timezone.
1011
1081
dt = datetime.datetime.fromtimestamp(r.timestamp)
1012
1082
if first <= dt and (last is None or dt <= last):
1014
1084
REVISION_NAMESPACES['date:'] = _namespace_date
1087
def _namespace_ancestor(self, revs, revision):
1088
from revision import common_ancestor, MultipleRevisionSources
1089
other_branch = find_branch(_trim_namespace('ancestor', revision))
1090
revision_a = self.last_patch()
1091
revision_b = other_branch.last_patch()
1092
for r, b in ((revision_a, self), (revision_b, other_branch)):
1094
raise bzrlib.errors.NoCommits(b)
1095
revision_source = MultipleRevisionSources(self, other_branch)
1096
result = common_ancestor(revision_a, revision_b, revision_source)
1098
revno = self.revision_id_to_revno(result)
1099
except bzrlib.errors.NoSuchRevision:
1104
REVISION_NAMESPACES['ancestor:'] = _namespace_ancestor
1016
1106
def revision_tree(self, revision_id):
1017
1107
"""Return Tree for a revision on this branch.
1019
1109
`revision_id` may be None for the null revision, in which case
1020
1110
an `EmptyTree` is returned."""
1021
from bzrlib.tree import EmptyTree, RevisionTree
1022
1111
# TODO: refactor this to use an existing revision object
1023
1112
# so we don't need to read it in twice.
1024
1113
if revision_id == None:
1025
return EmptyTree(self.get_root_id())
1027
1116
inv = self.get_revision_inventory(revision_id)
1028
1117
return RevisionTree(self.text_store, inv)
1344
def get_parent(self):
1345
"""Return the parent location of the branch.
1347
This is the default location for push/pull/missing. The usual
1348
pattern is that the user can override it by specifying a
1352
_locs = ['parent', 'pull', 'x-pull']
1355
return self.controlfile(l, 'r').read().strip('\n')
1357
if e.errno != errno.ENOENT:
1362
def set_parent(self, url):
1363
# TODO: Maybe delete old location files?
1364
from bzrlib.atomicfile import AtomicFile
1367
f = AtomicFile(self.controlfilename('parent'))
1376
def check_revno(self, revno):
1378
Check whether a revno corresponds to any revision.
1379
Zero (the NULL revision) is considered valid.
1382
self.check_real_revno(revno)
1384
def check_real_revno(self, revno):
1386
Check whether a revno corresponds to a real revision.
1387
Zero (the NULL revision) is considered invalid
1389
if revno < 1 or revno > self.revno():
1390
raise InvalidRevisionNumber(revno)
1253
1395
class ScratchBranch(Branch):
1254
1396
"""Special test class: a branch that cleans up after itself.
1371
1515
"""Return a new tree-root file id."""
1372
1516
return gen_file_id('TREE_ROOT')
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
1531
assert isinstance(branch_from, Branch)
1532
assert isinstance(to_location, basestring)
1534
br_to = Branch(to_location, init=True)
1535
br_to.set_root_id(branch_from.get_root_id())
1536
if revision is None:
1537
revno = branch_from.revno()
1539
revno, rev_id = branch_from.get_revision_info(revision)
1540
br_to.update_revisions(branch_from, stop_revision=revno)
1541
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1542
check_clean=False, ignore_zero=True)
1543
br_to.set_parent(branch_from.base)
1546
def _trim_namespace(namespace, spec):
1547
full_namespace = namespace + ':'
1548
assert spec.startswith(full_namespace)
1549
return spec[len(full_namespace):]