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
262
258
self._lock = None
263
259
self._lock_mode = self._lock_count = None
266
261
def abspath(self, name):
267
262
"""Return absolute filename for something in the branch"""
268
263
return os.path.join(self.base, name)
271
265
def relpath(self, path):
272
266
"""Return path relative to this branch of something inside it.
274
268
Raises an error if path is not in this branch."""
275
269
return _relpath(self.base, path)
278
271
def controlfilename(self, file_or_path):
279
272
"""Return location relative to branch."""
280
273
if isinstance(file_or_path, basestring):
308
301
raise BzrError("invalid controlfile mode %r" % mode)
312
303
def _make_control(self):
313
304
from bzrlib.inventory import Inventory
314
from bzrlib.xml import pack_xml
316
306
os.mkdir(self.controlfilename([]))
317
307
self.controlfile('README', 'w').write(
330
320
# if we want per-tree root ids then this is the place to set
331
321
# them; they're not needed for now and so ommitted for
333
pack_xml(Inventory(), self.controlfile('inventory','w'))
323
f = self.controlfile('inventory','w')
324
bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
336
327
def _check_format(self):
371
362
def read_working_inventory(self):
372
363
"""Read the working inventory."""
373
364
from bzrlib.inventory import Inventory
374
from bzrlib.xml import unpack_xml
375
from time import time
379
367
# ElementTree does its own conversion from UTF-8, so open in
381
inv = unpack_xml(Inventory,
382
self.controlfile('inventory', 'rb'))
383
mutter("loaded inventory of %d items in %f"
384
% (len(inv), time() - before))
369
f = self.controlfile('inventory', 'rb')
370
return bzrlib.xml.serializer_v4.read_inventory(f)
394
379
will be committed to the next revision.
396
381
from bzrlib.atomicfile import AtomicFile
397
from bzrlib.xml import pack_xml
399
383
self.lock_write()
401
385
f = AtomicFile(self.controlfilename('inventory'), 'wb')
387
bzrlib.xml.serializer_v4.write_inventory(inv, f)
414
398
"""Inventory for the working copy.""")
417
def add(self, files, verbose=False, ids=None):
401
def add(self, files, ids=None):
418
402
"""Make files versioned.
420
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.
422
407
This puts the files in the Added state, so that they will be
423
408
recorded by the next commit.
433
418
TODO: Perhaps have an option to add the ids even if the files do
436
TODO: Perhaps return the ids of the files? But then again it
437
is easy to retrieve them if they're needed.
439
TODO: Adding a directory should optionally recurse down and
440
add all non-ignored children. Perhaps do that in a
421
TODO: Perhaps yield the ids and paths as they're added.
443
423
# TODO: Re-adding a file that is removed in the working copy
444
424
# should probably put it back with the previous ID.
480
460
file_id = gen_file_id(f)
481
461
inv.add_path(f, kind=kind, file_id=file_id)
484
print 'added', quotefn(f)
486
463
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
488
465
self._write_inventory(inv)
601
def get_revision_xml(self, revision_id):
578
def get_revision_xml_file(self, revision_id):
602
579
"""Return XML file object for revision object."""
603
580
if not revision_id or not isinstance(revision_id, basestring):
604
581
raise InvalidRevisionId(revision_id)
594
get_revision_xml = get_revision_xml_file
616
597
def get_revision(self, revision_id):
617
598
"""Return the Revision object for a named revision"""
618
xml_file = self.get_revision_xml(revision_id)
599
xml_file = self.get_revision_xml_file(revision_id)
621
r = unpack_xml(Revision, xml_file)
602
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
622
603
except SyntaxError, e:
623
604
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
669
650
parameter which can be either an integer revno or a
671
652
from bzrlib.inventory import Inventory
672
from bzrlib.xml import unpack_xml
674
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)
677
658
def get_inventory_xml(self, inventory_id):
678
659
"""Get inventory XML as a file object."""
679
660
return self.inventory_store[inventory_id]
662
get_inventory_xml_file = get_inventory_xml
682
665
def get_inventory_sha1(self, inventory_id):
836
819
## note("Added %d revisions." % count)
841
822
def install_revisions(self, other, revision_ids, pb):
842
823
if hasattr(other.revision_store, "prefetch"):
843
824
other.revision_store.prefetch(revision_ids)
896
877
def lookup_revision(self, revision):
897
878
"""Return the revision identifier for a given revision information."""
898
revno, info = self.get_revision_info(revision)
879
revno, info = self._get_revision_info(revision)
916
897
revision can also be a string, in which case it is parsed for something like
917
898
'date:' or 'revid:' etc.
900
revno, rev_id = self._get_revision_info(revision)
902
raise bzrlib.errors.NoSuchRevision(self, revision)
905
def get_rev_id(self, revno, history=None):
906
"""Find the revision id of the specified revno."""
910
history = self.revision_history()
911
elif revno <= 0 or revno > len(history):
912
raise bzrlib.errors.NoSuchRevision(self, revno)
913
return history[revno - 1]
915
def _get_revision_info(self, revision):
916
"""Return (revno, revision id) for revision specifier.
918
revision can be an integer, in which case it is assumed to be revno
919
(though this will translate negative values into positive ones)
920
revision can also be a string, in which case it is parsed for something
921
like 'date:' or 'revid:' etc.
923
A revid is always returned. If it is None, the specifier referred to
924
the null revision. If the revid does not occur in the revision
925
history, revno will be None.
919
928
if revision is None:
926
935
revs = self.revision_history()
927
936
if isinstance(revision, int):
930
# Mabye we should do this first, but we don't need it if revision == 0
932
938
revno = len(revs) + revision + 1
941
rev_id = self.get_rev_id(revno, revs)
935
942
elif isinstance(revision, basestring):
936
943
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
937
944
if revision.startswith(prefix):
938
revno = func(self, revs, revision)
945
result = func(self, revs, revision)
947
revno, rev_id = result
950
rev_id = self.get_rev_id(revno, revs)
941
raise BzrError('No namespace registered for string: %r' % revision)
953
raise BzrError('No namespace registered for string: %r' %
956
raise TypeError('Unhandled revision type %s' % revision)
943
if revno is None or revno <= 0 or revno > len(revs):
944
raise BzrError("no such revision %s" % revision)
945
return revno, revs[revno-1]
960
raise bzrlib.errors.NoSuchRevision(self, revision)
947
963
def _namespace_revno(self, revs, revision):
948
964
"""Lookup a revision by revision number"""
949
965
assert revision.startswith('revno:')
951
return int(revision[6:])
967
return (int(revision[6:]),)
952
968
except ValueError:
954
970
REVISION_NAMESPACES['revno:'] = _namespace_revno
956
972
def _namespace_revid(self, revs, revision):
957
973
assert revision.startswith('revid:')
974
rev_id = revision[len('revid:'):]
959
return revs.index(revision[6:]) + 1
976
return revs.index(rev_id) + 1, rev_id
960
977
except ValueError:
962
979
REVISION_NAMESPACES['revid:'] = _namespace_revid
964
981
def _namespace_last(self, revs, revision):
967
984
offset = int(revision[5:])
968
985
except ValueError:
972
989
raise BzrError('You must supply a positive value for --revision last:XXX')
973
return len(revs) - offset + 1
990
return (len(revs) - offset + 1,)
974
991
REVISION_NAMESPACES['last:'] = _namespace_last
976
993
def _namespace_tag(self, revs, revision):
1051
1068
# TODO: Handle timezone.
1052
1069
dt = datetime.datetime.fromtimestamp(r.timestamp)
1053
1070
if first >= dt and (last is None or dt >= last):
1056
1073
for i in range(len(revs)):
1057
1074
r = self.get_revision(revs[i])
1058
1075
# TODO: Handle timezone.
1059
1076
dt = datetime.datetime.fromtimestamp(r.timestamp)
1060
1077
if first <= dt and (last is None or dt <= last):
1062
1079
REVISION_NAMESPACES['date:'] = _namespace_date
1064
1081
def revision_tree(self, revision_id):
1130
1147
inv.rename(file_id, to_dir_id, to_tail)
1132
print "%s => %s" % (from_rel, to_rel)
1134
1149
from_abs = self.abspath(from_rel)
1135
1150
to_abs = self.abspath(to_rel)
1156
1171
Note that to_name is only the last component of the new name;
1157
1172
this doesn't change the directory.
1174
This returns a list of (from_path, to_path) pairs for each
1175
entry that is moved.
1159
1178
self.lock_write()
1161
1180
## TODO: Option to move IDs only
1196
1215
for f in from_paths:
1197
1216
name_tail = splitpath(f)[-1]
1198
1217
dest_path = appendpath(to_name, name_tail)
1199
print "%s => %s" % (f, dest_path)
1218
result.append((f, dest_path))
1200
1219
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1202
1221
os.rename(self.abspath(f), self.abspath(dest_path))
1319
def get_parent(self):
1320
"""Return the parent location of the branch.
1322
This is the default location for push/pull/missing. The usual
1323
pattern is that the user can override it by specifying a
1327
_locs = ['parent', 'pull', 'x-pull']
1330
return self.controlfile(l, 'r').read().strip('\n')
1332
if e.errno != errno.ENOENT:
1337
def set_parent(self, url):
1338
# TODO: Maybe delete old location files?
1339
from bzrlib.atomicfile import AtomicFile
1342
f = AtomicFile(self.controlfilename('parent'))
1351
def check_revno(self, revno):
1353
Check whether a revno corresponds to any revision.
1354
Zero (the NULL revision) is considered valid.
1357
self.check_real_revno(revno)
1359
def check_real_revno(self, revno):
1361
Check whether a revno corresponds to a real revision.
1362
Zero (the NULL revision) is considered invalid
1364
if revno < 1 or revno > self.revno():
1365
raise InvalidRevisionNumber(revno)
1299
1370
class ScratchBranch(Branch):
1300
1371
"""Special test class: a branch that cleans up after itself.
1417
1490
"""Return a new tree-root file id."""
1418
1491
return gen_file_id('TREE_ROOT')
1494
def pull_loc(branch):
1495
# TODO: Should perhaps just make attribute be 'base' in
1496
# RemoteBranch and Branch?
1497
if hasattr(branch, "baseurl"):
1498
return branch.baseurl
1503
def copy_branch(branch_from, to_location, revision=None):
1504
"""Copy branch_from into the existing directory to_location.
1507
If not None, only revisions up to this point will be copied.
1508
The head of the new branch will be that revision.
1511
The name of a local directory that exists but is empty.
1513
from bzrlib.merge import merge
1514
from bzrlib.branch import Branch
1516
assert isinstance(branch_from, Branch)
1517
assert isinstance(to_location, basestring)
1519
br_to = Branch(to_location, init=True)
1520
br_to.set_root_id(branch_from.get_root_id())
1521
if revision is None:
1522
revno = branch_from.revno()
1524
revno, rev_id = branch_from.get_revision_info(revision)
1525
br_to.update_revisions(branch_from, stop_revision=revno)
1526
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1527
check_clean=False, ignore_zero=True)
1529
from_location = pull_loc(branch_from)
1530
br_to.set_parent(pull_loc(branch_from))