26
25
sha_file, appendpath, file_kind
28
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
30
29
from bzrlib.textui import show_status
31
30
from bzrlib.revision import Revision
31
from bzrlib.xml import unpack_xml
32
32
from bzrlib.delta import compare_trees
33
33
from bzrlib.tree import EmptyTree, RevisionTree
34
from bzrlib.inventory import Inventory
35
from bzrlib.weavestore import WeaveStore
36
from bzrlib.store import ImmutableStore
41
INVENTORY_FILEID = '__inventory'
42
ANCESTRY_FILEID = '__ancestry'
45
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
46
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
47
39
## TODO: Maybe include checks for common corruption of newlines, etc?
50
42
# TODO: Some operations like log might retrieve the same revisions
51
43
# repeatedly to calculate deltas. We could perhaps have a weakref
52
# cache in memory to make this faster. In general anything can be
53
# cached in memory between lock and unlock operations.
44
# cache in memory to make this faster.
55
46
# TODO: please move the revision-string syntax stuff out of the branch
56
47
# object; it's clutter
266
262
self._lock = None
267
263
self._lock_mode = self._lock_count = None
269
266
def abspath(self, name):
270
267
"""Return absolute filename for something in the branch"""
271
268
return os.path.join(self.base, name)
273
271
def relpath(self, path):
274
272
"""Return path relative to this branch of something inside it.
276
274
Raises an error if path is not in this branch."""
277
275
return _relpath(self.base, path)
279
278
def controlfilename(self, file_or_path):
280
279
"""Return location relative to branch."""
281
280
if isinstance(file_or_path, basestring):
309
308
raise BzrError("invalid controlfile mode %r" % mode)
311
312
def _make_control(self):
313
from bzrlib.inventory import Inventory
314
from bzrlib.xml import pack_xml
312
316
os.mkdir(self.controlfilename([]))
313
317
self.controlfile('README', 'w').write(
314
318
"This is a Bazaar-NG control directory.\n"
315
319
"Do not change any files in this directory.\n")
316
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT_5)
317
for d in ('text-store', 'revision-store',
320
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
321
for d in ('text-store', 'inventory-store', 'revision-store'):
319
322
os.mkdir(self.controlfilename(d))
320
323
for f in ('revision-history', 'merged-patches',
321
324
'pending-merged-patches', 'branch-name',
327
330
# if we want per-tree root ids then this is the place to set
328
331
# them; they're not needed for now and so ommitted for
330
f = self.controlfile('inventory','w')
331
bzrlib.xml5.serializer_v5.write_inventory(Inventory(), f)
333
pack_xml(Inventory(), self.controlfile('inventory','w'))
335
336
def _check_format(self):
336
337
"""Check this branch format is supported.
338
The format level is stored, as an integer, in
339
self._branch_format for code that needs to check it later.
339
The current tool only supports the current unstable format.
341
341
In the future, we might need different in-memory Branch
342
342
classes to support downlevel branches. But not yet.
344
# This ignores newlines so that we can open branches created
345
# on Windows from Linux and so on. I think it might be better
346
# to always make all internal files in unix format.
344
347
fmt = self.controlfile('branch-format', 'r').read()
345
if fmt == BZR_BRANCH_FORMAT_5:
346
self._branch_format = 5
348
raise BzrError('sorry, branch format "%s" not supported; '
349
'use a different bzr version, '
350
'or run "bzr upgrade", '
351
'or remove the .bzr directory and "bzr init" again'
352
% fmt.rstrip('\n\r'))
348
fmt.replace('\r\n', '')
349
if fmt != BZR_BRANCH_FORMAT:
350
raise BzrError('sorry, branch format %r not supported' % fmt,
351
['use a different bzr version',
352
'or remove the .bzr directory and "bzr init" again'])
354
354
def get_root_id(self):
355
355
"""Return the id of this branches root"""
371
371
def read_working_inventory(self):
372
372
"""Read the working inventory."""
373
from bzrlib.inventory import Inventory
374
from bzrlib.xml import unpack_xml
375
from time import time
375
379
# ElementTree does its own conversion from UTF-8, so open in
377
f = self.controlfile('inventory', 'rb')
378
return bzrlib.xml5.serializer_v5.read_inventory(f)
381
inv = unpack_xml(Inventory,
382
self.controlfile('inventory', 'rb'))
383
mutter("loaded inventory of %d items in %f"
384
% (len(inv), time() - before))
406
414
"""Inventory for the working copy.""")
409
def add(self, files, ids=None):
417
def add(self, files, verbose=False, ids=None):
410
418
"""Make files versioned.
412
Note that the command line normally calls smart_add instead,
413
which can automatically recurse.
420
Note that the command line normally calls smart_add instead.
415
422
This puts the files in the Added state, so that they will be
416
423
recorded by the next commit.
601
def get_revision_xml(self, revision_id):
602
return self.get_revision_xml_file(revision_id).read()
605
616
def get_revision(self, revision_id):
606
617
"""Return the Revision object for a named revision"""
607
xml_file = self.get_revision_xml_file(revision_id)
618
xml_file = self.get_revision_xml(revision_id)
610
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
621
r = unpack_xml(Revision, xml_file)
611
622
except SyntaxError, e:
612
623
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
643
654
def get_revision_sha1(self, revision_id):
644
655
"""Hash the stored value of a revision, and return it."""
645
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
648
def get_ancestry(self, revision_id):
649
"""Return a list of revision-ids integrated by a revision.
651
w = self.weave_store.get_weave(ANCESTRY_FILEID)
653
return [l[:-1] for l in w.get_iter(w.lookup(revision_id))]
656
def get_inventory_weave(self):
657
return self.weave_store.get_weave(INVENTORY_FILEID)
660
def get_inventory(self, revision_id):
661
"""Get Inventory object by hash."""
662
# FIXME: The text gets passed around a lot coming from the weave.
663
f = StringIO(self.get_inventory_xml(revision_id))
664
return bzrlib.xml5.serializer_v5.read_inventory(f)
667
def get_inventory_xml(self, revision_id):
656
# In the future, revision entries will be signed. At that
657
# point, it is probably best *not* to include the signature
658
# in the revision hash. Because that lets you re-sign
659
# the revision, (add signatures/remove signatures) and still
660
# have all hash pointers stay consistent.
661
# But for now, just hash the contents.
662
return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
665
def get_inventory(self, inventory_id):
666
"""Get Inventory object by hash.
668
TODO: Perhaps for this and similar methods, take a revision
669
parameter which can be either an integer revno or a
671
from bzrlib.inventory import Inventory
672
from bzrlib.xml import unpack_xml
674
return unpack_xml(Inventory, self.get_inventory_xml(inventory_id))
677
def get_inventory_xml(self, inventory_id):
668
678
"""Get inventory XML as a file object."""
670
assert isinstance(revision_id, basestring), type(revision_id)
671
iw = self.get_inventory_weave()
672
return iw.get_text(iw.lookup(revision_id))
674
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
677
def get_inventory_sha1(self, revision_id):
679
return self.inventory_store[inventory_id]
682
def get_inventory_sha1(self, inventory_id):
678
683
"""Return the sha1 hash of the inventory entry
680
return self.get_revision(revision_id).inventory_sha1
685
return sha_file(self.get_inventory_xml(inventory_id))
683
688
def get_revision_inventory(self, revision_id):
684
689
"""Return inventory of a past revision."""
685
# bzr 0.0.6 and later imposes the constraint that the inventory_id
690
# bzr 0.0.6 imposes the constraint that the inventory_id
686
691
# must be the same as its revision, so this is trivial.
687
692
if revision_id == None:
693
from bzrlib.inventory import Inventory
688
694
return Inventory(self.get_root_id())
690
696
return self.get_inventory(revision_id)
710
716
>>> sb = ScratchBranch(files=['foo', 'foo~'])
711
717
>>> sb.common_ancestor(sb) == (None, None)
713
>>> commit.commit(sb, "Committing first revision")
719
>>> commit.commit(sb, "Committing first revision", verbose=False)
714
720
>>> sb.common_ancestor(sb)[0]
716
722
>>> clone = sb.clone()
717
>>> commit.commit(sb, "Committing second revision")
723
>>> commit.commit(sb, "Committing second revision", verbose=False)
718
724
>>> sb.common_ancestor(sb)[0]
720
726
>>> sb.common_ancestor(clone)[0]
722
>>> commit.commit(clone, "Committing divergent second revision")
728
>>> commit.commit(clone, "Committing divergent second revision",
723
730
>>> sb.common_ancestor(clone)[0]
725
732
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
828
835
self.append_revision(*revision_ids)
829
836
## note("Added %d revisions." % count)
839
def install_revisions(self, other, revision_ids, pb):
840
if hasattr(other.revision_store, "prefetch"):
841
other.revision_store.prefetch(revision_ids)
842
if hasattr(other.inventory_store, "prefetch"):
843
inventory_ids = [other.get_revision(r).inventory_id
844
for r in revision_ids]
845
other.inventory_store.prefetch(inventory_ids)
848
pb = bzrlib.ui.ui_factory.progress_bar()
855
for i, rev_id in enumerate(revision_ids):
856
pb.update('fetching revision', i+1, len(revision_ids))
858
rev = other.get_revision(rev_id)
859
except bzrlib.errors.NoSuchRevision:
863
revisions.append(rev)
864
inv = other.get_inventory(str(rev.inventory_id))
865
for key, entry in inv.iter_entries():
866
if entry.text_id is None:
868
if entry.text_id not in self.text_store:
869
needed_texts.add(entry.text_id)
873
count, cp_fail = self.text_store.copy_multi(other.text_store,
875
print "Added %d texts." % count
876
inventory_ids = [ f.inventory_id for f in revisions ]
877
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
879
print "Added %d inventories." % count
880
revision_ids = [ f.revision_id for f in revisions]
882
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
885
assert len(cp_fail) == 0
886
return count, failures
833
889
def commit(self, *args, **kw):
834
from bzrlib.commit import Commit
835
Commit().commit(self, *args, **kw)
890
from bzrlib.commit import commit
891
commit(self, *args, **kw)
838
894
def lookup_revision(self, revision):
839
895
"""Return the revision identifier for a given revision information."""
840
revno, info = self._get_revision_info(revision)
896
revno, info = self.get_revision_info(revision)
858
914
revision can also be a string, in which case it is parsed for something like
859
915
'date:' or 'revid:' etc.
861
revno, rev_id = self._get_revision_info(revision)
863
raise bzrlib.errors.NoSuchRevision(self, revision)
866
def get_rev_id(self, revno, history=None):
867
"""Find the revision id of the specified revno."""
871
history = self.revision_history()
872
elif revno <= 0 or revno > len(history):
873
raise bzrlib.errors.NoSuchRevision(self, revno)
874
return history[revno - 1]
876
def _get_revision_info(self, revision):
877
"""Return (revno, revision id) for revision specifier.
879
revision can be an integer, in which case it is assumed to be revno
880
(though this will translate negative values into positive ones)
881
revision can also be a string, in which case it is parsed for something
882
like 'date:' or 'revid:' etc.
884
A revid is always returned. If it is None, the specifier referred to
885
the null revision. If the revid does not occur in the revision
886
history, revno will be None.
889
917
if revision is None:
896
924
revs = self.revision_history()
897
925
if isinstance(revision, int):
928
# Mabye we should do this first, but we don't need it if revision == 0
899
930
revno = len(revs) + revision + 1
902
rev_id = self.get_rev_id(revno, revs)
903
933
elif isinstance(revision, basestring):
904
934
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
905
935
if revision.startswith(prefix):
906
result = func(self, revs, revision)
908
revno, rev_id = result
911
rev_id = self.get_rev_id(revno, revs)
936
revno = func(self, revs, revision)
914
raise BzrError('No namespace registered for string: %r' %
917
raise TypeError('Unhandled revision type %s' % revision)
939
raise BzrError('No namespace registered for string: %r' % revision)
921
raise bzrlib.errors.NoSuchRevision(self, revision)
941
if revno is None or revno <= 0 or revno > len(revs):
942
raise BzrError("no such revision %s" % revision)
943
return revno, revs[revno-1]
924
945
def _namespace_revno(self, revs, revision):
925
946
"""Lookup a revision by revision number"""
926
947
assert revision.startswith('revno:')
928
return (int(revision[6:]),)
949
return int(revision[6:])
929
950
except ValueError:
931
952
REVISION_NAMESPACES['revno:'] = _namespace_revno
933
954
def _namespace_revid(self, revs, revision):
934
955
assert revision.startswith('revid:')
935
rev_id = revision[len('revid:'):]
937
return revs.index(rev_id) + 1, rev_id
957
return revs.index(revision[6:]) + 1
938
958
except ValueError:
940
960
REVISION_NAMESPACES['revid:'] = _namespace_revid
942
962
def _namespace_last(self, revs, revision):
1275
def get_parent(self):
1276
"""Return the parent location of the branch.
1278
This is the default location for push/pull/missing. The usual
1279
pattern is that the user can override it by specifying a
1283
_locs = ['parent', 'pull', 'x-pull']
1286
return self.controlfile(l, 'r').read().strip('\n')
1288
if e.errno != errno.ENOENT:
1293
def set_parent(self, url):
1294
# TODO: Maybe delete old location files?
1295
from bzrlib.atomicfile import AtomicFile
1298
f = AtomicFile(self.controlfilename('parent'))
1307
def check_revno(self, revno):
1309
Check whether a revno corresponds to any revision.
1310
Zero (the NULL revision) is considered valid.
1313
self.check_real_revno(revno)
1315
def check_real_revno(self, revno):
1317
Check whether a revno corresponds to a real revision.
1318
Zero (the NULL revision) is considered invalid
1320
if revno < 1 or revno > self.revno():
1321
raise InvalidRevisionNumber(revno)
1326
1297
class ScratchBranch(Branch):
1327
1298
"""Special test class: a branch that cleans up after itself.
1446
1415
"""Return a new tree-root file id."""
1447
1416
return gen_file_id('TREE_ROOT')
1450
def pull_loc(branch):
1451
# TODO: Should perhaps just make attribute be 'base' in
1452
# RemoteBranch and Branch?
1453
if hasattr(branch, "baseurl"):
1454
return branch.baseurl
1459
def copy_branch(branch_from, to_location, revision=None):
1460
"""Copy branch_from into the existing directory to_location.
1463
If not None, only revisions up to this point will be copied.
1464
The head of the new branch will be that revision.
1467
The name of a local directory that exists but is empty.
1469
from bzrlib.merge import merge
1470
from bzrlib.branch import Branch
1472
assert isinstance(branch_from, Branch)
1473
assert isinstance(to_location, basestring)
1475
br_to = Branch(to_location, init=True)
1476
br_to.set_root_id(branch_from.get_root_id())
1477
if revision is None:
1478
revno = branch_from.revno()
1480
revno, rev_id = branch_from.get_revision_info(revision)
1481
br_to.update_revisions(branch_from, stop_revision=revno)
1482
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1483
check_clean=False, ignore_zero=True)
1485
from_location = pull_loc(branch_from)
1486
br_to.set_parent(pull_loc(branch_from))