923
1067
def get_preview_tree(self):
924
1068
"""Return a tree representing the result of the transform.
926
The tree is a snapshot, and altering the TreeTransform will invalidate
1070
This tree only supports the subset of Tree functionality required
1071
by show_diff_trees. It must only be compared to tt._tree.
929
1073
return _PreviewTree(self)
931
def commit(self, branch, message, merge_parents=None, strict=False,
932
timestamp=None, timezone=None, committer=None, authors=None,
933
revprops=None, revision_id=None):
934
"""Commit the result of this TreeTransform to a branch.
936
:param branch: The branch to commit to.
937
:param message: The message to attach to the commit.
938
:param merge_parents: Additional parent revision-ids specified by
940
:param strict: If True, abort the commit if there are unversioned
942
:param timestamp: if not None, seconds-since-epoch for the time and
943
date. (May be a float.)
944
:param timezone: Optional timezone for timestamp, as an offset in
946
:param committer: Optional committer in email-id format.
947
(e.g. "J Random Hacker <jrandom@example.com>")
948
:param authors: Optional list of authors in email-id format.
949
:param revprops: Optional dictionary of revision properties.
950
:param revision_id: Optional revision id. (Specifying a revision-id
951
may reduce performance for some non-native formats.)
952
:return: The revision_id of the revision committed.
954
self._check_malformed()
956
unversioned = set(self._new_contents).difference(set(self._new_id))
957
for trans_id in unversioned:
958
if self.final_file_id(trans_id) is None:
959
raise errors.StrictCommitFailed()
961
revno, last_rev_id = branch.last_revision_info()
962
if last_rev_id == _mod_revision.NULL_REVISION:
963
if merge_parents is not None:
964
raise ValueError('Cannot supply merge parents for first'
968
parent_ids = [last_rev_id]
969
if merge_parents is not None:
970
parent_ids.extend(merge_parents)
971
if self._tree.get_revision_id() != last_rev_id:
972
raise ValueError('TreeTransform not based on branch basis: %s' %
973
self._tree.get_revision_id())
974
revprops = commit.Commit.update_revprops(revprops, branch, authors)
975
builder = branch.get_commit_builder(parent_ids,
980
revision_id=revision_id)
981
preview = self.get_preview_tree()
982
list(builder.record_iter_changes(preview, last_rev_id,
983
self.iter_changes()))
984
builder.finish_inventory()
985
revision_id = builder.commit(message)
986
branch.set_last_revision_info(revno + 1, revision_id)
989
def _text_parent(self, trans_id):
990
file_id = self.tree_file_id(trans_id)
992
if file_id is None or self._tree.kind(file_id) != 'file':
994
except errors.NoSuchFile:
998
def _get_parents_texts(self, trans_id):
999
"""Get texts for compression parents of this file."""
1000
file_id = self._text_parent(trans_id)
1003
return (self._tree.get_file_text(file_id),)
1005
def _get_parents_lines(self, trans_id):
1006
"""Get lines for compression parents of this file."""
1007
file_id = self._text_parent(trans_id)
1010
return (self._tree.get_file_lines(file_id),)
1012
def serialize(self, serializer):
1013
"""Serialize this TreeTransform.
1015
:param serializer: A Serialiser like pack.ContainerSerializer.
1017
new_name = dict((k, v.encode('utf-8')) for k, v in
1018
self._new_name.items())
1019
new_executability = dict((k, int(v)) for k, v in
1020
self._new_executability.items())
1021
tree_path_ids = dict((k.encode('utf-8'), v)
1022
for k, v in self._tree_path_ids.items())
1024
'_id_number': self._id_number,
1025
'_new_name': new_name,
1026
'_new_parent': self._new_parent,
1027
'_new_executability': new_executability,
1028
'_new_id': self._new_id,
1029
'_tree_path_ids': tree_path_ids,
1030
'_removed_id': list(self._removed_id),
1031
'_removed_contents': list(self._removed_contents),
1032
'_non_present_ids': self._non_present_ids,
1034
yield serializer.bytes_record(bencode.bencode(attribs),
1036
for trans_id, kind in self._new_contents.items():
1038
lines = osutils.chunks_to_lines(
1039
self._read_file_chunks(trans_id))
1040
parents = self._get_parents_lines(trans_id)
1041
mpdiff = multiparent.MultiParent.from_lines(lines, parents)
1042
content = ''.join(mpdiff.to_patch())
1043
if kind == 'directory':
1045
if kind == 'symlink':
1046
content = self._read_symlink_target(trans_id)
1047
yield serializer.bytes_record(content, ((trans_id, kind),))
1049
def deserialize(self, records):
1050
"""Deserialize a stored TreeTransform.
1052
:param records: An iterable of (names, content) tuples, as per
1053
pack.ContainerPushParser.
1055
names, content = records.next()
1056
attribs = bencode.bdecode(content)
1057
self._id_number = attribs['_id_number']
1058
self._new_name = dict((k, v.decode('utf-8'))
1059
for k, v in attribs['_new_name'].items())
1060
self._new_parent = attribs['_new_parent']
1061
self._new_executability = dict((k, bool(v)) for k, v in
1062
attribs['_new_executability'].items())
1063
self._new_id = attribs['_new_id']
1064
self._r_new_id = dict((v, k) for k, v in self._new_id.items())
1065
self._tree_path_ids = {}
1066
self._tree_id_paths = {}
1067
for bytepath, trans_id in attribs['_tree_path_ids'].items():
1068
path = bytepath.decode('utf-8')
1069
self._tree_path_ids[path] = trans_id
1070
self._tree_id_paths[trans_id] = path
1071
self._removed_id = set(attribs['_removed_id'])
1072
self._removed_contents = set(attribs['_removed_contents'])
1073
self._non_present_ids = attribs['_non_present_ids']
1074
for ((trans_id, kind),), content in records:
1076
mpdiff = multiparent.MultiParent.from_patch(content)
1077
lines = mpdiff.to_lines(self._get_parents_texts(trans_id))
1078
self.create_file(lines, trans_id)
1079
if kind == 'directory':
1080
self.create_directory(trans_id)
1081
if kind == 'symlink':
1082
self.create_symlink(content.decode('utf-8'), trans_id)
1085
class DiskTreeTransform(TreeTransformBase):
1086
"""Tree transform storing its contents on disk."""
1088
def __init__(self, tree, limbodir, pb=None,
1089
case_sensitive=True):
1091
:param tree: The tree that will be transformed, but not necessarily
1093
:param limbodir: A directory where new files can be stored until
1094
they are installed in their proper places
1096
:param case_sensitive: If True, the target of the transform is
1097
case sensitive, not just case preserving.
1099
TreeTransformBase.__init__(self, tree, pb, case_sensitive)
1100
self._limbodir = limbodir
1101
self._deletiondir = None
1102
# A mapping of transform ids to their limbo filename
1103
self._limbo_files = {}
1104
# A mapping of transform ids to a set of the transform ids of children
1105
# that their limbo directory has
1106
self._limbo_children = {}
1107
# Map transform ids to maps of child filename to child transform id
1108
self._limbo_children_names = {}
1109
# List of transform ids that need to be renamed from limbo into place
1110
self._needs_rename = set()
1111
self._creation_mtime = None
1114
"""Release the working tree lock, if held, clean up limbo dir.
1116
This is required if apply has not been invoked, but can be invoked
1119
if self._tree is None:
1122
entries = [(self._limbo_name(t), t, k) for t, k in
1123
self._new_contents.iteritems()]
1124
entries.sort(reverse=True)
1125
for path, trans_id, kind in entries:
1128
delete_any(self._limbodir)
1130
# We don't especially care *why* the dir is immortal.
1131
raise ImmortalLimbo(self._limbodir)
1133
if self._deletiondir is not None:
1134
delete_any(self._deletiondir)
1136
raise errors.ImmortalPendingDeletion(self._deletiondir)
1138
TreeTransformBase.finalize(self)
1140
def _limbo_name(self, trans_id):
1141
"""Generate the limbo name of a file"""
1142
limbo_name = self._limbo_files.get(trans_id)
1143
if limbo_name is None:
1144
limbo_name = self._generate_limbo_path(trans_id)
1145
self._limbo_files[trans_id] = limbo_name
1148
def _generate_limbo_path(self, trans_id):
1149
"""Generate a limbo path using the trans_id as the relative path.
1151
This is suitable as a fallback, and when the transform should not be
1152
sensitive to the path encoding of the limbo directory.
1154
self._needs_rename.add(trans_id)
1155
return pathjoin(self._limbodir, trans_id)
1157
def adjust_path(self, name, parent, trans_id):
1158
previous_parent = self._new_parent.get(trans_id)
1159
previous_name = self._new_name.get(trans_id)
1160
TreeTransformBase.adjust_path(self, name, parent, trans_id)
1161
if (trans_id in self._limbo_files and
1162
trans_id not in self._needs_rename):
1163
self._rename_in_limbo([trans_id])
1164
if previous_parent != parent:
1165
self._limbo_children[previous_parent].remove(trans_id)
1166
if previous_parent != parent or previous_name != name:
1167
del self._limbo_children_names[previous_parent][previous_name]
1169
def _rename_in_limbo(self, trans_ids):
1170
"""Fix limbo names so that the right final path is produced.
1172
This means we outsmarted ourselves-- we tried to avoid renaming
1173
these files later by creating them with their final names in their
1174
final parents. But now the previous name or parent is no longer
1175
suitable, so we have to rename them.
1177
Even for trans_ids that have no new contents, we must remove their
1178
entries from _limbo_files, because they are now stale.
1180
for trans_id in trans_ids:
1181
old_path = self._limbo_files.pop(trans_id)
1182
if trans_id not in self._new_contents:
1184
new_path = self._limbo_name(trans_id)
1185
osutils.rename(old_path, new_path)
1186
for descendant in self._limbo_descendants(trans_id):
1187
desc_path = self._limbo_files[descendant]
1188
desc_path = new_path + desc_path[len(old_path):]
1189
self._limbo_files[descendant] = desc_path
1191
def _limbo_descendants(self, trans_id):
1192
"""Return the set of trans_ids whose limbo paths descend from this."""
1193
descendants = set(self._limbo_children.get(trans_id, []))
1194
for descendant in list(descendants):
1195
descendants.update(self._limbo_descendants(descendant))
1198
def create_file(self, contents, trans_id, mode_id=None):
1199
"""Schedule creation of a new file.
1203
Contents is an iterator of strings, all of which will be written
1204
to the target destination.
1206
New file takes the permissions of any existing file with that id,
1207
unless mode_id is specified.
1209
name = self._limbo_name(trans_id)
1210
f = open(name, 'wb')
1213
unique_add(self._new_contents, trans_id, 'file')
1215
# Clean up the file, it never got registered so
1216
# TreeTransform.finalize() won't clean it up.
1221
f.writelines(contents)
1224
self._set_mtime(name)
1225
self._set_mode(trans_id, mode_id, S_ISREG)
1227
def _read_file_chunks(self, trans_id):
1228
cur_file = open(self._limbo_name(trans_id), 'rb')
1230
return cur_file.readlines()
1234
def _read_symlink_target(self, trans_id):
1235
return os.readlink(self._limbo_name(trans_id))
1237
def _set_mtime(self, path):
1238
"""All files that are created get the same mtime.
1240
This time is set by the first object to be created.
1242
if self._creation_mtime is None:
1243
self._creation_mtime = time.time()
1244
os.utime(path, (self._creation_mtime, self._creation_mtime))
1246
def create_hardlink(self, path, trans_id):
1247
"""Schedule creation of a hard link"""
1248
name = self._limbo_name(trans_id)
1252
if e.errno != errno.EPERM:
1254
raise errors.HardLinkNotSupported(path)
1256
unique_add(self._new_contents, trans_id, 'file')
1258
# Clean up the file, it never got registered so
1259
# TreeTransform.finalize() won't clean it up.
1263
def create_directory(self, trans_id):
1264
"""Schedule creation of a new directory.
1266
See also new_directory.
1268
os.mkdir(self._limbo_name(trans_id))
1269
unique_add(self._new_contents, trans_id, 'directory')
1271
def create_symlink(self, target, trans_id):
1272
"""Schedule creation of a new symbolic link.
1274
target is a bytestring.
1275
See also new_symlink.
1278
os.symlink(target, self._limbo_name(trans_id))
1279
unique_add(self._new_contents, trans_id, 'symlink')
1282
path = FinalPaths(self).get_path(trans_id)
1285
raise UnableCreateSymlink(path=path)
1287
def cancel_creation(self, trans_id):
1288
"""Cancel the creation of new file contents."""
1289
del self._new_contents[trans_id]
1290
children = self._limbo_children.get(trans_id)
1291
# if this is a limbo directory with children, move them before removing
1293
if children is not None:
1294
self._rename_in_limbo(children)
1295
del self._limbo_children[trans_id]
1296
del self._limbo_children_names[trans_id]
1297
delete_any(self._limbo_name(trans_id))
1300
class TreeTransform(DiskTreeTransform):
1076
class TreeTransform(TreeTransformBase):
1301
1077
"""Represent a tree transformation.
1303
1079
This object is designed to support incremental generation of the transform,
1392
# Cache of realpath results, to speed up canonical_path
1393
self._realpaths = {}
1394
# Cache of relpath results, to speed up canonical_path
1396
DiskTreeTransform.__init__(self, tree, limbodir, pb,
1169
TreeTransformBase.__init__(self, tree, limbodir, pb,
1397
1170
tree.case_sensitive)
1398
1171
self._deletiondir = deletiondir
1400
def canonical_path(self, path):
1401
"""Get the canonical tree-relative path"""
1402
# don't follow final symlinks
1403
abs = self._tree.abspath(path)
1404
if abs in self._relpaths:
1405
return self._relpaths[abs]
1406
dirname, basename = os.path.split(abs)
1407
if dirname not in self._realpaths:
1408
self._realpaths[dirname] = os.path.realpath(dirname)
1409
dirname = self._realpaths[dirname]
1410
abs = pathjoin(dirname, basename)
1411
if dirname in self._relpaths:
1412
relpath = pathjoin(self._relpaths[dirname], basename)
1413
relpath = relpath.rstrip('/\\')
1415
relpath = self._tree.relpath(abs)
1416
self._relpaths[abs] = relpath
1419
def tree_kind(self, trans_id):
1420
"""Determine the file kind in the working tree.
1422
Raises NoSuchFile if the file does not exist
1424
path = self._tree_id_paths.get(trans_id)
1426
raise NoSuchFile(None)
1428
return file_kind(self._tree.abspath(path))
1430
if e.errno != errno.ENOENT:
1433
raise NoSuchFile(path)
1435
def _set_mode(self, trans_id, mode_id, typefunc):
1436
"""Set the mode of new file contents.
1437
The mode_id is the existing file to get the mode from (often the same
1438
as trans_id). The operation is only performed if there's a mode match
1439
according to typefunc.
1444
old_path = self._tree_id_paths[mode_id]
1448
mode = os.stat(self._tree.abspath(old_path)).st_mode
1450
if e.errno in (errno.ENOENT, errno.ENOTDIR):
1451
# Either old_path doesn't exist, or the parent of the
1452
# target is not a directory (but will be one eventually)
1453
# Either way, we know it doesn't exist *right now*
1454
# See also bug #248448
1459
os.chmod(self._limbo_name(trans_id), mode)
1461
def iter_tree_children(self, parent_id):
1462
"""Iterate through the entry's tree children, if any"""
1464
path = self._tree_id_paths[parent_id]
1468
children = os.listdir(self._tree.abspath(path))
1470
if not (osutils._is_error_enotdir(e)
1471
or e.errno in (errno.ENOENT, errno.ESRCH)):
1475
for child in children:
1476
childpath = joinpath(path, child)
1477
if self._tree.is_control_filename(childpath):
1479
yield self.trans_id_tree_path(childpath)
1481
def _generate_limbo_path(self, trans_id):
1482
"""Generate a limbo path using the final path if possible.
1484
This optimizes the performance of applying the tree transform by
1485
avoiding renames. These renames can be avoided only when the parent
1486
directory is already scheduled for creation.
1488
If the final path cannot be used, falls back to using the trans_id as
1491
parent = self._new_parent.get(trans_id)
1492
# if the parent directory is already in limbo (e.g. when building a
1493
# tree), choose a limbo name inside the parent, to reduce further
1495
use_direct_path = False
1496
if self._new_contents.get(parent) == 'directory':
1497
filename = self._new_name.get(trans_id)
1498
if filename is not None:
1499
if parent not in self._limbo_children:
1500
self._limbo_children[parent] = set()
1501
self._limbo_children_names[parent] = {}
1502
use_direct_path = True
1503
# the direct path can only be used if no other file has
1504
# already taken this pathname, i.e. if the name is unused, or
1505
# if it is already associated with this trans_id.
1506
elif self._case_sensitive_target:
1507
if (self._limbo_children_names[parent].get(filename)
1508
in (trans_id, None)):
1509
use_direct_path = True
1511
for l_filename, l_trans_id in\
1512
self._limbo_children_names[parent].iteritems():
1513
if l_trans_id == trans_id:
1515
if l_filename.lower() == filename.lower():
1518
use_direct_path = True
1520
if not use_direct_path:
1521
return DiskTreeTransform._generate_limbo_path(self, trans_id)
1523
limbo_name = pathjoin(self._limbo_files[parent], filename)
1524
self._limbo_children[parent].add(trans_id)
1525
self._limbo_children_names[parent][filename] = trans_id
1529
def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
1173
def apply(self, no_conflicts=False, _mover=None):
1530
1174
"""Apply all changes to the inventory and filesystem.
1532
1176
If filesystem or inventory conflicts are present, MalformedTransform
1664
1239
self.rename_count += 1
1240
if trans_id in self._removed_id:
1241
if trans_id == self._new_root:
1242
file_id = self._tree.get_root_id()
1244
file_id = self.tree_file_id(trans_id)
1245
assert file_id is not None
1246
# File-id isn't really being deleted, just moved
1247
if file_id in self._r_new_id:
1249
inventory_delta.append((path, None, file_id, None))
1666
1251
child_pb.finished()
1668
def _apply_insertions(self, mover):
1253
def _apply_insertions(self, inventory_delta, mover):
1669
1254
"""Perform tree operations that insert directory/inventory names.
1671
1256
That is, create any files that need to be created, and restore from
1672
1257
limbo any files that needed renaming. This must be done in strict
1673
1258
parent-to-child order.
1675
If inventory_delta is None, no inventory delta is calculated, and
1676
no list of modified paths is returned.
1678
new_paths = self.new_paths(filesystem_only=True)
1260
new_paths = self.new_paths()
1679
1261
modified_paths = []
1680
new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1682
1262
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1684
1265
for num, (path, trans_id) in enumerate(new_paths):
1686
child_pb.update('adding file', num, len(new_paths))
1687
full_path = self._tree.abspath(path)
1688
if trans_id in self._needs_rename:
1690
mover.rename(self._limbo_name(trans_id), full_path)
1692
# We may be renaming a dangling inventory id
1693
if e.errno != errno.ENOENT:
1696
self.rename_count += 1
1697
if (trans_id in self._new_contents or
1698
self.path_changed(trans_id)):
1267
child_pb.update('adding file', num, len(new_paths))
1268
if trans_id in self._new_contents or \
1269
self.path_changed(trans_id):
1270
full_path = self._tree.abspath(path)
1271
if trans_id in self._needs_rename:
1273
mover.rename(self._limbo_name(trans_id), full_path)
1275
# We may be renaming a dangling inventory id
1276
if e.errno != errno.ENOENT:
1279
self.rename_count += 1
1699
1280
if trans_id in self._new_contents:
1700
1281
modified_paths.append(full_path)
1282
completed_new.append(trans_id)
1283
file_id = self.final_file_id(trans_id)
1284
if file_id is not None and (trans_id in self._new_id or
1285
trans_id in self._new_name or trans_id in self._new_parent
1286
or trans_id in self._new_executability):
1288
kind = self.final_kind(trans_id)
1290
kind = self._tree.stored_kind(file_id)
1291
if trans_id in self._new_reference_revision:
1292
new_entry = inventory.TreeReference(
1293
self.final_file_id(trans_id),
1294
self._new_name[trans_id],
1295
self.final_file_id(self._new_parent[trans_id]),
1296
None, self._new_reference_revision[trans_id])
1298
new_entry = inventory.make_entry(kind,
1299
self.final_name(trans_id),
1300
self.final_file_id(self.final_parent(trans_id)),
1301
self.final_file_id(trans_id))
1303
old_path = self._tree.id2path(new_entry.file_id)
1304
except errors.NoSuchId:
1306
inventory_delta.append((old_path, path, new_entry.file_id,
1701
1309
if trans_id in self._new_executability:
1702
self._set_executability(path, trans_id)
1310
self._set_executability(path, new_entry, trans_id)
1704
1312
child_pb.finished()
1705
self._new_contents.clear()
1313
for trans_id in completed_new:
1314
del self._new_contents[trans_id]
1706
1315
return modified_paths
1709
class TransformPreview(DiskTreeTransform):
1318
class TransformPreview(TreeTransformBase):
1710
1319
"""A TreeTransform for generating preview trees.
1712
1321
Unlike TreeTransform, this version works when the input tree is a
1745
1354
except KeyError:
1747
1356
file_id = self.tree_file_id(parent_id)
1750
entry = self._tree.iter_entries_by_dir([file_id]).next()[1]
1751
children = getattr(entry, 'children', {})
1752
for child in children:
1357
for child in self._tree.inventory[file_id].children.iterkeys():
1753
1358
childpath = joinpath(path, child)
1754
1359
yield self.trans_id_tree_path(childpath)
1757
class _PreviewTree(tree.Tree):
1362
class _PreviewTree(object):
1758
1363
"""Partial implementation of Tree to support show_diff_trees"""
1760
1365
def __init__(self, transform):
1761
1366
self._transform = transform
1762
self._final_paths = FinalPaths(transform)
1763
self.__by_parent = None
1764
self._parent_ids = []
1765
self._all_children_cache = {}
1766
self._path2trans_id_cache = {}
1767
self._final_name_cache = {}
1768
self._iter_changes_cache = dict((c[0], c) for c in
1769
self._transform.iter_changes())
1771
def _content_change(self, file_id):
1772
"""Return True if the content of this file changed"""
1773
changes = self._iter_changes_cache.get(file_id)
1774
# changes[2] is true if the file content changed. See
1775
# InterTree.iter_changes.
1776
return (changes is not None and changes[2])
1778
def _get_repository(self):
1779
repo = getattr(self._transform._tree, '_repository', None)
1781
repo = self._transform._tree.branch.repository
1784
def _iter_parent_trees(self):
1785
for revision_id in self.get_parent_ids():
1787
yield self.revision_tree(revision_id)
1788
except errors.NoSuchRevisionInTree:
1789
yield self._get_repository().revision_tree(revision_id)
1791
def _get_file_revision(self, file_id, vf, tree_revision):
1792
parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
1793
self._iter_parent_trees()]
1794
vf.add_lines((file_id, tree_revision), parent_keys,
1795
self.get_file(file_id).readlines())
1796
repo = self._get_repository()
1797
base_vf = repo.texts
1798
if base_vf not in vf.fallback_versionedfiles:
1799
vf.fallback_versionedfiles.append(base_vf)
1800
return tree_revision
1802
def _stat_limbo_file(self, file_id):
1803
trans_id = self._transform.trans_id_file_id(file_id)
1804
name = self._transform._limbo_name(trans_id)
1805
return os.lstat(name)
1808
def _by_parent(self):
1809
if self.__by_parent is None:
1810
self.__by_parent = self._transform.by_parent()
1811
return self.__by_parent
1813
def _comparison_data(self, entry, path):
1814
kind, size, executable, link_or_sha1 = self.path_content_summary(path)
1815
if kind == 'missing':
1819
file_id = self._transform.final_file_id(self._path2trans_id(path))
1820
executable = self.is_executable(file_id, path)
1821
return kind, executable, None
1823
def is_locked(self):
1826
1368
def lock_read(self):
1827
1369
# Perhaps in theory, this should lock the TreeTransform?
1830
1372
def unlock(self):
1834
def inventory(self):
1835
"""This Tree does not use inventory as its backing data."""
1836
raise NotImplementedError(_PreviewTree.inventory)
1838
def get_root_id(self):
1839
return self._transform.final_file_id(self._transform.root)
1841
def all_file_ids(self):
1842
tree_ids = set(self._transform._tree.all_file_ids())
1843
tree_ids.difference_update(self._transform.tree_file_id(t)
1844
for t in self._transform._removed_id)
1845
tree_ids.update(self._transform._new_id.values())
1849
return iter(self.all_file_ids())
1851
def _has_id(self, file_id, fallback_check):
1852
if file_id in self._transform._r_new_id:
1854
elif file_id in set([self._transform.tree_file_id(trans_id) for
1855
trans_id in self._transform._removed_id]):
1858
return fallback_check(file_id)
1860
def has_id(self, file_id):
1861
return self._has_id(file_id, self._transform._tree.has_id)
1863
def has_or_had_id(self, file_id):
1864
return self._has_id(file_id, self._transform._tree.has_or_had_id)
1866
def _path2trans_id(self, path):
1867
# We must not use None here, because that is a valid value to store.
1868
trans_id = self._path2trans_id_cache.get(path, object)
1869
if trans_id is not object:
1871
segments = splitpath(path)
1872
cur_parent = self._transform.root
1873
for cur_segment in segments:
1874
for child in self._all_children(cur_parent):
1875
final_name = self._final_name_cache.get(child)
1876
if final_name is None:
1877
final_name = self._transform.final_name(child)
1878
self._final_name_cache[child] = final_name
1879
if final_name == cur_segment:
1883
self._path2trans_id_cache[path] = None
1885
self._path2trans_id_cache[path] = cur_parent
1888
def path2id(self, path):
1889
return self._transform.final_file_id(self._path2trans_id(path))
1891
def id2path(self, file_id):
1892
trans_id = self._transform.trans_id_file_id(file_id)
1894
return self._final_paths._determine_path(trans_id)
1896
raise errors.NoSuchId(self, file_id)
1898
def _all_children(self, trans_id):
1899
children = self._all_children_cache.get(trans_id)
1900
if children is not None:
1902
children = set(self._transform.iter_tree_children(trans_id))
1903
# children in the _new_parent set are provided by _by_parent.
1904
children.difference_update(self._transform._new_parent.keys())
1905
children.update(self._by_parent.get(trans_id, []))
1906
self._all_children_cache[trans_id] = children
1909
def iter_children(self, file_id):
1910
trans_id = self._transform.trans_id_file_id(file_id)
1911
for child_trans_id in self._all_children(trans_id):
1912
yield self._transform.final_file_id(child_trans_id)
1915
possible_extras = set(self._transform.trans_id_tree_path(p) for p
1916
in self._transform._tree.extras())
1917
possible_extras.update(self._transform._new_contents)
1918
possible_extras.update(self._transform._removed_id)
1919
for trans_id in possible_extras:
1920
if self._transform.final_file_id(trans_id) is None:
1921
yield self._final_paths._determine_path(trans_id)
1923
def _make_inv_entries(self, ordered_entries, specific_file_ids=None,
1924
yield_parents=False):
1925
for trans_id, parent_file_id in ordered_entries:
1926
file_id = self._transform.final_file_id(trans_id)
1929
if (specific_file_ids is not None
1930
and file_id not in specific_file_ids):
1933
kind = self._transform.final_kind(trans_id)
1935
kind = self._transform._tree.stored_kind(file_id)
1936
new_entry = inventory.make_entry(
1938
self._transform.final_name(trans_id),
1939
parent_file_id, file_id)
1940
yield new_entry, trans_id
1942
def _list_files_by_dir(self):
1943
todo = [ROOT_PARENT]
1945
while len(todo) > 0:
1947
parent_file_id = self._transform.final_file_id(parent)
1948
children = list(self._all_children(parent))
1949
paths = dict(zip(children, self._final_paths.get_paths(children)))
1950
children.sort(key=paths.get)
1951
todo.extend(reversed(children))
1952
for trans_id in children:
1953
ordered_ids.append((trans_id, parent_file_id))
1956
def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
1957
# This may not be a maximally efficient implementation, but it is
1958
# reasonably straightforward. An implementation that grafts the
1959
# TreeTransform changes onto the tree's iter_entries_by_dir results
1960
# might be more efficient, but requires tricky inferences about stack
1962
ordered_ids = self._list_files_by_dir()
1963
for entry, trans_id in self._make_inv_entries(ordered_ids,
1964
specific_file_ids, yield_parents=yield_parents):
1965
yield unicode(self._final_paths.get_path(trans_id)), entry
1967
def _iter_entries_for_dir(self, dir_path):
1968
"""Return path, entry for items in a directory without recursing down."""
1969
dir_file_id = self.path2id(dir_path)
1971
for file_id in self.iter_children(dir_file_id):
1972
trans_id = self._transform.trans_id_file_id(file_id)
1973
ordered_ids.append((trans_id, file_id))
1974
for entry, trans_id in self._make_inv_entries(ordered_ids):
1975
yield unicode(self._final_paths.get_path(trans_id)), entry
1977
def list_files(self, include_root=False, from_dir=None, recursive=True):
1978
"""See WorkingTree.list_files."""
1979
# XXX This should behave like WorkingTree.list_files, but is really
1980
# more like RevisionTree.list_files.
1984
prefix = from_dir + '/'
1985
entries = self.iter_entries_by_dir()
1986
for path, entry in entries:
1987
if entry.name == '' and not include_root:
1990
if not path.startswith(prefix):
1992
path = path[len(prefix):]
1993
yield path, 'V', entry.kind, entry.file_id, entry
1995
if from_dir is None and include_root is True:
1996
root_entry = inventory.make_entry('directory', '',
1997
ROOT_PARENT, self.get_root_id())
1998
yield '', 'V', 'directory', root_entry.file_id, root_entry
1999
entries = self._iter_entries_for_dir(from_dir or '')
2000
for path, entry in entries:
2001
yield path, 'V', entry.kind, entry.file_id, entry
2003
def kind(self, file_id):
2004
trans_id = self._transform.trans_id_file_id(file_id)
2005
return self._transform.final_kind(trans_id)
2007
def stored_kind(self, file_id):
2008
trans_id = self._transform.trans_id_file_id(file_id)
2010
return self._transform._new_contents[trans_id]
2012
return self._transform._tree.stored_kind(file_id)
2014
def get_file_mtime(self, file_id, path=None):
2015
"""See Tree.get_file_mtime"""
2016
if not self._content_change(file_id):
2017
return self._transform._tree.get_file_mtime(file_id)
2018
return self._stat_limbo_file(file_id).st_mtime
2020
def _file_size(self, entry, stat_value):
2021
return self.get_file_size(entry.file_id)
2023
def get_file_size(self, file_id):
2024
"""See Tree.get_file_size"""
2025
if self.kind(file_id) == 'file':
2026
return self._transform._tree.get_file_size(file_id)
2030
def get_file_sha1(self, file_id, path=None, stat_value=None):
2031
trans_id = self._transform.trans_id_file_id(file_id)
2032
kind = self._transform._new_contents.get(trans_id)
2034
return self._transform._tree.get_file_sha1(file_id)
2036
fileobj = self.get_file(file_id)
2038
return sha_file(fileobj)
2042
def is_executable(self, file_id, path=None):
2045
trans_id = self._transform.trans_id_file_id(file_id)
2047
return self._transform._new_executability[trans_id]
2050
return self._transform._tree.is_executable(file_id, path)
2052
if e.errno == errno.ENOENT:
2055
except errors.NoSuchId:
2058
def path_content_summary(self, path):
2059
trans_id = self._path2trans_id(path)
2060
tt = self._transform
2061
tree_path = tt._tree_id_paths.get(trans_id)
2062
kind = tt._new_contents.get(trans_id)
2064
if tree_path is None or trans_id in tt._removed_contents:
2065
return 'missing', None, None, None
2066
summary = tt._tree.path_content_summary(tree_path)
2067
kind, size, executable, link_or_sha1 = summary
2070
limbo_name = tt._limbo_name(trans_id)
2071
if trans_id in tt._new_reference_revision:
2072
kind = 'tree-reference'
2074
statval = os.lstat(limbo_name)
2075
size = statval.st_size
2076
if not supports_executable():
2079
executable = statval.st_mode & S_IEXEC
2083
if kind == 'symlink':
2084
link_or_sha1 = os.readlink(limbo_name).decode(osutils._fs_enc)
2085
executable = tt._new_executability.get(trans_id, executable)
2086
return kind, size, executable, link_or_sha1
2088
1375
def iter_changes(self, from_tree, include_unchanged=False,
2089
1376
specific_files=None, pb=None, extra_trees=None,
2090
1377
require_versioned=True, want_unversioned=False):
2091
1378
"""See InterTree.iter_changes.
2093
This has a fast path that is only used when the from_tree matches
2094
the transform tree, and no fancy options are supplied.
1380
This implementation does not support include_unchanged, specific_files,
1381
or want_unversioned. extra_trees, require_versioned, and pb are
2096
if (from_tree is not self._transform._tree or include_unchanged or
2097
specific_files or want_unversioned):
2098
return tree.InterTree(from_tree, self).iter_changes(
2099
include_unchanged=include_unchanged,
2100
specific_files=specific_files,
2102
extra_trees=extra_trees,
2103
require_versioned=require_versioned,
2104
want_unversioned=want_unversioned)
1384
if from_tree is not self._transform._tree:
1385
raise ValueError('from_tree must be transform source tree.')
1386
if include_unchanged:
1387
raise ValueError('include_unchanged is not supported')
1388
if specific_files is not None:
1389
raise ValueError('specific_files is not supported')
2105
1390
if want_unversioned:
2106
1391
raise ValueError('want_unversioned is not supported')
2107
1392
return self._transform.iter_changes()
2109
def get_file(self, file_id, path=None):
1394
def kind(self, file_id):
1395
trans_id = self._transform.trans_id_file_id(file_id)
1396
return self._transform.final_kind(trans_id)
1398
def get_file_mtime(self, file_id, path=None):
1399
"""See Tree.get_file_mtime"""
1400
trans_id = self._transform.trans_id_file_id(file_id)
1401
name = self._transform._limbo_name(trans_id)
1402
return os.stat(name).st_mtime
1404
def get_file(self, file_id):
2110
1405
"""See Tree.get_file"""
2111
if not self._content_change(file_id):
2112
return self._transform._tree.get_file(file_id, path)
2113
1406
trans_id = self._transform.trans_id_file_id(file_id)
2114
1407
name = self._transform._limbo_name(trans_id)
2115
1408
return open(name, 'rb')
2117
def get_file_with_stat(self, file_id, path=None):
2118
return self.get_file(file_id, path), None
2120
def annotate_iter(self, file_id,
2121
default_revision=_mod_revision.CURRENT_REVISION):
2122
changes = self._iter_changes_cache.get(file_id)
2126
changed_content, versioned, kind = (changes[2], changes[3],
2130
get_old = (kind[0] == 'file' and versioned[0])
2132
old_annotation = self._transform._tree.annotate_iter(file_id,
2133
default_revision=default_revision)
2137
return old_annotation
2138
if not changed_content:
2139
return old_annotation
2140
# TODO: This is doing something similar to what WT.annotate_iter is
2141
# doing, however it fails slightly because it doesn't know what
2142
# the *other* revision_id is, so it doesn't know how to give the
2143
# other as the origin for some lines, they all get
2144
# 'default_revision'
2145
# It would be nice to be able to use the new Annotator based
2146
# approach, as well.
2147
return annotate.reannotate([old_annotation],
2148
self.get_file(file_id).readlines(),
2151
1410
def get_symlink_target(self, file_id):
2152
1411
"""See Tree.get_symlink_target"""
2153
if not self._content_change(file_id):
2154
return self._transform._tree.get_symlink_target(file_id)
2155
1412
trans_id = self._transform.trans_id_file_id(file_id)
2156
1413
name = self._transform._limbo_name(trans_id)
2157
return osutils.readlink(name)
2159
def walkdirs(self, prefix=''):
2160
pending = [self._transform.root]
2161
while len(pending) > 0:
2162
parent_id = pending.pop()
2165
prefix = prefix.rstrip('/')
2166
parent_path = self._final_paths.get_path(parent_id)
2167
parent_file_id = self._transform.final_file_id(parent_id)
2168
for child_id in self._all_children(parent_id):
2169
path_from_root = self._final_paths.get_path(child_id)
2170
basename = self._transform.final_name(child_id)
2171
file_id = self._transform.final_file_id(child_id)
2173
kind = self._transform.final_kind(child_id)
2174
versioned_kind = kind
2177
versioned_kind = self._transform._tree.stored_kind(file_id)
2178
if versioned_kind == 'directory':
2179
subdirs.append(child_id)
2180
children.append((path_from_root, basename, kind, None,
2181
file_id, versioned_kind))
2183
if parent_path.startswith(prefix):
2184
yield (parent_path, parent_file_id), children
2185
pending.extend(sorted(subdirs, key=self._final_paths.get_path,
2188
def get_parent_ids(self):
2189
return self._parent_ids
2191
def set_parent_ids(self, parent_ids):
2192
self._parent_ids = parent_ids
2194
def get_revision_tree(self, revision_id):
2195
return self._transform._tree.get_revision_tree(revision_id)
1414
return os.readlink(name)
1416
def paths2ids(self, specific_files, trees=None, require_versioned=False):
1417
"""See Tree.paths2ids"""
2198
1421
def joinpath(parent, child):
2535
1721
tt.create_directory(trans_id)
2538
def create_from_tree(tt, trans_id, tree, file_id, bytes=None,
2539
filter_tree_path=None):
2540
"""Create new file contents according to tree contents.
2542
:param filter_tree_path: the tree path to use to lookup
2543
content filters to apply to the bytes output in the working tree.
2544
This only applies if the working tree supports content filtering.
2546
kind = tree.kind(file_id)
2547
if kind == 'directory':
2548
tt.create_directory(trans_id)
2549
elif kind == "file":
2551
tree_file = tree.get_file(file_id)
2553
bytes = tree_file.readlines()
2557
if wt.supports_content_filtering() and filter_tree_path is not None:
2558
filters = wt._content_filter_stack(filter_tree_path)
2559
bytes = filtered_output_bytes(bytes, filters,
2560
ContentFilterContext(filter_tree_path, tree))
2561
tt.create_file(bytes, trans_id)
2562
elif kind == "symlink":
2563
tt.create_symlink(tree.get_symlink_target(file_id), trans_id)
2565
raise AssertionError('Unknown kind %r' % kind)
2568
1724
def create_entry_executability(tt, entry, trans_id):
2569
1725
"""Set the executability of a trans_id according to an inventory entry"""
2570
1726
if entry.kind == "file":
2571
1727
tt.set_executability(entry.executable, trans_id)
1730
@deprecated_function(zero_fifteen)
1731
def find_interesting(working_tree, target_tree, filenames):
1732
"""Find the ids corresponding to specified filenames.
1734
Deprecated: Please use tree1.paths2ids(filenames, [tree2]).
1736
working_tree.lock_read()
1738
target_tree.lock_read()
1740
return working_tree.paths2ids(filenames, [target_tree])
1742
target_tree.unlock()
1744
working_tree.unlock()
1747
@deprecated_function(zero_ninety)
1748
def change_entry(tt, file_id, working_tree, target_tree,
1749
trans_id_file_id, backups, trans_id, by_parent):
1750
"""Replace a file_id's contents with those from a target tree."""
1751
if file_id is None and target_tree is None:
1752
# skip the logic altogether in the deprecation test
1754
e_trans_id = trans_id_file_id(file_id)
1755
entry = target_tree.inventory[file_id]
1756
has_contents, contents_mod, meta_mod, = _entry_changes(file_id, entry,
1759
mode_id = e_trans_id
1762
tt.delete_contents(e_trans_id)
1764
parent_trans_id = trans_id_file_id(entry.parent_id)
1765
backup_name = get_backup_name(entry, by_parent,
1766
parent_trans_id, tt)
1767
tt.adjust_path(backup_name, parent_trans_id, e_trans_id)
1768
tt.unversion_file(e_trans_id)
1769
e_trans_id = tt.create_path(entry.name, parent_trans_id)
1770
tt.version_file(file_id, e_trans_id)
1771
trans_id[file_id] = e_trans_id
1772
create_by_entry(tt, entry, target_tree, e_trans_id, mode_id=mode_id)
1773
create_entry_executability(tt, entry, e_trans_id)
1776
tt.set_executability(entry.executable, e_trans_id)
1777
if tt.final_name(e_trans_id) != entry.name:
1780
parent_id = tt.final_parent(e_trans_id)
1781
parent_file_id = tt.final_file_id(parent_id)
1782
if parent_file_id != entry.parent_id:
1787
parent_trans_id = trans_id_file_id(entry.parent_id)
1788
tt.adjust_path(entry.name, parent_trans_id, e_trans_id)
2574
1791
def get_backup_name(entry, by_parent, parent_trans_id, tt):
2575
1792
return _get_backup_name(entry.name, by_parent, parent_trans_id, tt)