920
1201
(from_executable, to_executable)))
921
1202
return iter(sorted(results, key=lambda x:x[1]))
923
def get_preview_tree(self):
924
"""Return a tree representing the result of the transform.
926
The tree is a snapshot, and altering the TreeTransform will invalidate
929
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
os.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):
1301
"""Represent a tree transformation.
1303
This object is designed to support incremental generation of the transform,
1306
However, it gives optimum performance when parent directories are created
1307
before their contents. The transform is then able to put child files
1308
directly in their parent directory, avoiding later renames.
1310
It is easy to produce malformed transforms, but they are generally
1311
harmless. Attempting to apply a malformed transform will cause an
1312
exception to be raised before any modifications are made to the tree.
1314
Many kinds of malformed transforms can be corrected with the
1315
resolve_conflicts function. The remaining ones indicate programming error,
1316
such as trying to create a file with no path.
1318
Two sets of file creation methods are supplied. Convenience methods are:
1323
These are composed of the low-level methods:
1325
* create_file or create_directory or create_symlink
1329
Transform/Transaction ids
1330
-------------------------
1331
trans_ids are temporary ids assigned to all files involved in a transform.
1332
It's possible, even common, that not all files in the Tree have trans_ids.
1334
trans_ids are used because filenames and file_ids are not good enough
1335
identifiers; filenames change, and not all files have file_ids. File-ids
1336
are also associated with trans-ids, so that moving a file moves its
1339
trans_ids are only valid for the TreeTransform that generated them.
1343
Limbo is a temporary directory use to hold new versions of files.
1344
Files are added to limbo by create_file, create_directory, create_symlink,
1345
and their convenience variants (new_*). Files may be removed from limbo
1346
using cancel_creation. Files are renamed from limbo into their final
1347
location as part of TreeTransform.apply
1349
Limbo must be cleaned up, by either calling TreeTransform.apply or
1350
calling TreeTransform.finalize.
1352
Files are placed into limbo inside their parent directories, where
1353
possible. This reduces subsequent renames, and makes operations involving
1354
lots of files faster. This optimization is only possible if the parent
1355
directory is created *before* creating any of its children, so avoid
1356
creating children before parents, where possible.
1360
This temporary directory is used by _FileMover for storing files that are
1361
about to be deleted. In case of rollback, the files will be restored.
1362
FileMover does not delete files until it is sure that a rollback will not
1365
def __init__(self, tree, pb=None):
1366
"""Note: a tree_write lock is taken on the tree.
1368
Use TreeTransform.finalize() to release the lock (can be omitted if
1369
TreeTransform.apply() called).
1371
tree.lock_tree_write()
1374
limbodir = urlutils.local_path_from_url(
1375
tree._transport.abspath('limbo'))
1379
if e.errno == errno.EEXIST:
1380
raise ExistingLimbo(limbodir)
1381
deletiondir = urlutils.local_path_from_url(
1382
tree._transport.abspath('pending-deletion'))
1384
os.mkdir(deletiondir)
1386
if e.errno == errno.EEXIST:
1387
raise errors.ExistingPendingDeletion(deletiondir)
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,
1397
tree.case_sensitive)
1398
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):
1530
"""Apply all changes to the inventory and filesystem.
1532
If filesystem or inventory conflicts are present, MalformedTransform
1535
If apply succeeds, finalize is not necessary.
1537
:param no_conflicts: if True, the caller guarantees there are no
1538
conflicts, so no check is made.
1539
:param precomputed_delta: An inventory delta to use instead of
1541
:param _mover: Supply an alternate FileMover, for testing
1543
if not no_conflicts:
1544
self._check_malformed()
1545
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1547
if precomputed_delta is None:
1548
child_pb.update('Apply phase', 0, 2)
1549
inventory_delta = self._generate_inventory_delta()
1552
inventory_delta = precomputed_delta
1555
mover = _FileMover()
1559
child_pb.update('Apply phase', 0 + offset, 2 + offset)
1560
self._apply_removals(mover)
1561
child_pb.update('Apply phase', 1 + offset, 2 + offset)
1562
modified_paths = self._apply_insertions(mover)
1567
mover.apply_deletions()
1570
self._tree.apply_inventory_delta(inventory_delta)
1573
return _TransformResults(modified_paths, self.rename_count)
1575
def _generate_inventory_delta(self):
1576
"""Generate an inventory delta for the current transform."""
1577
inventory_delta = []
1578
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1579
new_paths = self._inventory_altered()
1580
total_entries = len(new_paths) + len(self._removed_id)
1582
for num, trans_id in enumerate(self._removed_id):
1584
child_pb.update('removing file', num, total_entries)
1585
if trans_id == self._new_root:
1586
file_id = self._tree.get_root_id()
1588
file_id = self.tree_file_id(trans_id)
1589
# File-id isn't really being deleted, just moved
1590
if file_id in self._r_new_id:
1592
path = self._tree_id_paths[trans_id]
1593
inventory_delta.append((path, None, file_id, None))
1594
new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1596
entries = self._tree.iter_entries_by_dir(
1597
new_path_file_ids.values())
1598
old_paths = dict((e.file_id, p) for p, e in entries)
1600
for num, (path, trans_id) in enumerate(new_paths):
1602
child_pb.update('adding file',
1603
num + len(self._removed_id), total_entries)
1604
file_id = new_path_file_ids[trans_id]
1609
kind = self.final_kind(trans_id)
1611
kind = self._tree.stored_kind(file_id)
1612
parent_trans_id = self.final_parent(trans_id)
1613
parent_file_id = new_path_file_ids.get(parent_trans_id)
1614
if parent_file_id is None:
1615
parent_file_id = self.final_file_id(parent_trans_id)
1616
if trans_id in self._new_reference_revision:
1617
new_entry = inventory.TreeReference(
1619
self._new_name[trans_id],
1620
self.final_file_id(self._new_parent[trans_id]),
1621
None, self._new_reference_revision[trans_id])
1623
new_entry = inventory.make_entry(kind,
1624
self.final_name(trans_id),
1625
parent_file_id, file_id)
1626
old_path = old_paths.get(new_entry.file_id)
1627
new_executability = self._new_executability.get(trans_id)
1628
if new_executability is not None:
1629
new_entry.executable = new_executability
1630
inventory_delta.append(
1631
(old_path, path, new_entry.file_id, new_entry))
1634
return inventory_delta
1636
def _apply_removals(self, mover):
1637
"""Perform tree operations that remove directory/inventory names.
1639
That is, delete files that are to be deleted, and put any files that
1640
need renaming into limbo. This must be done in strict child-to-parent
1643
If inventory_delta is None, no inventory delta generation is performed.
1645
tree_paths = list(self._tree_path_ids.iteritems())
1646
tree_paths.sort(reverse=True)
1647
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1649
for num, data in enumerate(tree_paths):
1650
path, trans_id = data
1651
child_pb.update('removing file', num, len(tree_paths))
1652
full_path = self._tree.abspath(path)
1653
if trans_id in self._removed_contents:
1654
delete_path = os.path.join(self._deletiondir, trans_id)
1655
mover.pre_delete(full_path, delete_path)
1656
elif (trans_id in self._new_name
1657
or trans_id in self._new_parent):
1659
mover.rename(full_path, self._limbo_name(trans_id))
1660
except errors.TransformRenameFailed, e:
1661
if e.errno != errno.ENOENT:
1664
self.rename_count += 1
1668
def _apply_insertions(self, mover):
1669
"""Perform tree operations that insert directory/inventory names.
1671
That is, create any files that need to be created, and restore from
1672
limbo any files that needed renaming. This must be done in strict
1673
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)
1680
new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1682
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1684
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)
1691
except errors.TransformRenameFailed, e:
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)):
1699
if trans_id in self._new_contents:
1700
modified_paths.append(full_path)
1701
if trans_id in self._new_executability:
1702
self._set_executability(path, trans_id)
1705
self._new_contents.clear()
1706
return modified_paths
1709
class TransformPreview(DiskTreeTransform):
1710
"""A TreeTransform for generating preview trees.
1712
Unlike TreeTransform, this version works when the input tree is a
1713
RevisionTree, rather than a WorkingTree. As a result, it tends to ignore
1714
unversioned files in the input tree.
1717
def __init__(self, tree, pb=None, case_sensitive=True):
1719
limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
1720
DiskTreeTransform.__init__(self, tree, limbodir, pb, case_sensitive)
1722
def canonical_path(self, path):
1725
def tree_kind(self, trans_id):
1726
path = self._tree_id_paths.get(trans_id)
1728
raise NoSuchFile(None)
1729
file_id = self._tree.path2id(path)
1730
return self._tree.kind(file_id)
1732
def _set_mode(self, trans_id, mode_id, typefunc):
1733
"""Set the mode of new file contents.
1734
The mode_id is the existing file to get the mode from (often the same
1735
as trans_id). The operation is only performed if there's a mode match
1736
according to typefunc.
1738
# is it ok to ignore this? probably
1741
def iter_tree_children(self, parent_id):
1742
"""Iterate through the entry's tree children, if any"""
1744
path = self._tree_id_paths[parent_id]
1747
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:
1753
childpath = joinpath(path, child)
1754
yield self.trans_id_tree_path(childpath)
1757
class _PreviewTree(tree.Tree):
1758
"""Partial implementation of Tree to support show_diff_trees"""
1760
def __init__(self, transform):
1761
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_lines(file_id))
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
def lock_read(self):
1827
# Perhaps in theory, this should lock the TreeTransform?
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
def iter_changes(self, from_tree, include_unchanged=False,
2089
specific_files=None, pb=None, extra_trees=None,
2090
require_versioned=True, want_unversioned=False):
2091
"""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.
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)
2105
if want_unversioned:
2106
raise ValueError('want_unversioned is not supported')
2107
return self._transform.iter_changes()
2109
def get_file(self, file_id, path=None):
2110
"""See Tree.get_file"""
2111
if not self._content_change(file_id):
2112
return self._transform._tree.get_file(file_id, path)
2113
trans_id = self._transform.trans_id_file_id(file_id)
2114
name = self._transform._limbo_name(trans_id)
2115
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
def get_symlink_target(self, file_id):
2152
"""See Tree.get_symlink_target"""
2153
if not self._content_change(file_id):
2154
return self._transform._tree.get_symlink_target(file_id)
2155
trans_id = self._transform.trans_id_file_id(file_id)
2156
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)
2198
1205
def joinpath(parent, child):
2199
1206
"""Join tree-relative paths, handling the tree root specially"""