28
28
import bzrlib.errors
29
29
from bzrlib.textui import show_status
30
30
from bzrlib.revision import Revision
31
from bzrlib.xml import unpack_xml
32
31
from bzrlib.delta import compare_trees
33
32
from bzrlib.tree import EmptyTree, RevisionTree
34
from bzrlib.progress import ProgressBar
36
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
37
39
## TODO: Maybe include checks for common corruption of newlines, etc?
260
258
self._lock = None
261
259
self._lock_mode = self._lock_count = None
264
261
def abspath(self, name):
265
262
"""Return absolute filename for something in the branch"""
266
263
return os.path.join(self.base, name)
269
265
def relpath(self, path):
270
266
"""Return path relative to this branch of something inside it.
272
268
Raises an error if path is not in this branch."""
273
269
return _relpath(self.base, path)
276
271
def controlfilename(self, file_or_path):
277
272
"""Return location relative to branch."""
278
273
if isinstance(file_or_path, basestring):
343
336
# on Windows from Linux and so on. I think it might be better
344
337
# to always make all internal files in unix format.
345
338
fmt = self.controlfile('branch-format', 'r').read()
346
fmt.replace('\r\n', '')
339
fmt = fmt.replace('\r\n', '\n')
347
340
if fmt != BZR_BRANCH_FORMAT:
348
341
raise BzrError('sorry, branch format %r not supported' % fmt,
349
342
['use a different bzr version',
369
362
def read_working_inventory(self):
370
363
"""Read the working inventory."""
371
364
from bzrlib.inventory import Inventory
372
from bzrlib.xml import unpack_xml
373
from time import time
377
367
# ElementTree does its own conversion from UTF-8, so open in
379
inv = unpack_xml(Inventory,
380
self.controlfile('inventory', 'rb'))
381
mutter("loaded inventory of %d items in %f"
382
% (len(inv), time() - before))
369
f = self.controlfile('inventory', 'rb')
370
return bzrlib.xml.serializer_v4.read_inventory(f)
412
398
"""Inventory for the working copy.""")
415
def add(self, files, verbose=False, ids=None):
401
def add(self, files, ids=None):
416
402
"""Make files versioned.
418
Note that the command line normally calls smart_add instead.
404
Note that the command line normally calls smart_add instead,
405
which can automatically recurse.
420
407
This puts the files in the Added state, so that they will be
421
408
recorded by the next commit.
431
418
TODO: Perhaps have an option to add the ids even if the files do
434
TODO: Perhaps return the ids of the files? But then again it
435
is easy to retrieve them if they're needed.
437
TODO: Adding a directory should optionally recurse down and
438
add all non-ignored children. Perhaps do that in a
421
TODO: Perhaps yield the ids and paths as they're added.
441
423
# TODO: Re-adding a file that is removed in the working copy
442
424
# should probably put it back with the previous ID.
594
get_revision_xml = get_revision_xml_file
614
597
def get_revision(self, revision_id):
615
598
"""Return the Revision object for a named revision"""
616
xml_file = self.get_revision_xml(revision_id)
599
xml_file = self.get_revision_xml_file(revision_id)
619
r = unpack_xml(Revision, xml_file)
602
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
620
603
except SyntaxError, e:
621
604
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
667
650
parameter which can be either an integer revno or a
669
652
from bzrlib.inventory import Inventory
670
from bzrlib.xml import unpack_xml
672
return unpack_xml(Inventory, self.get_inventory_xml(inventory_id))
654
f = self.get_inventory_xml_file(inventory_id)
655
return bzrlib.xml.serializer_v4.read_inventory(f)
675
658
def get_inventory_xml(self, inventory_id):
676
659
"""Get inventory XML as a file object."""
677
660
return self.inventory_store[inventory_id]
662
get_inventory_xml_file = get_inventory_xml
680
665
def get_inventory_sha1(self, inventory_id):
819
804
def update_revisions(self, other, stop_revision=None):
820
805
"""Pull in all new revisions from other branch.
822
>>> from bzrlib.commit import commit
823
>>> bzrlib.trace.silent = True
824
>>> br1 = ScratchBranch(files=['foo', 'bar'])
827
>>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
828
>>> br2 = ScratchBranch()
829
>>> br2.update_revisions(br1)
833
>>> br2.revision_history()
835
>>> br2.update_revisions(br1)
839
>>> 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()
843
811
pb.update('comparing histories')
844
revision_ids = self.missing_revisions(other, stop_revision)
845
count = self.install_revisions(other, revision_ids, pb=pb)
814
revision_ids = self.missing_revisions(other, stop_revision)
815
except DivergedBranches, e:
817
if stop_revision is None:
818
end_revision = other.last_patch()
819
revision_ids = get_intervening_revisions(self.last_patch(),
821
assert self.last_patch() not in revision_ids
822
except bzrlib.errors.NotAncestor:
825
if len(revision_ids) > 0:
826
count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
846
829
self.append_revision(*revision_ids)
847
print "Added %d revisions." % count
849
def install_revisions(self, other, revision_ids, pb=None):
830
## note("Added %d revisions." % count)
833
def install_revisions(self, other, revision_ids, pb):
852
834
if hasattr(other.revision_store, "prefetch"):
853
835
other.revision_store.prefetch(revision_ids)
854
836
if hasattr(other.inventory_store, "prefetch"):
855
837
inventory_ids = [other.get_revision(r).inventory_id
856
838
for r in revision_ids]
857
839
other.inventory_store.prefetch(inventory_ids)
842
pb = bzrlib.ui.ui_factory.progress_bar()
860
845
needed_texts = set()
862
for rev_id in revision_ids:
864
pb.update('fetching revision', i, len(revision_ids))
865
rev = other.get_revision(rev_id)
849
for i, rev_id in enumerate(revision_ids):
850
pb.update('fetching revision', i+1, len(revision_ids))
852
rev = other.get_revision(rev_id)
853
except bzrlib.errors.NoSuchRevision:
866
857
revisions.append(rev)
867
858
inv = other.get_inventory(str(rev.inventory_id))
868
859
for key, entry in inv.iter_entries():
876
count = self.text_store.copy_multi(other.text_store, needed_texts)
877
print "Added %d texts." % count
867
count, cp_fail = self.text_store.copy_multi(other.text_store,
869
#print "Added %d texts." % count
878
870
inventory_ids = [ f.inventory_id for f in revisions ]
879
count = self.inventory_store.copy_multi(other.inventory_store,
881
print "Added %d inventories." % count
871
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
873
#print "Added %d inventories." % count
882
874
revision_ids = [ f.revision_id for f in revisions]
883
count = self.revision_store.copy_multi(other.revision_store,
876
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
879
assert len(cp_fail) == 0
880
return count, failures
887
883
def commit(self, *args, **kw):
888
884
from bzrlib.commit import commit
889
885
commit(self, *args, **kw)
892
888
def lookup_revision(self, revision):
893
889
"""Return the revision identifier for a given revision information."""
894
revno, info = self.get_revision_info(revision)
890
revno, info = self._get_revision_info(revision)
894
def revision_id_to_revno(self, revision_id):
895
"""Given a revision id, return its revno"""
896
history = self.revision_history()
898
return history.index(revision_id) + 1
900
raise bzrlib.errors.NoSuchRevision(self, revision_id)
897
903
def get_revision_info(self, revision):
898
904
"""Return (revno, revision id) for revision identifier.
902
908
revision can also be a string, in which case it is parsed for something like
903
909
'date:' or 'revid:' etc.
911
revno, rev_id = self._get_revision_info(revision)
913
raise bzrlib.errors.NoSuchRevision(self, revision)
916
def get_rev_id(self, revno, history=None):
917
"""Find the revision id of the specified revno."""
921
history = self.revision_history()
922
elif revno <= 0 or revno > len(history):
923
raise bzrlib.errors.NoSuchRevision(self, revno)
924
return history[revno - 1]
926
def _get_revision_info(self, revision):
927
"""Return (revno, revision id) for revision specifier.
929
revision can be an integer, in which case it is assumed to be revno
930
(though this will translate negative values into positive ones)
931
revision can also be a string, in which case it is parsed for something
932
like 'date:' or 'revid:' etc.
934
A revid is always returned. If it is None, the specifier referred to
935
the null revision. If the revid does not occur in the revision
936
history, revno will be None.
905
939
if revision is None:
912
946
revs = self.revision_history()
913
947
if isinstance(revision, int):
916
# Mabye we should do this first, but we don't need it if revision == 0
918
949
revno = len(revs) + revision + 1
952
rev_id = self.get_rev_id(revno, revs)
921
953
elif isinstance(revision, basestring):
922
954
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
923
955
if revision.startswith(prefix):
924
revno = func(self, revs, revision)
956
result = func(self, revs, revision)
958
revno, rev_id = result
961
rev_id = self.get_rev_id(revno, revs)
927
raise BzrError('No namespace registered for string: %r' % revision)
964
raise BzrError('No namespace registered for string: %r' %
967
raise TypeError('Unhandled revision type %s' % revision)
929
if revno is None or revno <= 0 or revno > len(revs):
930
raise BzrError("no such revision %s" % revision)
931
return revno, revs[revno-1]
971
raise bzrlib.errors.NoSuchRevision(self, revision)
933
974
def _namespace_revno(self, revs, revision):
934
975
"""Lookup a revision by revision number"""
935
976
assert revision.startswith('revno:')
937
return int(revision[6:])
978
return (int(revision[6:]),)
938
979
except ValueError:
940
981
REVISION_NAMESPACES['revno:'] = _namespace_revno
942
983
def _namespace_revid(self, revs, revision):
943
984
assert revision.startswith('revid:')
985
rev_id = revision[len('revid:'):]
945
return revs.index(revision[6:]) + 1
987
return revs.index(rev_id) + 1, rev_id
946
988
except ValueError:
948
990
REVISION_NAMESPACES['revid:'] = _namespace_revid
950
992
def _namespace_last(self, revs, revision):
1037
1079
# TODO: Handle timezone.
1038
1080
dt = datetime.datetime.fromtimestamp(r.timestamp)
1039
1081
if first >= dt and (last is None or dt >= last):
1042
1084
for i in range(len(revs)):
1043
1085
r = self.get_revision(revs[i])
1044
1086
# TODO: Handle timezone.
1045
1087
dt = datetime.datetime.fromtimestamp(r.timestamp)
1046
1088
if first <= dt and (last is None or dt <= last):
1048
1090
REVISION_NAMESPACES['date:'] = _namespace_date
1050
1092
def revision_tree(self, revision_id):
1182
1226
for f in from_paths:
1183
1227
name_tail = splitpath(f)[-1]
1184
1228
dest_path = appendpath(to_name, name_tail)
1185
print "%s => %s" % (f, dest_path)
1229
result.append((f, dest_path))
1186
1230
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1188
1232
os.rename(self.abspath(f), self.abspath(dest_path))
1330
def get_parent(self):
1331
"""Return the parent location of the branch.
1333
This is the default location for push/pull/missing. The usual
1334
pattern is that the user can override it by specifying a
1338
_locs = ['parent', 'pull', 'x-pull']
1341
return self.controlfile(l, 'r').read().strip('\n')
1343
if e.errno != errno.ENOENT:
1348
def set_parent(self, url):
1349
# TODO: Maybe delete old location files?
1350
from bzrlib.atomicfile import AtomicFile
1353
f = AtomicFile(self.controlfilename('parent'))
1362
def check_revno(self, revno):
1364
Check whether a revno corresponds to any revision.
1365
Zero (the NULL revision) is considered valid.
1368
self.check_real_revno(revno)
1370
def check_real_revno(self, revno):
1372
Check whether a revno corresponds to a real revision.
1373
Zero (the NULL revision) is considered invalid
1375
if revno < 1 or revno > self.revno():
1376
raise InvalidRevisionNumber(revno)
1285
1381
class ScratchBranch(Branch):
1286
1382
"""Special test class: a branch that cleans up after itself.
1403
1501
"""Return a new tree-root file id."""
1404
1502
return gen_file_id('TREE_ROOT')
1505
def pull_loc(branch):
1506
# TODO: Should perhaps just make attribute be 'base' in
1507
# RemoteBranch and Branch?
1508
if hasattr(branch, "baseurl"):
1509
return branch.baseurl
1514
def copy_branch(branch_from, to_location, revision=None):
1515
"""Copy branch_from into the existing directory to_location.
1518
If not None, only revisions up to this point will be copied.
1519
The head of the new branch will be that revision.
1522
The name of a local directory that exists but is empty.
1524
from bzrlib.merge import merge
1525
from bzrlib.branch import Branch
1527
assert isinstance(branch_from, Branch)
1528
assert isinstance(to_location, basestring)
1530
br_to = Branch(to_location, init=True)
1531
br_to.set_root_id(branch_from.get_root_id())
1532
if revision is None:
1533
revno = branch_from.revno()
1535
revno, rev_id = branch_from.get_revision_info(revision)
1536
br_to.update_revisions(branch_from, stop_revision=revno)
1537
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1538
check_clean=False, ignore_zero=True)
1540
from_location = pull_loc(branch_from)
1541
br_to.set_parent(pull_loc(branch_from))