59
53
class _TransformResults(object):
60
def __init__(self, modified_paths, rename_count):
54
def __init__(self, modified_paths):
61
55
object.__init__(self)
62
56
self.modified_paths = modified_paths
63
self.rename_count = rename_count
66
class TreeTransformBase(object):
67
"""The base class for TreeTransform and TreeTransformBase"""
69
def __init__(self, tree, limbodir, pb=DummyProgress(),
73
:param tree: The tree that will be transformed, but not necessarily
75
:param limbodir: A directory where new files can be stored until
76
they are installed in their proper places
77
:param pb: A ProgressBar indicating how much progress is being made
78
:param case_sensitive: If True, the target of the transform is
79
case sensitive, not just case preserving.
59
class TreeTransform(object):
60
"""Represent a tree transformation.
62
This object is designed to support incremental generation of the transform,
65
It is easy to produce malformed transforms, but they are generally
66
harmless. Attempting to apply a malformed transform will cause an
67
exception to be raised before any modifications are made to the tree.
69
Many kinds of malformed transforms can be corrected with the
70
resolve_conflicts function. The remaining ones indicate programming error,
71
such as trying to create a file with no path.
73
Two sets of file creation methods are supplied. Convenience methods are:
78
These are composed of the low-level methods:
80
* create_file or create_directory or create_symlink
84
def __init__(self, tree, pb=DummyProgress()):
85
"""Note: a tree_write lock is taken on the tree.
87
Use TreeTransform.finalize() to release the lock
81
89
object.__init__(self)
83
self._limbodir = limbodir
84
self._deletiondir = None
91
self._tree.lock_tree_write()
93
control_files = self._tree._control_files
94
self._limbodir = urlutils.local_path_from_url(
95
control_files.controlfilename('limbo'))
97
os.mkdir(self._limbodir)
99
if e.errno == errno.EEXIST:
100
raise ExistingLimbo(self._limbodir)
85
105
self._id_number = 0
86
# mapping of trans_id -> new basename
87
106
self._new_name = {}
88
# mapping of trans_id -> new parent trans_id
89
107
self._new_parent = {}
90
# mapping of trans_id with new contents -> new file_kind
91
108
self._new_contents = {}
92
# A mapping of transform ids to their limbo filename
93
self._limbo_files = {}
94
# A mapping of transform ids to a set of the transform ids of children
95
# that their limbo directory has
96
self._limbo_children = {}
97
# Map transform ids to maps of child filename to child transform id
98
self._limbo_children_names = {}
99
# List of transform ids that need to be renamed from limbo into place
100
self._needs_rename = set()
101
# Set of trans_ids whose contents will be removed
102
109
self._removed_contents = set()
103
# Mapping of trans_id -> new execute-bit value
104
110
self._new_executability = {}
105
# Mapping of trans_id -> new tree-reference value
106
111
self._new_reference_revision = {}
107
# Mapping of trans_id -> new file_id
108
112
self._new_id = {}
109
# Mapping of old file-id -> trans_id
110
113
self._non_present_ids = {}
111
# Mapping of new file_id -> trans_id
112
114
self._r_new_id = {}
113
# Set of file_ids that will be removed
114
115
self._removed_id = set()
115
# Mapping of path in old tree -> trans_id
116
116
self._tree_path_ids = {}
117
# Mapping trans_id -> path in old tree
118
117
self._tree_id_paths = {}
119
119
# Cache of realpath results, to speed up canonical_path
121
121
# Cache of relpath results, to speed up canonical_path
123
# The trans_id that will be used as the tree root
124
122
self._new_root = self.trans_id_tree_file_id(tree.get_root_id())
125
# Indictor of whether the transform has been applied
129
# Whether the target is case sensitive
130
self._case_sensitive_target = case_sensitive
131
# A counter of how many files have been renamed
132
self.rename_count = 0
134
126
def __get_root(self):
135
127
return self._new_root
733
"""Apply all changes to the inventory and filesystem.
735
If filesystem or inventory conflicts are present, MalformedTransform
738
conflicts = self.find_conflicts()
739
if len(conflicts) != 0:
740
raise MalformedTransform(conflicts=conflicts)
741
inv = self._tree.inventory
743
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
745
child_pb.update('Apply phase', 0, 2)
746
self._apply_removals(inv, inventory_delta)
747
child_pb.update('Apply phase', 1, 2)
748
modified_paths = self._apply_insertions(inv, inventory_delta)
751
self._tree.apply_inventory_delta(inventory_delta)
754
return _TransformResults(modified_paths)
814
756
def _limbo_name(self, trans_id):
815
757
"""Generate the limbo name of a file"""
816
limbo_name = self._limbo_files.get(trans_id)
817
if limbo_name is not None:
819
parent = self._new_parent.get(trans_id)
820
# if the parent directory is already in limbo (e.g. when building a
821
# tree), choose a limbo name inside the parent, to reduce further
823
use_direct_path = False
824
if self._new_contents.get(parent) == 'directory':
825
filename = self._new_name.get(trans_id)
826
if filename is not None:
827
if parent not in self._limbo_children:
828
self._limbo_children[parent] = set()
829
self._limbo_children_names[parent] = {}
830
use_direct_path = True
831
# the direct path can only be used if no other file has
832
# already taken this pathname, i.e. if the name is unused, or
833
# if it is already associated with this trans_id.
834
elif self._case_sensitive_target:
835
if (self._limbo_children_names[parent].get(filename)
836
in (trans_id, None)):
837
use_direct_path = True
758
return pathjoin(self._limbodir, trans_id)
760
def _apply_removals(self, inv, inventory_delta):
761
"""Perform tree operations that remove directory/inventory names.
763
That is, delete files that are to be deleted, and put any files that
764
need renaming into limbo. This must be done in strict child-to-parent
767
tree_paths = list(self._tree_path_ids.iteritems())
768
tree_paths.sort(reverse=True)
769
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
771
for num, data in enumerate(tree_paths):
772
path, trans_id = data
773
child_pb.update('removing file', num, len(tree_paths))
774
full_path = self._tree.abspath(path)
775
if trans_id in self._removed_contents:
776
delete_any(full_path)
777
elif trans_id in self._new_name or trans_id in \
780
os.rename(full_path, self._limbo_name(trans_id))
782
if e.errno != errno.ENOENT:
784
if trans_id in self._removed_id:
785
if trans_id == self._new_root:
786
file_id = self._tree.inventory.root.file_id
788
file_id = self.tree_file_id(trans_id)
789
assert file_id is not None
790
inventory_delta.append((path, None, file_id, None))
794
def _apply_insertions(self, inv, inventory_delta):
795
"""Perform tree operations that insert directory/inventory names.
797
That is, create any files that need to be created, and restore from
798
limbo any files that needed renaming. This must be done in strict
799
parent-to-child order.
801
new_paths = self.new_paths()
803
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
805
for num, (path, trans_id) in enumerate(new_paths):
807
child_pb.update('adding file', num, len(new_paths))
809
kind = self._new_contents[trans_id]
811
kind = contents = None
812
if trans_id in self._new_contents or \
813
self.path_changed(trans_id):
814
full_path = self._tree.abspath(path)
816
os.rename(self._limbo_name(trans_id), full_path)
818
# We may be renaming a dangling inventory id
819
if e.errno != errno.ENOENT:
821
if trans_id in self._new_contents:
822
modified_paths.append(full_path)
823
del self._new_contents[trans_id]
825
if trans_id in self._new_id:
827
kind = file_kind(self._tree.abspath(path))
828
if trans_id in self._new_reference_revision:
829
new_entry = inventory.TreeReference(
830
self._new_id[trans_id],
831
self._new_name[trans_id],
832
self.final_file_id(self._new_parent[trans_id]),
833
None, self._new_reference_revision[trans_id])
835
new_entry = inventory.make_entry(kind,
836
self.final_name(trans_id),
837
self.final_file_id(self.final_parent(trans_id)),
838
self._new_id[trans_id])
839
for l_filename, l_trans_id in\
840
self._limbo_children_names[parent].iteritems():
841
if l_trans_id == trans_id:
843
if l_filename.lower() == filename.lower():
840
if trans_id in self._new_name or trans_id in\
842
trans_id in self._new_executability:
843
file_id = self.final_file_id(trans_id)
844
if file_id is not None:
846
new_entry = entry.copy()
848
if trans_id in self._new_name or trans_id in\
850
if new_entry is not None:
851
new_entry.name = self.final_name(trans_id)
852
parent = self.final_parent(trans_id)
853
parent_id = self.final_file_id(parent)
854
new_entry.parent_id = parent_id
856
if trans_id in self._new_executability:
857
self._set_executability(path, new_entry, trans_id)
858
if new_entry is not None:
859
if new_entry.file_id in inv:
860
old_path = inv.id2path(new_entry.file_id)
846
use_direct_path = True
849
limbo_name = pathjoin(self._limbo_files[parent], filename)
850
self._limbo_children[parent].add(trans_id)
851
self._limbo_children_names[parent][filename] = trans_id
853
limbo_name = pathjoin(self._limbodir, trans_id)
854
self._needs_rename.add(trans_id)
855
self._limbo_files[trans_id] = limbo_name
863
inventory_delta.append((old_path, path,
868
return modified_paths
858
870
def _set_executability(self, path, entry, trans_id):
859
871
"""Set the executability of versioned files """
1064
1076
(from_executable, to_executable)))
1065
1077
return iter(sorted(results, key=lambda x:x[1]))
1067
def get_preview_tree(self):
1068
"""Return a tree representing the result of the transform.
1070
This tree only supports the subset of Tree functionality required
1071
by show_diff_trees. It must only be compared to tt._tree.
1073
return _PreviewTree(self)
1076
class TreeTransform(TreeTransformBase):
1077
"""Represent a tree transformation.
1079
This object is designed to support incremental generation of the transform,
1082
However, it gives optimum performance when parent directories are created
1083
before their contents. The transform is then able to put child files
1084
directly in their parent directory, avoiding later renames.
1086
It is easy to produce malformed transforms, but they are generally
1087
harmless. Attempting to apply a malformed transform will cause an
1088
exception to be raised before any modifications are made to the tree.
1090
Many kinds of malformed transforms can be corrected with the
1091
resolve_conflicts function. The remaining ones indicate programming error,
1092
such as trying to create a file with no path.
1094
Two sets of file creation methods are supplied. Convenience methods are:
1099
These are composed of the low-level methods:
1101
* create_file or create_directory or create_symlink
1105
Transform/Transaction ids
1106
-------------------------
1107
trans_ids are temporary ids assigned to all files involved in a transform.
1108
It's possible, even common, that not all files in the Tree have trans_ids.
1110
trans_ids are used because filenames and file_ids are not good enough
1111
identifiers; filenames change, and not all files have file_ids. File-ids
1112
are also associated with trans-ids, so that moving a file moves its
1115
trans_ids are only valid for the TreeTransform that generated them.
1119
Limbo is a temporary directory use to hold new versions of files.
1120
Files are added to limbo by create_file, create_directory, create_symlink,
1121
and their convenience variants (new_*). Files may be removed from limbo
1122
using cancel_creation. Files are renamed from limbo into their final
1123
location as part of TreeTransform.apply
1125
Limbo must be cleaned up, by either calling TreeTransform.apply or
1126
calling TreeTransform.finalize.
1128
Files are placed into limbo inside their parent directories, where
1129
possible. This reduces subsequent renames, and makes operations involving
1130
lots of files faster. This optimization is only possible if the parent
1131
directory is created *before* creating any of its children, so avoid
1132
creating children before parents, where possible.
1136
This temporary directory is used by _FileMover for storing files that are
1137
about to be deleted. In case of rollback, the files will be restored.
1138
FileMover does not delete files until it is sure that a rollback will not
1141
def __init__(self, tree, pb=DummyProgress()):
1142
"""Note: a tree_write lock is taken on the tree.
1144
Use TreeTransform.finalize() to release the lock (can be omitted if
1145
TreeTransform.apply() called).
1147
tree.lock_tree_write()
1150
control_files = tree._control_files
1151
limbodir = urlutils.local_path_from_url(
1152
control_files.controlfilename('limbo'))
1156
if e.errno == errno.EEXIST:
1157
raise ExistingLimbo(limbodir)
1158
deletiondir = urlutils.local_path_from_url(
1159
control_files.controlfilename('pending-deletion'))
1161
os.mkdir(deletiondir)
1163
if e.errno == errno.EEXIST:
1164
raise errors.ExistingPendingDeletion(deletiondir)
1169
TreeTransformBase.__init__(self, tree, limbodir, pb,
1170
tree.case_sensitive)
1171
self._deletiondir = deletiondir
1173
def apply(self, no_conflicts=False, _mover=None):
1174
"""Apply all changes to the inventory and filesystem.
1176
If filesystem or inventory conflicts are present, MalformedTransform
1179
If apply succeeds, finalize is not necessary.
1181
:param no_conflicts: if True, the caller guarantees there are no
1182
conflicts, so no check is made.
1183
:param _mover: Supply an alternate FileMover, for testing
1185
if not no_conflicts:
1186
conflicts = self.find_conflicts()
1187
if len(conflicts) != 0:
1188
raise MalformedTransform(conflicts=conflicts)
1189
inventory_delta = []
1190
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1193
mover = _FileMover()
1197
child_pb.update('Apply phase', 0, 2)
1198
self._apply_removals(inventory_delta, mover)
1199
child_pb.update('Apply phase', 1, 2)
1200
modified_paths = self._apply_insertions(inventory_delta, mover)
1205
mover.apply_deletions()
1208
self._tree.apply_inventory_delta(inventory_delta)
1211
return _TransformResults(modified_paths, self.rename_count)
1213
def _apply_removals(self, inventory_delta, mover):
1214
"""Perform tree operations that remove directory/inventory names.
1216
That is, delete files that are to be deleted, and put any files that
1217
need renaming into limbo. This must be done in strict child-to-parent
1220
tree_paths = list(self._tree_path_ids.iteritems())
1221
tree_paths.sort(reverse=True)
1222
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1224
for num, data in enumerate(tree_paths):
1225
path, trans_id = data
1226
child_pb.update('removing file', num, len(tree_paths))
1227
full_path = self._tree.abspath(path)
1228
if trans_id in self._removed_contents:
1229
mover.pre_delete(full_path, os.path.join(self._deletiondir,
1231
elif trans_id in self._new_name or trans_id in \
1234
mover.rename(full_path, self._limbo_name(trans_id))
1236
if e.errno != errno.ENOENT:
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))
1253
def _apply_insertions(self, inventory_delta, mover):
1254
"""Perform tree operations that insert directory/inventory names.
1256
That is, create any files that need to be created, and restore from
1257
limbo any files that needed renaming. This must be done in strict
1258
parent-to-child order.
1260
new_paths = self.new_paths()
1262
child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1265
for num, (path, trans_id) in enumerate(new_paths):
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
1280
if trans_id in self._new_contents:
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,
1309
if trans_id in self._new_executability:
1310
self._set_executability(path, new_entry, trans_id)
1313
for trans_id in completed_new:
1314
del self._new_contents[trans_id]
1315
return modified_paths
1318
class TransformPreview(TreeTransformBase):
1319
"""A TreeTransform for generating preview trees.
1321
Unlike TreeTransform, this version works when the input tree is a
1322
RevisionTree, rather than a WorkingTree. As a result, it tends to ignore
1323
unversioned files in the input tree.
1326
def __init__(self, tree, pb=DummyProgress(), case_sensitive=True):
1328
limbodir = tempfile.mkdtemp(prefix='bzr-limbo-')
1329
TreeTransformBase.__init__(self, tree, limbodir, pb, case_sensitive)
1331
def canonical_path(self, path):
1334
def tree_kind(self, trans_id):
1335
path = self._tree_id_paths.get(trans_id)
1337
raise NoSuchFile(None)
1338
file_id = self._tree.path2id(path)
1339
return self._tree.kind(file_id)
1341
def _set_mode(self, trans_id, mode_id, typefunc):
1342
"""Set the mode of new file contents.
1343
The mode_id is the existing file to get the mode from (often the same
1344
as trans_id). The operation is only performed if there's a mode match
1345
according to typefunc.
1347
# is it ok to ignore this? probably
1350
def iter_tree_children(self, parent_id):
1351
"""Iterate through the entry's tree children, if any"""
1353
path = self._tree_id_paths[parent_id]
1356
file_id = self.tree_file_id(parent_id)
1357
for child in self._tree.inventory[file_id].children.iterkeys():
1358
childpath = joinpath(path, child)
1359
yield self.trans_id_tree_path(childpath)
1362
class _PreviewTree(object):
1363
"""Partial implementation of Tree to support show_diff_trees"""
1365
def __init__(self, transform):
1366
self._transform = transform
1368
def lock_read(self):
1369
# Perhaps in theory, this should lock the TreeTransform?
1375
def iter_changes(self, from_tree, include_unchanged=False,
1376
specific_files=None, pb=None, extra_trees=None,
1377
require_versioned=True, want_unversioned=False):
1378
"""See InterTree.iter_changes.
1380
This implementation does not support include_unchanged, specific_files,
1381
or want_unversioned. extra_trees, require_versioned, and pb are
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')
1390
if want_unversioned:
1391
raise ValueError('want_unversioned is not supported')
1392
return self._transform.iter_changes()
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):
1405
"""See Tree.get_file"""
1406
trans_id = self._transform.trans_id_file_id(file_id)
1407
name = self._transform._limbo_name(trans_id)
1408
return open(name, 'rb')
1410
def get_symlink_target(self, file_id):
1411
"""See Tree.get_symlink_target"""
1412
trans_id = self._transform.trans_id_file_id(file_id)
1413
name = self._transform._limbo_name(trans_id)
1414
return os.readlink(name)
1416
def paths2ids(self, specific_files, trees=None, require_versioned=False):
1417
"""See Tree.paths2ids"""
1421
1080
def joinpath(parent, child):
1422
1081
"""Join tree-relative paths, handling the tree root specially"""
1474
1132
- Otherwise, if the content on disk matches the content we are building,
1475
1133
it is silently replaced.
1476
1134
- Otherwise, conflict resolution will move the old file to 'oldname.moved'.
1478
:param tree: The tree to convert wt into a copy of
1479
:param wt: The working tree that files will be placed into
1480
:param accelerator_tree: A tree which can be used for retrieving file
1481
contents more quickly than tree itself, i.e. a workingtree. tree
1482
will be used for cases where accelerator_tree's content is different.
1483
:param hardlink: If true, hard-link files to accelerator_tree, where
1484
possible. accelerator_tree must implement abspath, i.e. be a
1487
1136
wt.lock_tree_write()
1489
1138
tree.lock_read()
1491
if accelerator_tree is not None:
1492
accelerator_tree.lock_read()
1494
return _build_tree(tree, wt, accelerator_tree, hardlink)
1496
if accelerator_tree is not None:
1497
accelerator_tree.unlock()
1140
return _build_tree(tree, wt)
1504
def _build_tree(tree, wt, accelerator_tree, hardlink):
1146
def _build_tree(tree, wt):
1505
1147
"""See build_tree."""
1506
for num, _unused in enumerate(wt.all_file_ids()):
1507
if num > 0: # more than just a root
1508
raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
1148
if len(wt.inventory) > 1: # more than just a root
1149
raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
1509
1150
file_trans_id = {}
1510
1151
top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1511
1152
pp = ProgressPhase("Build phase", 2, top_pb)
1512
1153
if tree.inventory.root is not None:
1513
# This is kind of a hack: we should be altering the root
1514
# as part of the regular tree shape diff logic.
1515
# The conditional test here is to avoid doing an
1154
# this is kindof a hack: we should be altering the root
1155
# as partof the regular tree shape diff logic.
1156
# the conditional test hereis to avoid doing an
1516
1157
# expensive operation (flush) every time the root id
1517
1158
# is set within the tree, nor setting the root and thus
1518
1159
# marking the tree as dirty, because we use two different
1519
1160
# idioms here: tree interfaces and inventory interfaces.
1520
if wt.get_root_id() != tree.get_root_id():
1521
wt.set_root_id(tree.get_root_id())
1161
if wt.path2id('') != tree.inventory.root.file_id:
1162
wt.set_root_id(tree.inventory.root.file_id)
1523
1164
tt = TreeTransform(wt)