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
######################################################################
204
206
def __del__(self):
205
207
if self._lock_mode or self._lock:
206
from warnings import warn
208
from bzrlib.warnings import warn
207
209
warn("branch %r was not explicitly unlocked" % self)
208
210
self._lock.unlock()
212
213
def lock_write(self):
213
214
if self._lock_mode:
214
215
if self._lock_mode != 'w':
215
from errors import LockError
216
from bzrlib.errors import LockError
216
217
raise LockError("can't upgrade to a write lock from %r" %
218
219
self._lock_count += 1
251
249
self._lock = None
252
250
self._lock_mode = self._lock_count = None
255
252
def abspath(self, name):
256
253
"""Return absolute filename for something in the branch"""
257
254
return os.path.join(self.base, name)
260
256
def relpath(self, path):
261
257
"""Return path relative to this branch of something inside it.
263
259
Raises an error if path is not in this branch."""
264
260
return _relpath(self.base, path)
267
262
def controlfilename(self, file_or_path):
268
263
"""Return location relative to branch."""
269
264
if isinstance(file_or_path, basestring):
316
308
self.controlfile(f, 'w').write('')
317
309
mutter('created control directory in ' + self.base)
319
pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
311
# if we want per-tree root ids then this is the place to set
312
# them; they're not needed for now and so ommitted for
314
f = self.controlfile('inventory','w')
315
bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
322
318
def _check_format(self):
331
327
# on Windows from Linux and so on. I think it might be better
332
328
# to always make all internal files in unix format.
333
329
fmt = self.controlfile('branch-format', 'r').read()
334
fmt.replace('\r\n', '')
330
fmt = fmt.replace('\r\n', '\n')
335
331
if fmt != BZR_BRANCH_FORMAT:
336
332
raise BzrError('sorry, branch format %r not supported' % fmt,
337
333
['use a different bzr version',
357
353
def read_working_inventory(self):
358
354
"""Read the working inventory."""
359
355
from bzrlib.inventory import Inventory
360
from bzrlib.xml import unpack_xml
361
from time import time
365
358
# 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))
360
f = self.controlfile('inventory', 'rb')
361
return bzrlib.xml.serializer_v4.read_inventory(f)
400
389
"""Inventory for the working copy.""")
403
def add(self, files, verbose=False, ids=None):
392
def add(self, files, ids=None):
404
393
"""Make files versioned.
406
Note that the command line normally calls smart_add instead.
395
Note that the command line normally calls smart_add instead,
396
which can automatically recurse.
408
398
This puts the files in the Added state, so that they will be
409
399
recorded by the next commit.
419
409
TODO: Perhaps have an option to add the ids even if the files do
422
TODO: Perhaps return the ids of the files? But then again it
423
is easy to retrieve them if they're needed.
425
TODO: Adding a directory should optionally recurse down and
426
add all non-ignored children. Perhaps do that in a
412
TODO: Perhaps yield the ids and paths as they're added.
429
414
# TODO: Re-adding a file that is removed in the working copy
430
415
# should probably put it back with the previous ID.
595
577
return self.revision_store[revision_id]
596
578
except IndexError:
597
raise bzrlib.errors.NoSuchRevision(revision_id)
579
raise bzrlib.errors.NoSuchRevision(self, revision_id)
585
get_revision_xml = get_revision_xml_file
602
588
def get_revision(self, revision_id):
603
589
"""Return the Revision object for a named revision"""
604
xml_file = self.get_revision_xml(revision_id)
590
xml_file = self.get_revision_xml_file(revision_id)
607
r = unpack_xml(Revision, xml_file)
593
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
608
594
except SyntaxError, e:
609
595
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
655
641
parameter which can be either an integer revno or a
657
643
from bzrlib.inventory import Inventory
658
from bzrlib.xml import unpack_xml
660
return unpack_xml(Inventory, self.inventory_store[inventory_id])
645
f = self.get_inventory_xml_file(inventory_id)
646
return bzrlib.xml.serializer_v4.read_inventory(f)
649
def get_inventory_xml(self, inventory_id):
650
"""Get inventory XML as a file object."""
651
return self.inventory_store[inventory_id]
653
get_inventory_xml_file = get_inventory_xml
663
656
def get_inventory_sha1(self, inventory_id):
664
657
"""Return the sha1 hash of the inventory entry
666
return sha_file(self.inventory_store[inventory_id])
659
return sha_file(self.get_inventory_xml(inventory_id))
669
662
def get_revision_inventory(self, revision_id):
694
687
def common_ancestor(self, other, self_revno=None, other_revno=None):
689
>>> from bzrlib.commit import commit
697
690
>>> sb = ScratchBranch(files=['foo', 'foo~'])
698
691
>>> sb.common_ancestor(sb) == (None, None)
700
>>> commit.commit(sb, "Committing first revision", verbose=False)
693
>>> commit(sb, "Committing first revision", verbose=False)
701
694
>>> sb.common_ancestor(sb)[0]
703
696
>>> clone = sb.clone()
704
>>> commit.commit(sb, "Committing second revision", verbose=False)
697
>>> commit(sb, "Committing second revision", verbose=False)
705
698
>>> sb.common_ancestor(sb)[0]
707
700
>>> sb.common_ancestor(clone)[0]
709
>>> commit.commit(clone, "Committing divergent second revision",
702
>>> commit(clone, "Committing divergent second revision",
710
703
... verbose=False)
711
704
>>> sb.common_ancestor(clone)[0]
758
def missing_revisions(self, other, stop_revision=None):
751
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
760
753
If self and other have not diverged, return a list of the revisions
761
754
present in other, but missing from self.
794
787
if stop_revision is None:
795
788
stop_revision = other_len
796
789
elif stop_revision > other_len:
797
raise NoSuchRevision(self, stop_revision)
790
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
799
792
return other_history[self_len:stop_revision]
802
795
def update_revisions(self, other, stop_revision=None):
803
796
"""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
798
from bzrlib.fetch import greedy_fetch
800
pb = bzrlib.ui.ui_factory.progress_bar()
829
801
pb.update('comparing histories')
830
803
revision_ids = self.missing_revisions(other, stop_revision)
805
if len(revision_ids) > 0:
806
count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
809
self.append_revision(*revision_ids)
810
## note("Added %d revisions." % count)
813
def install_revisions(self, other, revision_ids, pb):
832
814
if hasattr(other.revision_store, "prefetch"):
833
815
other.revision_store.prefetch(revision_ids)
834
816
if hasattr(other.inventory_store, "prefetch"):
835
817
inventory_ids = [other.get_revision(r).inventory_id
836
818
for r in revision_ids]
837
819
other.inventory_store.prefetch(inventory_ids)
822
pb = bzrlib.ui.ui_factory.progress_bar()
840
825
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)
829
for i, rev_id in enumerate(revision_ids):
830
pb.update('fetching revision', i+1, len(revision_ids))
832
rev = other.get_revision(rev_id)
833
except bzrlib.errors.NoSuchRevision:
846
837
revisions.append(rev)
847
838
inv = other.get_inventory(str(rev.inventory_id))
848
839
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
847
count, cp_fail = self.text_store.copy_multi(other.text_store,
849
#print "Added %d texts." % count
858
850
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
851
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
853
#print "Added %d inventories." % count
862
854
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
856
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
859
assert len(cp_fail) == 0
860
return count, failures
870
863
def commit(self, *args, **kw):
871
864
from bzrlib.commit import commit
872
865
commit(self, *args, **kw)
875
868
def lookup_revision(self, revision):
876
869
"""Return the revision identifier for a given revision information."""
877
revno, info = self.get_revision_info(revision)
870
revno, info = self._get_revision_info(revision)
874
def revision_id_to_revno(self, revision_id):
875
"""Given a revision id, return its revno"""
876
history = self.revision_history()
878
return history.index(revision_id) + 1
880
raise bzrlib.errors.NoSuchRevision(self, revision_id)
880
883
def get_revision_info(self, revision):
881
884
"""Return (revno, revision id) for revision identifier.
885
888
revision can also be a string, in which case it is parsed for something like
886
889
'date:' or 'revid:' etc.
891
revno, rev_id = self._get_revision_info(revision)
893
raise bzrlib.errors.NoSuchRevision(self, revision)
896
def get_rev_id(self, revno, history=None):
897
"""Find the revision id of the specified revno."""
901
history = self.revision_history()
902
elif revno <= 0 or revno > len(history):
903
raise bzrlib.errors.NoSuchRevision(self, revno)
904
return history[revno - 1]
906
def _get_revision_info(self, revision):
907
"""Return (revno, revision id) for revision specifier.
909
revision can be an integer, in which case it is assumed to be revno
910
(though this will translate negative values into positive ones)
911
revision can also be a string, in which case it is parsed for something
912
like 'date:' or 'revid:' etc.
914
A revid is always returned. If it is None, the specifier referred to
915
the null revision. If the revid does not occur in the revision
916
history, revno will be None.
888
919
if revision is None:
895
926
revs = self.revision_history()
896
927
if isinstance(revision, int):
899
# Mabye we should do this first, but we don't need it if revision == 0
901
929
revno = len(revs) + revision + 1
932
rev_id = self.get_rev_id(revno, revs)
904
933
elif isinstance(revision, basestring):
905
934
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
935
if revision.startswith(prefix):
907
revno = func(self, revs, revision)
936
result = func(self, revs, revision)
938
revno, rev_id = result
941
rev_id = self.get_rev_id(revno, revs)
910
raise BzrError('No namespace registered for string: %r' % revision)
944
raise BzrError('No namespace registered for string: %r' %
947
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]
951
raise bzrlib.errors.NoSuchRevision(self, revision)
916
954
def _namespace_revno(self, revs, revision):
917
955
"""Lookup a revision by revision number"""
918
956
assert revision.startswith('revno:')
920
return int(revision[6:])
958
return (int(revision[6:]),)
921
959
except ValueError:
923
961
REVISION_NAMESPACES['revno:'] = _namespace_revno
925
963
def _namespace_revid(self, revs, revision):
926
964
assert revision.startswith('revid:')
965
rev_id = revision[len('revid:'):]
928
return revs.index(revision[6:]) + 1
967
return revs.index(rev_id) + 1, rev_id
929
968
except ValueError:
931
970
REVISION_NAMESPACES['revid:'] = _namespace_revid
933
972
def _namespace_last(self, revs, revision):
936
975
offset = int(revision[5:])
937
976
except ValueError:
941
980
raise BzrError('You must supply a positive value for --revision last:XXX')
942
return len(revs) - offset + 1
981
return (len(revs) - offset + 1,)
943
982
REVISION_NAMESPACES['last:'] = _namespace_last
945
984
def _namespace_tag(self, revs, revision):
1020
1059
# TODO: Handle timezone.
1021
1060
dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
1061
if first >= dt and (last is None or dt >= last):
1025
1064
for i in range(len(revs)):
1026
1065
r = self.get_revision(revs[i])
1027
1066
# TODO: Handle timezone.
1028
1067
dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
1068
if first <= dt and (last is None or dt <= last):
1031
1070
REVISION_NAMESPACES['date:'] = _namespace_date
1033
1072
def revision_tree(self, revision_id):
1165
1206
for f in from_paths:
1166
1207
name_tail = splitpath(f)[-1]
1167
1208
dest_path = appendpath(to_name, name_tail)
1168
print "%s => %s" % (f, dest_path)
1209
result.append((f, dest_path))
1169
1210
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1171
1212
os.rename(self.abspath(f), self.abspath(dest_path))
1310
def get_parent(self):
1311
"""Return the parent location of the branch.
1313
This is the default location for push/pull/missing. The usual
1314
pattern is that the user can override it by specifying a
1318
_locs = ['parent', 'pull', 'x-pull']
1321
return self.controlfile(l, 'r').read().strip('\n')
1323
if e.errno != errno.ENOENT:
1328
def set_parent(self, url):
1329
# TODO: Maybe delete old location files?
1330
from bzrlib.atomicfile import AtomicFile
1333
f = AtomicFile(self.controlfilename('parent'))
1342
def check_revno(self, revno):
1344
Check whether a revno corresponds to any revision.
1345
Zero (the NULL revision) is considered valid.
1348
self.check_real_revno(revno)
1350
def check_real_revno(self, revno):
1352
Check whether a revno corresponds to a real revision.
1353
Zero (the NULL revision) is considered invalid
1355
if revno < 1 or revno > self.revno():
1356
raise InvalidRevisionNumber(revno)
1268
1361
class ScratchBranch(Branch):
1269
1362
"""Special test class: a branch that cleans up after itself.
1386
1481
"""Return a new tree-root file id."""
1387
1482
return gen_file_id('TREE_ROOT')
1485
def copy_branch(branch_from, to_location, revision=None):
1486
"""Copy branch_from into the existing directory to_location.
1489
If not None, only revisions up to this point will be copied.
1490
The head of the new branch will be that revision.
1493
The name of a local directory that exists but is empty.
1495
from bzrlib.merge import merge
1497
assert isinstance(branch_from, Branch)
1498
assert isinstance(to_location, basestring)
1500
br_to = Branch(to_location, init=True)
1501
br_to.set_root_id(branch_from.get_root_id())
1502
if revision is None:
1503
revno = branch_from.revno()
1505
revno, rev_id = branch_from.get_revision_info(revision)
1506
br_to.update_revisions(branch_from, stop_revision=revno)
1507
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1508
check_clean=False, ignore_zero=True)
1510
from_location = branch_from.base
1511
br_to.set_parent(branch_from.base)