1172
851
(from_executable, to_executable)))
1173
852
return iter(sorted(results, key=lambda x:x[1]))
854
def get_preview_tree(self):
855
"""Return a tree representing the result of the transform.
857
This tree only supports the subset of Tree functionality required
858
by show_diff_trees. It must only be compared to tt._tree.
860
return _PreviewTree(self)
862
def _text_parent(self, trans_id):
863
file_id = self.tree_file_id(trans_id)
865
if file_id is None or self._tree.kind(file_id) != 'file':
867
except errors.NoSuchFile:
871
def _get_parents_texts(self, trans_id):
872
"""Get texts for compression parents of this file."""
873
file_id = self._text_parent(trans_id)
876
return (self._tree.get_file_text(file_id),)
878
def _get_parents_lines(self, trans_id):
879
"""Get lines for compression parents of this file."""
880
file_id = self._text_parent(trans_id)
883
return (self._tree.get_file_lines(file_id),)
885
def serialize(self, serializer):
886
"""Serialize this TreeTransform.
888
:param serializer: A Serialiser like pack.ContainerSerializer.
890
new_name = dict((k, v.encode('utf-8')) for k, v in
891
self._new_name.items())
892
new_executability = dict((k, int(v)) for k, v in
893
self._new_executability.items())
894
tree_path_ids = dict((k.encode('utf-8'), v)
895
for k, v in self._tree_path_ids.items())
897
'_id_number': self._id_number,
898
'_new_name': new_name,
899
'_new_parent': self._new_parent,
900
'_new_executability': new_executability,
901
'_new_id': self._new_id,
902
'_tree_path_ids': tree_path_ids,
903
'_removed_id': list(self._removed_id),
904
'_removed_contents': list(self._removed_contents),
905
'_non_present_ids': self._non_present_ids,
907
yield serializer.bytes_record(bencode.bencode(attribs),
909
for trans_id, kind in self._new_contents.items():
911
lines = osutils.chunks_to_lines(
912
self._read_file_chunks(trans_id))
913
parents = self._get_parents_lines(trans_id)
914
mpdiff = multiparent.MultiParent.from_lines(lines, parents)
915
content = ''.join(mpdiff.to_patch())
916
if kind == 'directory':
918
if kind == 'symlink':
919
content = self._read_symlink_target(trans_id)
920
yield serializer.bytes_record(content, ((trans_id, kind),))
922
def deserialize(self, records):
923
"""Deserialize a stored TreeTransform.
925
:param records: An iterable of (names, content) tuples, as per
926
pack.ContainerPushParser.
928
names, content = records.next()
929
attribs = bencode.bdecode(content)
930
self._id_number = attribs['_id_number']
931
self._new_name = dict((k, v.decode('utf-8'))
932
for k, v in attribs['_new_name'].items())
933
self._new_parent = attribs['_new_parent']
934
self._new_executability = dict((k, bool(v)) for k, v in
935
attribs['_new_executability'].items())
936
self._new_id = attribs['_new_id']
937
self._r_new_id = dict((v, k) for k, v in self._new_id.items())
938
self._tree_path_ids = {}
939
self._tree_id_paths = {}
940
for bytepath, trans_id in attribs['_tree_path_ids'].items():
941
path = bytepath.decode('utf-8')
942
self._tree_path_ids[path] = trans_id
943
self._tree_id_paths[trans_id] = path
944
self._removed_id = set(attribs['_removed_id'])
945
self._removed_contents = set(attribs['_removed_contents'])
946
self._non_present_ids = attribs['_non_present_ids']
947
for ((trans_id, kind),), content in records:
949
mpdiff = multiparent.MultiParent.from_patch(content)
950
lines = mpdiff.to_lines(self._get_parents_texts(trans_id))
951
self.create_file(lines, trans_id)
952
if kind == 'directory':
953
self.create_directory(trans_id)
954
if kind == 'symlink':
955
self.create_symlink(content.decode('utf-8'), trans_id)
958
class DiskTreeTransform(TreeTransformBase):
959
"""Tree transform storing its contents on disk."""
961
def __init__(self, tree, limbodir, pb=DummyProgress(),
962
case_sensitive=True):
964
:param tree: The tree that will be transformed, but not necessarily
966
:param limbodir: A directory where new files can be stored until
967
they are installed in their proper places
968
:param pb: A ProgressBar indicating how much progress is being made
969
:param case_sensitive: If True, the target of the transform is
970
case sensitive, not just case preserving.
972
TreeTransformBase.__init__(self, tree, pb, case_sensitive)
973
self._limbodir = limbodir
974
self._deletiondir = None
975
# A mapping of transform ids to their limbo filename
976
self._limbo_files = {}
977
# A mapping of transform ids to a set of the transform ids of children
978
# that their limbo directory has
979
self._limbo_children = {}
980
# Map transform ids to maps of child filename to child transform id
981
self._limbo_children_names = {}
982
# List of transform ids that need to be renamed from limbo into place
983
self._needs_rename = set()
986
"""Release the working tree lock, if held, clean up limbo dir.
988
This is required if apply has not been invoked, but can be invoked
991
if self._tree is None:
994
entries = [(self._limbo_name(t), t, k) for t, k in
995
self._new_contents.iteritems()]
996
entries.sort(reverse=True)
997
for path, trans_id, kind in entries:
1000
delete_any(self._limbodir)
1002
# We don't especially care *why* the dir is immortal.
1003
raise ImmortalLimbo(self._limbodir)
1005
if self._deletiondir is not None:
1006
delete_any(self._deletiondir)
1008
raise errors.ImmortalPendingDeletion(self._deletiondir)
1010
TreeTransformBase.finalize(self)
1012
def _limbo_name(self, trans_id):
1013
"""Generate the limbo name of a file"""
1014
limbo_name = self._limbo_files.get(trans_id)
1015
if limbo_name is not None:
1017
parent = self._new_parent.get(trans_id)
1018
# if the parent directory is already in limbo (e.g. when building a
1019
# tree), choose a limbo name inside the parent, to reduce further
1021
use_direct_path = False
1022
if self._new_contents.get(parent) == 'directory':
1023
filename = self._new_name.get(trans_id)
1024
if filename is not None:
1025
if parent not in self._limbo_children:
1026
self._limbo_children[parent] = set()
1027
self._limbo_children_names[parent] = {}
1028
use_direct_path = True
1029
# the direct path can only be used if no other file has
1030
# already taken this pathname, i.e. if the name is unused, or
1031
# if it is already associated with this trans_id.
1032
elif self._case_sensitive_target:
1033
if (self._limbo_children_names[parent].get(filename)
1034
in (trans_id, None)):
1035
use_direct_path = True
1037
for l_filename, l_trans_id in\
1038
self._limbo_children_names[parent].iteritems():
1039
if l_trans_id == trans_id:
1041
if l_filename.lower() == filename.lower():
1044
use_direct_path = True
1047
limbo_name = pathjoin(self._limbo_files[parent], filename)
1048
self._limbo_children[parent].add(trans_id)
1049
self._limbo_children_names[parent][filename] = trans_id
1051
limbo_name = pathjoin(self._limbodir, trans_id)
1052
self._needs_rename.add(trans_id)
1053
self._limbo_files[trans_id] = limbo_name
1056
def adjust_path(self, name, parent, trans_id):
1057
previous_parent = self._new_parent.get(trans_id)
1058
previous_name = self._new_name.get(trans_id)
1059
TreeTransformBase.adjust_path(self, name, parent, trans_id)
1060
if (trans_id in self._limbo_files and
1061
trans_id not in self._needs_rename):
1062
self._rename_in_limbo([trans_id])
1063
self._limbo_children[previous_parent].remove(trans_id)
1064
del self._limbo_children_names[previous_parent][previous_name]
1066
def _rename_in_limbo(self, trans_ids):
1067
"""Fix limbo names so that the right final path is produced.
1069
This means we outsmarted ourselves-- we tried to avoid renaming
1070
these files later by creating them with their final names in their
1071
final parents. But now the previous name or parent is no longer
1072
suitable, so we have to rename them.
1074
Even for trans_ids that have no new contents, we must remove their
1075
entries from _limbo_files, because they are now stale.
1077
for trans_id in trans_ids:
1078
old_path = self._limbo_files.pop(trans_id)
1079
if trans_id not in self._new_contents:
1081
new_path = self._limbo_name(trans_id)
1082
os.rename(old_path, new_path)
1084
def create_file(self, contents, trans_id, mode_id=None):
1085
"""Schedule creation of a new file.
1089
Contents is an iterator of strings, all of which will be written
1090
to the target destination.
1092
New file takes the permissions of any existing file with that id,
1093
unless mode_id is specified.
1095
name = self._limbo_name(trans_id)
1096
f = open(name, 'wb')
1099
unique_add(self._new_contents, trans_id, 'file')
1101
# Clean up the file, it never got registered so
1102
# TreeTransform.finalize() won't clean it up.
1107
f.writelines(contents)
1110
self._set_mode(trans_id, mode_id, S_ISREG)
1112
def _read_file_chunks(self, trans_id):
1113
cur_file = open(self._limbo_name(trans_id), 'rb')
1115
return cur_file.readlines()
1119
def _read_symlink_target(self, trans_id):
1120
return os.readlink(self._limbo_name(trans_id))
1122
def create_hardlink(self, path, trans_id):
1123
"""Schedule creation of a hard link"""
1124
name = self._limbo_name(trans_id)
1128
if e.errno != errno.EPERM:
1130
raise errors.HardLinkNotSupported(path)
1132
unique_add(self._new_contents, trans_id, 'file')
1134
# Clean up the file, it never got registered so
1135
# TreeTransform.finalize() won't clean it up.
1139
def create_directory(self, trans_id):
1140
"""Schedule creation of a new directory.
1142
See also new_directory.
1144
os.mkdir(self._limbo_name(trans_id))
1145
unique_add(self._new_contents, trans_id, 'directory')
1147
def create_symlink(self, target, trans_id):
1148
"""Schedule creation of a new symbolic link.
1150
target is a bytestring.
1151
See also new_symlink.
1154
os.symlink(target, self._limbo_name(trans_id))
1155
unique_add(self._new_contents, trans_id, 'symlink')
1158
path = FinalPaths(self).get_path(trans_id)
1161
raise UnableCreateSymlink(path=path)
1163
def cancel_creation(self, trans_id):
1164
"""Cancel the creation of new file contents."""
1165
del self._new_contents[trans_id]
1166
children = self._limbo_children.get(trans_id)
1167
# if this is a limbo directory with children, move them before removing
1169
if children is not None:
1170
self._rename_in_limbo(children)
1171
del self._limbo_children[trans_id]
1172
del self._limbo_children_names[trans_id]
1173
delete_any(self._limbo_name(trans_id))
1176
class TreeTransform(DiskTreeTransform):
1177
"""Represent a tree transformation.
1179
This object is designed to support incremental generation of the transform,
1182
However, it gives optimum performance when parent directories are created
1183
before their contents. The transform is then able to put child files
1184
directly in their parent directory, avoiding later renames.
1186
It is easy to produce malformed transforms, but they are generally
1187
harmless. Attempting to apply a malformed transform will cause an
1188
exception to be raised before any modifications are made to the tree.
1190
Many kinds of malformed transforms can be corrected with the
1191
resolve_conflicts function. The remaining ones indicate programming error,
1192
such as trying to create a file with no path.
1194
Two sets of file creation methods are supplied. Convenience methods are:
1199
These are composed of the low-level methods:
1201
* create_file or create_directory or create_symlink
1205
Transform/Transaction ids
1206
-------------------------
1207
trans_ids are temporary ids assigned to all files involved in a transform.
1208
It's possible, even common, that not all files in the Tree have trans_ids.
1210
trans_ids are used because filenames and file_ids are not good enough
1211
identifiers; filenames change, and not all files have file_ids. File-ids
1212
are also associated with trans-ids, so that moving a file moves its
1215
trans_ids are only valid for the TreeTransform that generated them.
1219
Limbo is a temporary directory use to hold new versions of files.
1220
Files are added to limbo by create_file, create_directory, create_symlink,
1221
and their convenience variants (new_*). Files may be removed from limbo
1222
using cancel_creation. Files are renamed from limbo into their final
1223
location as part of TreeTransform.apply
1225
Limbo must be cleaned up, by either calling TreeTransform.apply or
1226
calling TreeTransform.finalize.
1228
Files are placed into limbo inside their parent directories, where
1229
possible. This reduces subsequent renames, and makes operations involving
1230
lots of files faster. This optimization is only possible if the parent
1231
directory is created *before* creating any of its children, so avoid
1232
creating children before parents, where possible.
1236
This temporary directory is used by _FileMover for storing files that are
1237
about to be deleted. In case of rollback, the files will be restored.
1238
FileMover does not delete files until it is sure that a rollback will not
1241
def __init__(self, tree, pb=DummyProgress()):
1242
"""Note: a tree_write lock is taken on the tree.
1244
Use TreeTransform.finalize() to release the lock (can be omitted if
1245
TreeTransform.apply() called).
1247
tree.lock_tree_write()
1250
limbodir = urlutils.local_path_from_url(
1251
tree._transport.abspath('limbo'))
1255
if e.errno == errno.EEXIST:
1256
raise ExistingLimbo(limbodir)
1257
deletiondir = urlutils.local_path_from_url(
1258
tree._transport.abspath('pending-deletion'))
1260
os.mkdir(deletiondir)
1262
if e.errno == errno.EEXIST:
1263
raise errors.ExistingPendingDeletion(deletiondir)
1268
# Cache of realpath results, to speed up canonical_path
1269
self._realpaths = {}
1270
# Cache of relpath results, to speed up canonical_path
1272
DiskTreeTransform.__init__(self, tree, limbodir, pb,
1273
tree.case_sensitive)
1274
self._deletiondir = deletiondir
1276
def canonical_path(self, path):
1277
"""Get the canonical tree-relative path"""
1278
# don't follow final symlinks
1279
abs = self._tree.abspath(path)
1280
if abs in self._relpaths:
1281
return self._relpaths[abs]
1282
dirname, basename = os.path.split(abs)
1283
if dirname not in self._realpaths:
1284
self._realpaths[dirname] = os.path.realpath(dirname)
1285
dirname = self._realpaths[dirname]
1286
abs = pathjoin(dirname, basename)
1287
if dirname in self._relpaths:
1288
relpath = pathjoin(self._relpaths[dirname], basename)
1289
relpath = relpath.rstrip('/\\')
1291
relpath = self._tree.relpath(abs)
1292
self._relpaths[abs] = relpath
1295
def tree_kind(self, trans_id):
1296
"""Determine the file kind in the working tree.
1298
Raises NoSuchFile if the file does not exist
1300
path = self._tree_id_paths.get(trans_id)
1302
raise NoSuchFile(None)
1304
return file_kind(self._tree.abspath(path))
1306
if e.errno != errno.ENOENT:
1309
raise NoSuchFile(path)
1311
def _set_mode(self, trans_id, mode_id, typefunc):
1312
"""Set the mode of new file contents.
1313
The mode_id is the existing file to get the mode from (often the same
1314
as trans_id). The operation is only performed if there's a mode match
1315
according to typefunc.
1320
old_path = self._tree_id_paths[mode_id]
1324
mode = os.stat(self._tree.abspath(old_path)).st_mode
1326
if e.errno in (errno.ENOENT, errno.ENOTDIR):
1327
# Either old_path doesn't exist, or the parent of the
1328
# target is not a directory (but will be one eventually)
1329
# Either way, we know it doesn't exist *right now*
1330
# See also bug #248448
1335
os.chmod(self._limbo_name(trans_id), mode)
1337
def iter_tree_children(self, parent_id):
1338
"""Iterate through the entry's tree children, if any"""
1340
path = self._tree_id_paths[parent_id]
1344
children = os.listdir(self._tree.abspath(path))
1346
if not (osutils._is_error_enotdir(e)
1347
or e.errno in (errno.ENOENT, errno.ESRCH)):
1351
for child in children:
1352
childpath = joinpath(path, child)
1353
if self._tree.is_control_filename(childpath):
1355
yield self.trans_id_tree_path(childpath)
1358
def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
1359
"""Apply all changes to the inventory and filesystem.
1361
If filesystem or inventory conflicts are present, MalformedTransform
1364
If apply succeeds, finalize is not necessary.
1366
:param no_conflicts: if True, the caller guarantees there are no
1367
conflicts, so no check is made.
1368
:param precomputed_delta: An inventory delta to use instead of
1370
:param _mover: Supply an alternate FileMover, for testing
1372
if not no_conflicts:
1373
conflicts = self.find_conflicts()
1374
if len(conflicts) != 0:
1375
raise MalformedTransform(conflicts=conflicts)
1376
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1378
if precomputed_delta is None:
1379
child_pb.update('Apply phase', 0, 2)
1380
inventory_delta = self._generate_inventory_delta()
1383
inventory_delta = precomputed_delta
1386
mover = _FileMover()
1390
child_pb.update('Apply phase', 0 + offset, 2 + offset)
1391
self._apply_removals(mover)
1392
child_pb.update('Apply phase', 1 + offset, 2 + offset)
1393
modified_paths = self._apply_insertions(mover)
1398
mover.apply_deletions()
1401
self._tree.apply_inventory_delta(inventory_delta)
1404
return _TransformResults(modified_paths, self.rename_count)
1406
def _generate_inventory_delta(self):
1407
"""Generate an inventory delta for the current transform."""
1408
inventory_delta = []
1409
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1410
new_paths = self._inventory_altered()
1411
total_entries = len(new_paths) + len(self._removed_id)
1413
for num, trans_id in enumerate(self._removed_id):
1415
child_pb.update('removing file', num, total_entries)
1416
if trans_id == self._new_root:
1417
file_id = self._tree.get_root_id()
1419
file_id = self.tree_file_id(trans_id)
1420
# File-id isn't really being deleted, just moved
1421
if file_id in self._r_new_id:
1423
path = self._tree_id_paths[trans_id]
1424
inventory_delta.append((path, None, file_id, None))
1425
new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1427
entries = self._tree.iter_entries_by_dir(
1428
new_path_file_ids.values())
1429
old_paths = dict((e.file_id, p) for p, e in entries)
1431
for num, (path, trans_id) in enumerate(new_paths):
1433
child_pb.update('adding file',
1434
num + len(self._removed_id), total_entries)
1435
file_id = new_path_file_ids[trans_id]
1440
kind = self.final_kind(trans_id)
1442
kind = self._tree.stored_kind(file_id)
1443
parent_trans_id = self.final_parent(trans_id)
1444
parent_file_id = new_path_file_ids.get(parent_trans_id)
1445
if parent_file_id is None:
1446
parent_file_id = self.final_file_id(parent_trans_id)
1447
if trans_id in self._new_reference_revision:
1448
new_entry = inventory.TreeReference(
1450
self._new_name[trans_id],
1451
self.final_file_id(self._new_parent[trans_id]),
1452
None, self._new_reference_revision[trans_id])
1454
new_entry = inventory.make_entry(kind,
1455
self.final_name(trans_id),
1456
parent_file_id, file_id)
1457
old_path = old_paths.get(new_entry.file_id)
1458
new_executability = self._new_executability.get(trans_id)
1459
if new_executability is not None:
1460
new_entry.executable = new_executability
1461
inventory_delta.append(
1462
(old_path, path, new_entry.file_id, new_entry))
1465
return inventory_delta
1467
def _apply_removals(self, mover):
1468
"""Perform tree operations that remove directory/inventory names.
1470
That is, delete files that are to be deleted, and put any files that
1471
need renaming into limbo. This must be done in strict child-to-parent
1474
If inventory_delta is None, no inventory delta generation is performed.
1476
tree_paths = list(self._tree_path_ids.iteritems())
1477
tree_paths.sort(reverse=True)
1478
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1480
for num, data in enumerate(tree_paths):
1481
path, trans_id = data
1482
child_pb.update('removing file', num, len(tree_paths))
1483
full_path = self._tree.abspath(path)
1484
if trans_id in self._removed_contents:
1485
mover.pre_delete(full_path, os.path.join(self._deletiondir,
1487
elif trans_id in self._new_name or trans_id in \
1490
mover.rename(full_path, self._limbo_name(trans_id))
1492
if e.errno != errno.ENOENT:
1495
self.rename_count += 1
1499
def _apply_insertions(self, mover):
1500
"""Perform tree operations that insert directory/inventory names.
1502
That is, create any files that need to be created, and restore from
1503
limbo any files that needed renaming. This must be done in strict
1504
parent-to-child order.
1506
If inventory_delta is None, no inventory delta is calculated, and
1507
no list of modified paths is returned.
1509
new_paths = self.new_paths(filesystem_only=True)
1511
new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1513
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1515
for num, (path, trans_id) in enumerate(new_paths):
1517
child_pb.update('adding file', num, len(new_paths))
1518
full_path = self._tree.abspath(path)
1519
if trans_id in self._needs_rename:
1521
mover.rename(self._limbo_name(trans_id), full_path)
1523
# We may be renaming a dangling inventory id
1524
if e.errno != errno.ENOENT:
1527
self.rename_count += 1
1528
if (trans_id in self._new_contents or
1529
self.path_changed(trans_id)):
1530
if trans_id in self._new_contents:
1531
modified_paths.append(full_path)
1532
if trans_id in self._new_executability:
1533
self._set_executability(path, trans_id)
1536
self._new_contents.clear()
1537
return modified_paths
1540
class TransformPreview(DiskTreeTransform):
1541
"""A TreeTransform for generating preview trees.
1543
Unlike TreeTransform, this version works when the input tree is a
1544
RevisionTree, rather than a WorkingTree. As a result, it tends to ignore
1545
unversioned files in the input tree.
1548
def __init__(self, tree, pb=DummyProgress(), case_sensitive=True):
1550
limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
1551
DiskTreeTransform.__init__(self, tree, limbodir, pb, case_sensitive)
1553
def canonical_path(self, path):
1556
def tree_kind(self, trans_id):
1557
path = self._tree_id_paths.get(trans_id)
1559
raise NoSuchFile(None)
1560
file_id = self._tree.path2id(path)
1561
return self._tree.kind(file_id)
1563
def _set_mode(self, trans_id, mode_id, typefunc):
1564
"""Set the mode of new file contents.
1565
The mode_id is the existing file to get the mode from (often the same
1566
as trans_id). The operation is only performed if there's a mode match
1567
according to typefunc.
1569
# is it ok to ignore this? probably
1572
def iter_tree_children(self, parent_id):
1573
"""Iterate through the entry's tree children, if any"""
1575
path = self._tree_id_paths[parent_id]
1578
file_id = self.tree_file_id(parent_id)
1581
entry = self._tree.iter_entries_by_dir([file_id]).next()[1]
1582
children = getattr(entry, 'children', {})
1583
for child in children:
1584
childpath = joinpath(path, child)
1585
yield self.trans_id_tree_path(childpath)
1588
class _PreviewTree(tree.Tree):
1589
"""Partial implementation of Tree to support show_diff_trees"""
1591
def __init__(self, transform):
1592
self._transform = transform
1593
self._final_paths = FinalPaths(transform)
1594
self.__by_parent = None
1595
self._parent_ids = []
1596
self._all_children_cache = {}
1597
self._path2trans_id_cache = {}
1598
self._final_name_cache = {}
1600
def _changes(self, file_id):
1601
for changes in self._transform.iter_changes():
1602
if changes[0] == file_id:
1605
def _content_change(self, file_id):
1606
"""Return True if the content of this file changed"""
1607
changes = self._changes(file_id)
1608
# changes[2] is true if the file content changed. See
1609
# InterTree.iter_changes.
1610
return (changes is not None and changes[2])
1612
def _get_repository(self):
1613
repo = getattr(self._transform._tree, '_repository', None)
1615
repo = self._transform._tree.branch.repository
1618
def _iter_parent_trees(self):
1619
for revision_id in self.get_parent_ids():
1621
yield self.revision_tree(revision_id)
1622
except errors.NoSuchRevisionInTree:
1623
yield self._get_repository().revision_tree(revision_id)
1625
def _get_file_revision(self, file_id, vf, tree_revision):
1626
parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
1627
self._iter_parent_trees()]
1628
vf.add_lines((file_id, tree_revision), parent_keys,
1629
self.get_file(file_id).readlines())
1630
repo = self._get_repository()
1631
base_vf = repo.texts
1632
if base_vf not in vf.fallback_versionedfiles:
1633
vf.fallback_versionedfiles.append(base_vf)
1634
return tree_revision
1636
def _stat_limbo_file(self, file_id):
1637
trans_id = self._transform.trans_id_file_id(file_id)
1638
name = self._transform._limbo_name(trans_id)
1639
return os.lstat(name)
1642
def _by_parent(self):
1643
if self.__by_parent is None:
1644
self.__by_parent = self._transform.by_parent()
1645
return self.__by_parent
1647
def _comparison_data(self, entry, path):
1648
kind, size, executable, link_or_sha1 = self.path_content_summary(path)
1649
if kind == 'missing':
1653
file_id = self._transform.final_file_id(self._path2trans_id(path))
1654
executable = self.is_executable(file_id, path)
1655
return kind, executable, None
1657
def lock_read(self):
1658
# Perhaps in theory, this should lock the TreeTransform?
1665
def inventory(self):
1666
"""This Tree does not use inventory as its backing data."""
1667
raise NotImplementedError(_PreviewTree.inventory)
1669
def get_root_id(self):
1670
return self._transform.final_file_id(self._transform.root)
1672
def all_file_ids(self):
1673
tree_ids = set(self._transform._tree.all_file_ids())
1674
tree_ids.difference_update(self._transform.tree_file_id(t)
1675
for t in self._transform._removed_id)
1676
tree_ids.update(self._transform._new_id.values())
1680
return iter(self.all_file_ids())
1682
def has_id(self, file_id):
1683
if file_id in self._transform._r_new_id:
1685
elif file_id in set([self._transform.tree_file_id(trans_id) for
1686
trans_id in self._transform._removed_id]):
1689
return self._transform._tree.has_id(file_id)
1691
def _path2trans_id(self, path):
1692
# We must not use None here, because that is a valid value to store.
1693
trans_id = self._path2trans_id_cache.get(path, object)
1694
if trans_id is not object:
1696
segments = splitpath(path)
1697
cur_parent = self._transform.root
1698
for cur_segment in segments:
1699
for child in self._all_children(cur_parent):
1700
final_name = self._final_name_cache.get(child)
1701
if final_name is None:
1702
final_name = self._transform.final_name(child)
1703
self._final_name_cache[child] = final_name
1704
if final_name == cur_segment:
1708
self._path2trans_id_cache[path] = None
1710
self._path2trans_id_cache[path] = cur_parent
1713
def path2id(self, path):
1714
return self._transform.final_file_id(self._path2trans_id(path))
1716
def id2path(self, file_id):
1717
trans_id = self._transform.trans_id_file_id(file_id)
1719
return self._final_paths._determine_path(trans_id)
1721
raise errors.NoSuchId(self, file_id)
1723
def _all_children(self, trans_id):
1724
children = self._all_children_cache.get(trans_id)
1725
if children is not None:
1727
children = set(self._transform.iter_tree_children(trans_id))
1728
# children in the _new_parent set are provided by _by_parent.
1729
children.difference_update(self._transform._new_parent.keys())
1730
children.update(self._by_parent.get(trans_id, []))
1731
self._all_children_cache[trans_id] = children
1734
def iter_children(self, file_id):
1735
trans_id = self._transform.trans_id_file_id(file_id)
1736
for child_trans_id in self._all_children(trans_id):
1737
yield self._transform.final_file_id(child_trans_id)
1740
possible_extras = set(self._transform.trans_id_tree_path(p) for p
1741
in self._transform._tree.extras())
1742
possible_extras.update(self._transform._new_contents)
1743
possible_extras.update(self._transform._removed_id)
1744
for trans_id in possible_extras:
1745
if self._transform.final_file_id(trans_id) is None:
1746
yield self._final_paths._determine_path(trans_id)
1748
def _make_inv_entries(self, ordered_entries, specific_file_ids=None):
1749
for trans_id, parent_file_id in ordered_entries:
1750
file_id = self._transform.final_file_id(trans_id)
1753
if (specific_file_ids is not None
1754
and file_id not in specific_file_ids):
1757
kind = self._transform.final_kind(trans_id)
1759
kind = self._transform._tree.stored_kind(file_id)
1760
new_entry = inventory.make_entry(
1762
self._transform.final_name(trans_id),
1763
parent_file_id, file_id)
1764
yield new_entry, trans_id
1766
def _list_files_by_dir(self):
1767
todo = [ROOT_PARENT]
1769
while len(todo) > 0:
1771
parent_file_id = self._transform.final_file_id(parent)
1772
children = list(self._all_children(parent))
1773
paths = dict(zip(children, self._final_paths.get_paths(children)))
1774
children.sort(key=paths.get)
1775
todo.extend(reversed(children))
1776
for trans_id in children:
1777
ordered_ids.append((trans_id, parent_file_id))
1780
def iter_entries_by_dir(self, specific_file_ids=None):
1781
# This may not be a maximally efficient implementation, but it is
1782
# reasonably straightforward. An implementation that grafts the
1783
# TreeTransform changes onto the tree's iter_entries_by_dir results
1784
# might be more efficient, but requires tricky inferences about stack
1786
ordered_ids = self._list_files_by_dir()
1787
for entry, trans_id in self._make_inv_entries(ordered_ids,
1789
yield unicode(self._final_paths.get_path(trans_id)), entry
1791
def _iter_entries_for_dir(self, dir_path):
1792
"""Return path, entry for items in a directory without recursing down."""
1793
dir_file_id = self.path2id(dir_path)
1795
for file_id in self.iter_children(dir_file_id):
1796
trans_id = self._transform.trans_id_file_id(file_id)
1797
ordered_ids.append((trans_id, file_id))
1798
for entry, trans_id in self._make_inv_entries(ordered_ids):
1799
yield unicode(self._final_paths.get_path(trans_id)), entry
1801
def list_files(self, include_root=False, from_dir=None, recursive=True):
1802
"""See WorkingTree.list_files."""
1803
# XXX This should behave like WorkingTree.list_files, but is really
1804
# more like RevisionTree.list_files.
1808
prefix = from_dir + '/'
1809
entries = self.iter_entries_by_dir()
1810
for path, entry in entries:
1811
if entry.name == '' and not include_root:
1814
if not path.startswith(prefix):
1816
path = path[len(prefix):]
1817
yield path, 'V', entry.kind, entry.file_id, entry
1819
if from_dir is None and include_root is True:
1820
root_entry = inventory.make_entry('directory', '',
1821
ROOT_PARENT, self.get_root_id())
1822
yield '', 'V', 'directory', root_entry.file_id, root_entry
1823
entries = self._iter_entries_for_dir(from_dir or '')
1824
for path, entry in entries:
1825
yield path, 'V', entry.kind, entry.file_id, entry
1827
def kind(self, file_id):
1828
trans_id = self._transform.trans_id_file_id(file_id)
1829
return self._transform.final_kind(trans_id)
1831
def stored_kind(self, file_id):
1832
trans_id = self._transform.trans_id_file_id(file_id)
1834
return self._transform._new_contents[trans_id]
1836
return self._transform._tree.stored_kind(file_id)
1838
def get_file_mtime(self, file_id, path=None):
1839
"""See Tree.get_file_mtime"""
1840
if not self._content_change(file_id):
1841
return self._transform._tree.get_file_mtime(file_id, path)
1842
return self._stat_limbo_file(file_id).st_mtime
1844
def _file_size(self, entry, stat_value):
1845
return self.get_file_size(entry.file_id)
1847
def get_file_size(self, file_id):
1848
"""See Tree.get_file_size"""
1849
if self.kind(file_id) == 'file':
1850
return self._transform._tree.get_file_size(file_id)
1854
def get_file_sha1(self, file_id, path=None, stat_value=None):
1855
trans_id = self._transform.trans_id_file_id(file_id)
1856
kind = self._transform._new_contents.get(trans_id)
1858
return self._transform._tree.get_file_sha1(file_id)
1860
fileobj = self.get_file(file_id)
1862
return sha_file(fileobj)
1866
def is_executable(self, file_id, path=None):
1869
trans_id = self._transform.trans_id_file_id(file_id)
1871
return self._transform._new_executability[trans_id]
1874
return self._transform._tree.is_executable(file_id, path)
1876
if e.errno == errno.ENOENT:
1879
except errors.NoSuchId:
1882
def path_content_summary(self, path):
1883
trans_id = self._path2trans_id(path)
1884
tt = self._transform
1885
tree_path = tt._tree_id_paths.get(trans_id)
1886
kind = tt._new_contents.get(trans_id)
1888
if tree_path is None or trans_id in tt._removed_contents:
1889
return 'missing', None, None, None
1890
summary = tt._tree.path_content_summary(tree_path)
1891
kind, size, executable, link_or_sha1 = summary
1894
limbo_name = tt._limbo_name(trans_id)
1895
if trans_id in tt._new_reference_revision:
1896
kind = 'tree-reference'
1898
statval = os.lstat(limbo_name)
1899
size = statval.st_size
1900
if not supports_executable():
1903
executable = statval.st_mode & S_IEXEC
1907
if kind == 'symlink':
1908
link_or_sha1 = os.readlink(limbo_name).decode(osutils._fs_enc)
1909
if supports_executable():
1910
executable = tt._new_executability.get(trans_id, executable)
1911
return kind, size, executable, link_or_sha1
1913
def iter_changes(self, from_tree, include_unchanged=False,
1914
specific_files=None, pb=None, extra_trees=None,
1915
require_versioned=True, want_unversioned=False):
1916
"""See InterTree.iter_changes.
1918
This has a fast path that is only used when the from_tree matches
1919
the transform tree, and no fancy options are supplied.
1921
if (from_tree is not self._transform._tree or include_unchanged or
1922
specific_files or want_unversioned):
1923
return tree.InterTree(from_tree, self).iter_changes(
1924
include_unchanged=include_unchanged,
1925
specific_files=specific_files,
1927
extra_trees=extra_trees,
1928
require_versioned=require_versioned,
1929
want_unversioned=want_unversioned)
1930
if want_unversioned:
1931
raise ValueError('want_unversioned is not supported')
1932
return self._transform.iter_changes()
1934
def get_file(self, file_id, path=None):
1935
"""See Tree.get_file"""
1936
if not self._content_change(file_id):
1937
return self._transform._tree.get_file(file_id, path)
1938
trans_id = self._transform.trans_id_file_id(file_id)
1939
name = self._transform._limbo_name(trans_id)
1940
return open(name, 'rb')
1942
def get_file_with_stat(self, file_id, path=None):
1943
return self.get_file(file_id, path), None
1945
def annotate_iter(self, file_id,
1946
default_revision=_mod_revision.CURRENT_REVISION):
1947
changes = self._changes(file_id)
1951
changed_content, versioned, kind = (changes[2], changes[3],
1955
get_old = (kind[0] == 'file' and versioned[0])
1957
old_annotation = self._transform._tree.annotate_iter(file_id,
1958
default_revision=default_revision)
1962
return old_annotation
1963
if not changed_content:
1964
return old_annotation
1965
return annotate.reannotate([old_annotation],
1966
self.get_file(file_id).readlines(),
1969
def get_symlink_target(self, file_id):
1970
"""See Tree.get_symlink_target"""
1971
if not self._content_change(file_id):
1972
return self._transform._tree.get_symlink_target(file_id)
1973
trans_id = self._transform.trans_id_file_id(file_id)
1974
name = self._transform._limbo_name(trans_id)
1975
return osutils.readlink(name)
1977
def walkdirs(self, prefix=''):
1978
pending = [self._transform.root]
1979
while len(pending) > 0:
1980
parent_id = pending.pop()
1983
prefix = prefix.rstrip('/')
1984
parent_path = self._final_paths.get_path(parent_id)
1985
parent_file_id = self._transform.final_file_id(parent_id)
1986
for child_id in self._all_children(parent_id):
1987
path_from_root = self._final_paths.get_path(child_id)
1988
basename = self._transform.final_name(child_id)
1989
file_id = self._transform.final_file_id(child_id)
1991
kind = self._transform.final_kind(child_id)
1992
versioned_kind = kind
1995
versioned_kind = self._transform._tree.stored_kind(file_id)
1996
if versioned_kind == 'directory':
1997
subdirs.append(child_id)
1998
children.append((path_from_root, basename, kind, None,
1999
file_id, versioned_kind))
2001
if parent_path.startswith(prefix):
2002
yield (parent_path, parent_file_id), children
2003
pending.extend(sorted(subdirs, key=self._final_paths.get_path,
2006
def get_parent_ids(self):
2007
return self._parent_ids
2009
def set_parent_ids(self, parent_ids):
2010
self._parent_ids = parent_ids
2012
def get_revision_tree(self, revision_id):
2013
return self._transform._tree.get_revision_tree(revision_id)
1176
2016
def joinpath(parent, child):
1177
2017
"""Join tree-relative paths, handling the tree root specially"""