23
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
25
25
sha_file, appendpath, file_kind
26
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
28
DivergedBranches, NotBranchError
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?
39
43
# repeatedly to calculate deltas. We could perhaps have a weakref
40
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
43
50
def find_branch(f, **args):
44
51
if f and (f.startswith('http://') or f.startswith('https://')):
46
return remotebranch.RemoteBranch(f, **args)
52
from bzrlib.remotebranch import RemoteBranch
53
return RemoteBranch(f, **args)
48
55
return Branch(f, **args)
51
58
def find_cached_branch(f, cache_root, **args):
52
from remotebranch import RemoteBranch
59
from bzrlib.remotebranch import RemoteBranch
53
60
br = find_branch(f, **args)
54
61
def cacheify(br, store_name):
55
from meta_store import CachedStore
62
from bzrlib.meta_store import CachedStore
56
63
cache_path = os.path.join(cache_root, store_name)
57
64
os.mkdir(cache_path)
58
65
new_store = CachedStore(getattr(br, store_name), cache_path)
120
127
head, tail = os.path.split(f)
122
129
# reached the root, whatever that may be
123
raise BzrError('%r is not in a branch' % orig_f)
130
raise NotBranchError('%s is not in a branch' % orig_f)
126
class DivergedBranches(Exception):
127
def __init__(self, branch1, branch2):
128
self.branch1 = branch1
129
self.branch2 = branch2
130
Exception.__init__(self, "These branches have diverged.")
133
136
######################################################################
182
185
self.base = find_branch_root(base)
187
if base.startswith("file://"):
184
189
self.base = os.path.realpath(base)
185
190
if not isdir(self.controlfilename('.')):
186
from errors import NotBranchError
187
191
raise NotBranchError("not a bzr branch: %s" % quotefn(base),
188
192
['use "bzr init" to initialize a new working tree',
189
193
'current bzr can only operate from top-of-tree'])
251
250
self._lock = None
252
251
self._lock_mode = self._lock_count = None
255
253
def abspath(self, name):
256
254
"""Return absolute filename for something in the branch"""
257
255
return os.path.join(self.base, name)
260
257
def relpath(self, path):
261
258
"""Return path relative to this branch of something inside it.
263
260
Raises an error if path is not in this branch."""
264
261
return _relpath(self.base, path)
267
263
def controlfilename(self, file_or_path):
268
264
"""Return location relative to branch."""
269
265
if isinstance(file_or_path, basestring):
316
309
self.controlfile(f, 'w').write('')
317
310
mutter('created control directory in ' + self.base)
319
pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
312
# if we want per-tree root ids then this is the place to set
313
# them; they're not needed for now and so ommitted for
315
f = self.controlfile('inventory','w')
316
bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
322
319
def _check_format(self):
331
328
# on Windows from Linux and so on. I think it might be better
332
329
# to always make all internal files in unix format.
333
330
fmt = self.controlfile('branch-format', 'r').read()
334
fmt.replace('\r\n', '')
331
fmt = fmt.replace('\r\n', '\n')
335
332
if fmt != BZR_BRANCH_FORMAT:
336
333
raise BzrError('sorry, branch format %r not supported' % fmt,
337
334
['use a different bzr version',
357
354
def read_working_inventory(self):
358
355
"""Read the working inventory."""
359
356
from bzrlib.inventory import Inventory
360
from bzrlib.xml import unpack_xml
361
from time import time
365
359
# 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))
361
f = self.controlfile('inventory', 'rb')
362
return bzrlib.xml.serializer_v4.read_inventory(f)
400
390
"""Inventory for the working copy.""")
403
def add(self, files, verbose=False, ids=None):
393
def add(self, files, ids=None):
404
394
"""Make files versioned.
406
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.
408
399
This puts the files in the Added state, so that they will be
409
400
recorded by the next commit.
595
578
return self.revision_store[revision_id]
596
579
except IndexError:
597
raise bzrlib.errors.NoSuchRevision(revision_id)
580
raise bzrlib.errors.NoSuchRevision(self, revision_id)
586
get_revision_xml = get_revision_xml_file
602
589
def get_revision(self, revision_id):
603
590
"""Return the Revision object for a named revision"""
604
xml_file = self.get_revision_xml(revision_id)
591
xml_file = self.get_revision_xml_file(revision_id)
607
r = unpack_xml(Revision, xml_file)
594
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
608
595
except SyntaxError, e:
609
596
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
655
642
parameter which can be either an integer revno or a
657
644
from bzrlib.inventory import Inventory
658
from bzrlib.xml import unpack_xml
660
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
663
657
def get_inventory_sha1(self, inventory_id):
664
658
"""Return the sha1 hash of the inventory entry
666
return sha_file(self.inventory_store[inventory_id])
660
return sha_file(self.get_inventory_xml(inventory_id))
669
663
def get_revision_inventory(self, revision_id):
694
688
def common_ancestor(self, other, self_revno=None, other_revno=None):
690
>>> from bzrlib.commit import commit
697
691
>>> sb = ScratchBranch(files=['foo', 'foo~'])
698
692
>>> sb.common_ancestor(sb) == (None, None)
700
>>> commit.commit(sb, "Committing first revision", verbose=False)
694
>>> commit(sb, "Committing first revision", verbose=False)
701
695
>>> sb.common_ancestor(sb)[0]
703
697
>>> clone = sb.clone()
704
>>> commit.commit(sb, "Committing second revision", verbose=False)
698
>>> commit(sb, "Committing second revision", verbose=False)
705
699
>>> sb.common_ancestor(sb)[0]
707
701
>>> sb.common_ancestor(clone)[0]
709
>>> commit.commit(clone, "Committing divergent second revision",
703
>>> commit(clone, "Committing divergent second revision",
710
704
... verbose=False)
711
705
>>> sb.common_ancestor(clone)[0]
794
788
if stop_revision is None:
795
789
stop_revision = other_len
796
790
elif stop_revision > other_len:
797
raise NoSuchRevision(self, stop_revision)
791
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
799
793
return other_history[self_len:stop_revision]
802
796
def update_revisions(self, other, stop_revision=None):
803
797
"""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
799
from bzrlib.fetch import greedy_fetch
800
from bzrlib.revision import get_intervening_revisions
802
pb = bzrlib.ui.ui_factory.progress_bar()
829
803
pb.update('comparing histories')
830
revision_ids = self.missing_revisions(other, stop_revision)
806
revision_ids = self.missing_revisions(other, stop_revision)
807
except DivergedBranches, e:
809
if stop_revision is None:
810
end_revision = other.last_patch()
811
revision_ids = get_intervening_revisions(self.last_patch(),
813
assert self.last_patch() not in revision_ids
814
except bzrlib.errors.NotAncestor:
817
if len(revision_ids) > 0:
818
count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
821
self.append_revision(*revision_ids)
822
## note("Added %d revisions." % count)
825
def install_revisions(self, other, revision_ids, pb):
832
826
if hasattr(other.revision_store, "prefetch"):
833
827
other.revision_store.prefetch(revision_ids)
834
828
if hasattr(other.inventory_store, "prefetch"):
835
829
inventory_ids = [other.get_revision(r).inventory_id
836
830
for r in revision_ids]
837
831
other.inventory_store.prefetch(inventory_ids)
834
pb = bzrlib.ui.ui_factory.progress_bar()
840
837
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)
841
for i, rev_id in enumerate(revision_ids):
842
pb.update('fetching revision', i+1, len(revision_ids))
844
rev = other.get_revision(rev_id)
845
except bzrlib.errors.NoSuchRevision:
846
849
revisions.append(rev)
847
850
inv = other.get_inventory(str(rev.inventory_id))
848
851
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
859
count, cp_fail = self.text_store.copy_multi(other.text_store,
861
#print "Added %d texts." % count
858
862
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
863
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
865
#print "Added %d inventories." % count
862
866
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
868
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
871
assert len(cp_fail) == 0
872
return count, failures
870
875
def commit(self, *args, **kw):
871
876
from bzrlib.commit import commit
872
877
commit(self, *args, **kw)
875
880
def lookup_revision(self, revision):
876
881
"""Return the revision identifier for a given revision information."""
877
revno, info = self.get_revision_info(revision)
882
revno, info = self._get_revision_info(revision)
886
def revision_id_to_revno(self, revision_id):
887
"""Given a revision id, return its revno"""
888
history = self.revision_history()
890
return history.index(revision_id) + 1
892
raise bzrlib.errors.NoSuchRevision(self, revision_id)
880
895
def get_revision_info(self, revision):
881
896
"""Return (revno, revision id) for revision identifier.
885
900
revision can also be a string, in which case it is parsed for something like
886
901
'date:' or 'revid:' etc.
903
revno, rev_id = self._get_revision_info(revision)
905
raise bzrlib.errors.NoSuchRevision(self, revision)
908
def get_rev_id(self, revno, history=None):
909
"""Find the revision id of the specified revno."""
913
history = self.revision_history()
914
elif revno <= 0 or revno > len(history):
915
raise bzrlib.errors.NoSuchRevision(self, revno)
916
return history[revno - 1]
918
def _get_revision_info(self, revision):
919
"""Return (revno, revision id) for revision specifier.
921
revision can be an integer, in which case it is assumed to be revno
922
(though this will translate negative values into positive ones)
923
revision can also be a string, in which case it is parsed for something
924
like 'date:' or 'revid:' etc.
926
A revid is always returned. If it is None, the specifier referred to
927
the null revision. If the revid does not occur in the revision
928
history, revno will be None.
888
931
if revision is None:
895
938
revs = self.revision_history()
896
939
if isinstance(revision, int):
899
# Mabye we should do this first, but we don't need it if revision == 0
901
941
revno = len(revs) + revision + 1
944
rev_id = self.get_rev_id(revno, revs)
904
945
elif isinstance(revision, basestring):
905
946
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
947
if revision.startswith(prefix):
907
revno = func(self, revs, revision)
948
result = func(self, revs, revision)
950
revno, rev_id = result
953
rev_id = self.get_rev_id(revno, revs)
910
raise BzrError('No namespace registered for string: %r' % revision)
956
raise BzrError('No namespace registered for string: %r' %
959
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]
963
raise bzrlib.errors.NoSuchRevision(self, revision)
916
966
def _namespace_revno(self, revs, revision):
917
967
"""Lookup a revision by revision number"""
918
968
assert revision.startswith('revno:')
920
return int(revision[6:])
970
return (int(revision[6:]),)
921
971
except ValueError:
923
973
REVISION_NAMESPACES['revno:'] = _namespace_revno
925
975
def _namespace_revid(self, revs, revision):
926
976
assert revision.startswith('revid:')
977
rev_id = revision[len('revid:'):]
928
return revs.index(revision[6:]) + 1
979
return revs.index(rev_id) + 1, rev_id
929
980
except ValueError:
931
982
REVISION_NAMESPACES['revid:'] = _namespace_revid
933
984
def _namespace_last(self, revs, revision):
1322
def get_parent(self):
1323
"""Return the parent location of the branch.
1325
This is the default location for push/pull/missing. The usual
1326
pattern is that the user can override it by specifying a
1330
_locs = ['parent', 'pull', 'x-pull']
1333
return self.controlfile(l, 'r').read().strip('\n')
1335
if e.errno != errno.ENOENT:
1340
def set_parent(self, url):
1341
# TODO: Maybe delete old location files?
1342
from bzrlib.atomicfile import AtomicFile
1345
f = AtomicFile(self.controlfilename('parent'))
1354
def check_revno(self, revno):
1356
Check whether a revno corresponds to any revision.
1357
Zero (the NULL revision) is considered valid.
1360
self.check_real_revno(revno)
1362
def check_real_revno(self, revno):
1364
Check whether a revno corresponds to a real revision.
1365
Zero (the NULL revision) is considered invalid
1367
if revno < 1 or revno > self.revno():
1368
raise InvalidRevisionNumber(revno)
1268
1373
class ScratchBranch(Branch):
1269
1374
"""Special test class: a branch that cleans up after itself.
1386
1493
"""Return a new tree-root file id."""
1387
1494
return gen_file_id('TREE_ROOT')
1497
def copy_branch(branch_from, to_location, revision=None):
1498
"""Copy branch_from into the existing directory to_location.
1501
If not None, only revisions up to this point will be copied.
1502
The head of the new branch will be that revision.
1505
The name of a local directory that exists but is empty.
1507
from bzrlib.merge import merge
1509
assert isinstance(branch_from, Branch)
1510
assert isinstance(to_location, basestring)
1512
br_to = Branch(to_location, init=True)
1513
br_to.set_root_id(branch_from.get_root_id())
1514
if revision is None:
1515
revno = branch_from.revno()
1517
revno, rev_id = branch_from.get_revision_info(revision)
1518
br_to.update_revisions(branch_from, stop_revision=revno)
1519
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1520
check_clean=False, ignore_zero=True)
1522
br_to.set_parent(branch_from.base)