395
524
def find_conflicts(self):
396
525
"""Find any violations of inventory or filesystem invariants"""
397
raise NotImplementedError(self.find_conflicts)
526
if self._done is True:
527
raise ReusingTransform()
529
# ensure all children of all existent parents are known
530
# all children of non-existent parents are known, by definition.
531
self._add_tree_children()
532
by_parent = self.by_parent()
533
conflicts.extend(self._unversioned_parents(by_parent))
534
conflicts.extend(self._parent_loops())
535
conflicts.extend(self._duplicate_entries(by_parent))
536
conflicts.extend(self._duplicate_ids())
537
conflicts.extend(self._parent_type_conflicts(by_parent))
538
conflicts.extend(self._improper_versioning())
539
conflicts.extend(self._executability_conflicts())
540
conflicts.extend(self._overwrite_conflicts())
543
def _check_malformed(self):
544
conflicts = self.find_conflicts()
545
if len(conflicts) != 0:
546
raise MalformedTransform(conflicts=conflicts)
548
def _add_tree_children(self):
549
"""Add all the children of all active parents to the known paths.
551
Active parents are those which gain children, and those which are
552
removed. This is a necessary first step in detecting conflicts.
554
parents = list(self.by_parent())
555
parents.extend([t for t in self._removed_contents if
556
self.tree_kind(t) == 'directory'])
557
for trans_id in self._removed_id:
558
path = self.tree_path(trans_id)
560
if self._tree.stored_kind(path) == 'directory':
561
parents.append(trans_id)
562
elif self.tree_kind(trans_id) == 'directory':
563
parents.append(trans_id)
565
for parent_id in parents:
566
# ensure that all children are registered with the transaction
567
list(self.iter_tree_children(parent_id))
569
def _has_named_child(self, name, parent_id, known_children):
570
"""Does a parent already have a name child.
572
:param name: The searched for name.
574
:param parent_id: The parent for which the check is made.
576
:param known_children: The already known children. This should have
577
been recently obtained from `self.by_parent.get(parent_id)`
578
(or will be if None is passed).
580
if known_children is None:
581
known_children = self.by_parent().get(parent_id, [])
582
for child in known_children:
583
if self.final_name(child) == name:
585
parent_path = self._tree_id_paths.get(parent_id, None)
586
if parent_path is None:
587
# No parent... no children
589
child_path = joinpath(parent_path, name)
590
child_id = self._tree_path_ids.get(child_path, None)
592
# Not known by the tree transform yet, check the filesystem
593
return osutils.lexists(self._tree.abspath(child_path))
595
raise AssertionError('child_id is missing: %s, %s, %s'
596
% (name, parent_id, child_id))
598
def _available_backup_name(self, name, target_id):
599
"""Find an available backup name.
601
:param name: The basename of the file.
603
:param target_id: The directory trans_id where the backup should
606
known_children = self.by_parent().get(target_id, [])
607
return osutils.available_backup_name(
609
lambda base: self._has_named_child(
610
base, target_id, known_children))
612
def _parent_loops(self):
613
"""No entry should be its own ancestor"""
615
for trans_id in self._new_parent:
618
while parent_id != ROOT_PARENT:
621
parent_id = self.final_parent(parent_id)
624
if parent_id == trans_id:
625
conflicts.append(('parent loop', trans_id))
626
if parent_id in seen:
630
def _unversioned_parents(self, by_parent):
631
"""If parent directories are versioned, children must be versioned."""
633
for parent_id, children in by_parent.items():
634
if parent_id == ROOT_PARENT:
636
if self.final_file_id(parent_id) is not None:
638
for child_id in children:
639
if self.final_file_id(child_id) is not None:
640
conflicts.append(('unversioned parent', parent_id))
644
def _improper_versioning(self):
645
"""Cannot version a file with no contents, or a bad type.
647
However, existing entries with no contents are okay.
650
for trans_id in self._new_id:
651
kind = self.final_kind(trans_id)
652
if kind == 'symlink' and not self._tree.supports_symlinks():
653
# Ignore symlinks as they are not supported on this platform
656
conflicts.append(('versioning no contents', trans_id))
658
if not self._tree.versionable_kind(kind):
659
conflicts.append(('versioning bad kind', trans_id, kind))
662
def _executability_conflicts(self):
663
"""Check for bad executability changes.
665
Only versioned files may have their executability set, because
666
1. only versioned entries can have executability under windows
667
2. only files can be executable. (The execute bit on a directory
668
does not indicate searchability)
671
for trans_id in self._new_executability:
672
if self.final_file_id(trans_id) is None:
673
conflicts.append(('unversioned executability', trans_id))
675
if self.final_kind(trans_id) != "file":
676
conflicts.append(('non-file executability', trans_id))
679
def _overwrite_conflicts(self):
680
"""Check for overwrites (not permitted on Win32)"""
682
for trans_id in self._new_contents:
683
if self.tree_kind(trans_id) is None:
685
if trans_id not in self._removed_contents:
686
conflicts.append(('overwrite', trans_id,
687
self.final_name(trans_id)))
690
def _duplicate_entries(self, by_parent):
691
"""No directory may have two entries with the same name."""
693
if (self._new_name, self._new_parent) == ({}, {}):
695
for children in by_parent.values():
697
for child_tid in children:
698
name = self.final_name(child_tid)
700
# Keep children only if they still exist in the end
701
if not self._case_sensitive_target:
703
name_ids.append((name, child_tid))
707
for name, trans_id in name_ids:
708
kind = self.final_kind(trans_id)
709
file_id = self.final_file_id(trans_id)
710
if kind is None and file_id is None:
712
if name == last_name:
713
conflicts.append(('duplicate', last_trans_id, trans_id,
716
last_trans_id = trans_id
719
def _duplicate_ids(self):
720
"""Each inventory id may only be used once"""
723
all_ids = self._tree.all_file_ids()
724
except errors.UnsupportedOperation:
725
# it's okay for non-file-id trees to raise UnsupportedOperation.
727
removed_tree_ids = set((self.tree_file_id(trans_id) for trans_id in
729
active_tree_ids = all_ids.difference(removed_tree_ids)
730
for trans_id, file_id in self._new_id.items():
731
if file_id in active_tree_ids:
732
path = self._tree.id2path(file_id)
733
old_trans_id = self.trans_id_tree_path(path)
734
conflicts.append(('duplicate id', old_trans_id, trans_id))
737
def _parent_type_conflicts(self, by_parent):
738
"""Children must have a directory parent"""
740
for parent_id, children in by_parent.items():
741
if parent_id == ROOT_PARENT:
744
for child_id in children:
745
if self.final_kind(child_id) is not None:
750
# There is at least a child, so we need an existing directory to
752
kind = self.final_kind(parent_id)
754
# The directory will be deleted
755
conflicts.append(('missing parent', parent_id))
756
elif kind != "directory":
757
# Meh, we need a *directory* to put something in it
758
conflicts.append(('non-directory parent', parent_id))
761
def _set_executability(self, path, trans_id):
762
"""Set the executability of versioned files """
763
if self._tree._supports_executable():
764
new_executability = self._new_executability[trans_id]
765
abspath = self._tree.abspath(path)
766
current_mode = os.stat(abspath).st_mode
767
if new_executability:
770
to_mode = current_mode | (0o100 & ~umask)
771
# Enable x-bit for others only if they can read it.
772
if current_mode & 0o004:
773
to_mode |= 0o001 & ~umask
774
if current_mode & 0o040:
775
to_mode |= 0o010 & ~umask
777
to_mode = current_mode & ~0o111
778
osutils.chmod_if_possible(abspath, to_mode)
780
def _new_entry(self, name, parent_id, file_id):
781
"""Helper function to create a new filesystem entry."""
782
trans_id = self.create_path(name, parent_id)
783
if file_id is not None:
784
self.version_file(file_id, trans_id)
399
787
def new_file(self, name, parent_id, contents, file_id=None,
400
788
executable=None, sha1=None):
525
1237
raise NotImplementedError(self.cancel_creation)
1240
class DiskTreeTransform(TreeTransformBase):
1241
"""Tree transform storing its contents on disk."""
1243
def __init__(self, tree, limbodir, pb=None, case_sensitive=True):
1245
:param tree: The tree that will be transformed, but not necessarily
1247
:param limbodir: A directory where new files can be stored until
1248
they are installed in their proper places
1250
:param case_sensitive: If True, the target of the transform is
1251
case sensitive, not just case preserving.
1253
TreeTransformBase.__init__(self, tree, pb, case_sensitive)
1254
self._limbodir = limbodir
1255
self._deletiondir = None
1256
# A mapping of transform ids to their limbo filename
1257
self._limbo_files = {}
1258
self._possibly_stale_limbo_files = set()
1259
# A mapping of transform ids to a set of the transform ids of children
1260
# that their limbo directory has
1261
self._limbo_children = {}
1262
# Map transform ids to maps of child filename to child transform id
1263
self._limbo_children_names = {}
1264
# List of transform ids that need to be renamed from limbo into place
1265
self._needs_rename = set()
1266
self._creation_mtime = None
1267
self._create_symlinks = osutils.supports_symlinks(self._limbodir)
1270
"""Release the working tree lock, if held, clean up limbo dir.
1272
This is required if apply has not been invoked, but can be invoked
1275
if self._tree is None:
1278
limbo_paths = list(self._limbo_files.values())
1279
limbo_paths.extend(self._possibly_stale_limbo_files)
1280
limbo_paths.sort(reverse=True)
1281
for path in limbo_paths:
1284
except OSError as e:
1285
if e.errno != errno.ENOENT:
1287
# XXX: warn? perhaps we just got interrupted at an
1288
# inconvenient moment, but perhaps files are disappearing
1291
delete_any(self._limbodir)
1293
# We don't especially care *why* the dir is immortal.
1294
raise ImmortalLimbo(self._limbodir)
1296
if self._deletiondir is not None:
1297
delete_any(self._deletiondir)
1299
raise errors.ImmortalPendingDeletion(self._deletiondir)
1301
TreeTransformBase.finalize(self)
1303
def _limbo_supports_executable(self):
1304
"""Check if the limbo path supports the executable bit."""
1305
return osutils.supports_executable(self._limbodir)
1307
def _limbo_name(self, trans_id):
1308
"""Generate the limbo name of a file"""
1309
limbo_name = self._limbo_files.get(trans_id)
1310
if limbo_name is None:
1311
limbo_name = self._generate_limbo_path(trans_id)
1312
self._limbo_files[trans_id] = limbo_name
1315
def _generate_limbo_path(self, trans_id):
1316
"""Generate a limbo path using the trans_id as the relative path.
1318
This is suitable as a fallback, and when the transform should not be
1319
sensitive to the path encoding of the limbo directory.
1321
self._needs_rename.add(trans_id)
1322
return pathjoin(self._limbodir, trans_id)
1324
def adjust_path(self, name, parent, trans_id):
1325
previous_parent = self._new_parent.get(trans_id)
1326
previous_name = self._new_name.get(trans_id)
1327
TreeTransformBase.adjust_path(self, name, parent, trans_id)
1328
if (trans_id in self._limbo_files
1329
and trans_id not in self._needs_rename):
1330
self._rename_in_limbo([trans_id])
1331
if previous_parent != parent:
1332
self._limbo_children[previous_parent].remove(trans_id)
1333
if previous_parent != parent or previous_name != name:
1334
del self._limbo_children_names[previous_parent][previous_name]
1336
def _rename_in_limbo(self, trans_ids):
1337
"""Fix limbo names so that the right final path is produced.
1339
This means we outsmarted ourselves-- we tried to avoid renaming
1340
these files later by creating them with their final names in their
1341
final parents. But now the previous name or parent is no longer
1342
suitable, so we have to rename them.
1344
Even for trans_ids that have no new contents, we must remove their
1345
entries from _limbo_files, because they are now stale.
1347
for trans_id in trans_ids:
1348
old_path = self._limbo_files[trans_id]
1349
self._possibly_stale_limbo_files.add(old_path)
1350
del self._limbo_files[trans_id]
1351
if trans_id not in self._new_contents:
1353
new_path = self._limbo_name(trans_id)
1354
os.rename(old_path, new_path)
1355
self._possibly_stale_limbo_files.remove(old_path)
1356
for descendant in self._limbo_descendants(trans_id):
1357
desc_path = self._limbo_files[descendant]
1358
desc_path = new_path + desc_path[len(old_path):]
1359
self._limbo_files[descendant] = desc_path
1361
def _limbo_descendants(self, trans_id):
1362
"""Return the set of trans_ids whose limbo paths descend from this."""
1363
descendants = set(self._limbo_children.get(trans_id, []))
1364
for descendant in list(descendants):
1365
descendants.update(self._limbo_descendants(descendant))
1368
def create_file(self, contents, trans_id, mode_id=None, sha1=None):
1369
"""Schedule creation of a new file.
1373
:param contents: an iterator of strings, all of which will be written
1374
to the target destination.
1375
:param trans_id: TreeTransform handle
1376
:param mode_id: If not None, force the mode of the target file to match
1377
the mode of the object referenced by mode_id.
1378
Otherwise, we will try to preserve mode bits of an existing file.
1379
:param sha1: If the sha1 of this content is already known, pass it in.
1380
We can use it to prevent future sha1 computations.
1382
name = self._limbo_name(trans_id)
1383
with open(name, 'wb') as f:
1384
unique_add(self._new_contents, trans_id, 'file')
1385
f.writelines(contents)
1386
self._set_mtime(name)
1387
self._set_mode(trans_id, mode_id, S_ISREG)
1388
# It is unfortunate we have to use lstat instead of fstat, but we just
1389
# used utime and chmod on the file, so we need the accurate final
1391
if sha1 is not None:
1392
self._observed_sha1s[trans_id] = (sha1, osutils.lstat(name))
1394
def _read_symlink_target(self, trans_id):
1395
return os.readlink(self._limbo_name(trans_id))
1397
def _set_mtime(self, path):
1398
"""All files that are created get the same mtime.
1400
This time is set by the first object to be created.
1402
if self._creation_mtime is None:
1403
self._creation_mtime = time.time()
1404
os.utime(path, (self._creation_mtime, self._creation_mtime))
1406
def create_hardlink(self, path, trans_id):
1407
"""Schedule creation of a hard link"""
1408
name = self._limbo_name(trans_id)
1411
except OSError as e:
1412
if e.errno != errno.EPERM:
1414
raise errors.HardLinkNotSupported(path)
1416
unique_add(self._new_contents, trans_id, 'file')
1417
except BaseException:
1418
# Clean up the file, it never got registered so
1419
# TreeTransform.finalize() won't clean it up.
1423
def create_directory(self, trans_id):
1424
"""Schedule creation of a new directory.
1426
See also new_directory.
1428
os.mkdir(self._limbo_name(trans_id))
1429
unique_add(self._new_contents, trans_id, 'directory')
1431
def create_symlink(self, target, trans_id):
1432
"""Schedule creation of a new symbolic link.
1434
target is a bytestring.
1435
See also new_symlink.
1437
if self._create_symlinks:
1438
os.symlink(target, self._limbo_name(trans_id))
1441
path = FinalPaths(self).get_path(trans_id)
1445
'Unable to create symlink "%s" on this filesystem.' % (path,))
1446
# We add symlink to _new_contents even if they are unsupported
1447
# and not created. These entries are subsequently used to avoid
1448
# conflicts on platforms that don't support symlink
1449
unique_add(self._new_contents, trans_id, 'symlink')
1451
def cancel_creation(self, trans_id):
1452
"""Cancel the creation of new file contents."""
1453
del self._new_contents[trans_id]
1454
if trans_id in self._observed_sha1s:
1455
del self._observed_sha1s[trans_id]
1456
children = self._limbo_children.get(trans_id)
1457
# if this is a limbo directory with children, move them before removing
1459
if children is not None:
1460
self._rename_in_limbo(children)
1461
del self._limbo_children[trans_id]
1462
del self._limbo_children_names[trans_id]
1463
delete_any(self._limbo_name(trans_id))
1465
def new_orphan(self, trans_id, parent_id):
1466
conf = self._tree.get_config_stack()
1467
handle_orphan = conf.get('transform.orphan_policy')
1468
handle_orphan(self, trans_id, parent_id)
528
1471
class OrphaningError(errors.BzrError):
530
1473
# Only bugs could lead to such exception being seen by the user
596
1539
invalid='warning')
1542
class TreeTransform(DiskTreeTransform):
1543
"""Represent a tree transformation.
1545
This object is designed to support incremental generation of the transform,
1548
However, it gives optimum performance when parent directories are created
1549
before their contents. The transform is then able to put child files
1550
directly in their parent directory, avoiding later renames.
1552
It is easy to produce malformed transforms, but they are generally
1553
harmless. Attempting to apply a malformed transform will cause an
1554
exception to be raised before any modifications are made to the tree.
1556
Many kinds of malformed transforms can be corrected with the
1557
resolve_conflicts function. The remaining ones indicate programming error,
1558
such as trying to create a file with no path.
1560
Two sets of file creation methods are supplied. Convenience methods are:
1565
These are composed of the low-level methods:
1567
* create_file or create_directory or create_symlink
1571
Transform/Transaction ids
1572
-------------------------
1573
trans_ids are temporary ids assigned to all files involved in a transform.
1574
It's possible, even common, that not all files in the Tree have trans_ids.
1576
trans_ids are used because filenames and file_ids are not good enough
1577
identifiers; filenames change, and not all files have file_ids. File-ids
1578
are also associated with trans-ids, so that moving a file moves its
1581
trans_ids are only valid for the TreeTransform that generated them.
1585
Limbo is a temporary directory use to hold new versions of files.
1586
Files are added to limbo by create_file, create_directory, create_symlink,
1587
and their convenience variants (new_*). Files may be removed from limbo
1588
using cancel_creation. Files are renamed from limbo into their final
1589
location as part of TreeTransform.apply
1591
Limbo must be cleaned up, by either calling TreeTransform.apply or
1592
calling TreeTransform.finalize.
1594
Files are placed into limbo inside their parent directories, where
1595
possible. This reduces subsequent renames, and makes operations involving
1596
lots of files faster. This optimization is only possible if the parent
1597
directory is created *before* creating any of its children, so avoid
1598
creating children before parents, where possible.
1602
This temporary directory is used by _FileMover for storing files that are
1603
about to be deleted. In case of rollback, the files will be restored.
1604
FileMover does not delete files until it is sure that a rollback will not
1608
def __init__(self, tree, pb=None):
1609
"""Note: a tree_write lock is taken on the tree.
1611
Use TreeTransform.finalize() to release the lock (can be omitted if
1612
TreeTransform.apply() called).
1614
tree.lock_tree_write()
1616
limbodir = urlutils.local_path_from_url(
1617
tree._transport.abspath('limbo'))
1618
osutils.ensure_empty_directory_exists(
1620
errors.ExistingLimbo)
1621
deletiondir = urlutils.local_path_from_url(
1622
tree._transport.abspath('pending-deletion'))
1623
osutils.ensure_empty_directory_exists(
1625
errors.ExistingPendingDeletion)
1626
except BaseException:
1630
# Cache of realpath results, to speed up canonical_path
1631
self._realpaths = {}
1632
# Cache of relpath results, to speed up canonical_path
1634
DiskTreeTransform.__init__(self, tree, limbodir, pb,
1635
tree.case_sensitive)
1636
self._deletiondir = deletiondir
1638
def canonical_path(self, path):
1639
"""Get the canonical tree-relative path"""
1640
# don't follow final symlinks
1641
abs = self._tree.abspath(path)
1642
if abs in self._relpaths:
1643
return self._relpaths[abs]
1644
dirname, basename = os.path.split(abs)
1645
if dirname not in self._realpaths:
1646
self._realpaths[dirname] = os.path.realpath(dirname)
1647
dirname = self._realpaths[dirname]
1648
abs = pathjoin(dirname, basename)
1649
if dirname in self._relpaths:
1650
relpath = pathjoin(self._relpaths[dirname], basename)
1651
relpath = relpath.rstrip('/\\')
1653
relpath = self._tree.relpath(abs)
1654
self._relpaths[abs] = relpath
1657
def tree_kind(self, trans_id):
1658
"""Determine the file kind in the working tree.
1660
:returns: The file kind or None if the file does not exist
1662
path = self._tree_id_paths.get(trans_id)
1666
return file_kind(self._tree.abspath(path))
1667
except errors.NoSuchFile:
1670
def _set_mode(self, trans_id, mode_id, typefunc):
1671
"""Set the mode of new file contents.
1672
The mode_id is the existing file to get the mode from (often the same
1673
as trans_id). The operation is only performed if there's a mode match
1674
according to typefunc.
1679
old_path = self._tree_id_paths[mode_id]
1683
mode = os.stat(self._tree.abspath(old_path)).st_mode
1684
except OSError as e:
1685
if e.errno in (errno.ENOENT, errno.ENOTDIR):
1686
# Either old_path doesn't exist, or the parent of the
1687
# target is not a directory (but will be one eventually)
1688
# Either way, we know it doesn't exist *right now*
1689
# See also bug #248448
1694
osutils.chmod_if_possible(self._limbo_name(trans_id), mode)
1696
def iter_tree_children(self, parent_id):
1697
"""Iterate through the entry's tree children, if any"""
1699
path = self._tree_id_paths[parent_id]
1703
children = os.listdir(self._tree.abspath(path))
1704
except OSError as e:
1705
if not (osutils._is_error_enotdir(e) or
1706
e.errno in (errno.ENOENT, errno.ESRCH)):
1710
for child in children:
1711
childpath = joinpath(path, child)
1712
if self._tree.is_control_filename(childpath):
1714
yield self.trans_id_tree_path(childpath)
1716
def _generate_limbo_path(self, trans_id):
1717
"""Generate a limbo path using the final path if possible.
1719
This optimizes the performance of applying the tree transform by
1720
avoiding renames. These renames can be avoided only when the parent
1721
directory is already scheduled for creation.
1723
If the final path cannot be used, falls back to using the trans_id as
1726
parent = self._new_parent.get(trans_id)
1727
# if the parent directory is already in limbo (e.g. when building a
1728
# tree), choose a limbo name inside the parent, to reduce further
1730
use_direct_path = False
1731
if self._new_contents.get(parent) == 'directory':
1732
filename = self._new_name.get(trans_id)
1733
if filename is not None:
1734
if parent not in self._limbo_children:
1735
self._limbo_children[parent] = set()
1736
self._limbo_children_names[parent] = {}
1737
use_direct_path = True
1738
# the direct path can only be used if no other file has
1739
# already taken this pathname, i.e. if the name is unused, or
1740
# if it is already associated with this trans_id.
1741
elif self._case_sensitive_target:
1742
if (self._limbo_children_names[parent].get(filename)
1743
in (trans_id, None)):
1744
use_direct_path = True
1746
for l_filename, l_trans_id in (
1747
self._limbo_children_names[parent].items()):
1748
if l_trans_id == trans_id:
1750
if l_filename.lower() == filename.lower():
1753
use_direct_path = True
1755
if not use_direct_path:
1756
return DiskTreeTransform._generate_limbo_path(self, trans_id)
1758
limbo_name = pathjoin(self._limbo_files[parent], filename)
1759
self._limbo_children[parent].add(trans_id)
1760
self._limbo_children_names[parent][filename] = trans_id
1763
def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
1764
"""Apply all changes to the inventory and filesystem.
1766
If filesystem or inventory conflicts are present, MalformedTransform
1769
If apply succeeds, finalize is not necessary.
1771
:param no_conflicts: if True, the caller guarantees there are no
1772
conflicts, so no check is made.
1773
:param precomputed_delta: An inventory delta to use instead of
1775
:param _mover: Supply an alternate FileMover, for testing
1777
for hook in MutableTree.hooks['pre_transform']:
1778
hook(self._tree, self)
1779
if not no_conflicts:
1780
self._check_malformed()
1781
with ui.ui_factory.nested_progress_bar() as child_pb:
1782
if precomputed_delta is None:
1783
child_pb.update(gettext('Apply phase'), 0, 2)
1784
inventory_delta = self._generate_inventory_delta()
1787
inventory_delta = precomputed_delta
1790
mover = _FileMover()
1794
child_pb.update(gettext('Apply phase'), 0 + offset, 2 + offset)
1795
self._apply_removals(mover)
1796
child_pb.update(gettext('Apply phase'), 1 + offset, 2 + offset)
1797
modified_paths = self._apply_insertions(mover)
1798
except BaseException:
1802
mover.apply_deletions()
1803
if self.final_file_id(self.root) is None:
1804
inventory_delta = [e for e in inventory_delta if e[0] != '']
1805
self._tree.apply_inventory_delta(inventory_delta)
1806
self._apply_observed_sha1s()
1809
return _TransformResults(modified_paths, self.rename_count)
1811
def _generate_inventory_delta(self):
1812
"""Generate an inventory delta for the current transform."""
1813
inventory_delta = []
1814
new_paths = self._inventory_altered()
1815
total_entries = len(new_paths) + len(self._removed_id)
1816
with ui.ui_factory.nested_progress_bar() as child_pb:
1817
for num, trans_id in enumerate(self._removed_id):
1819
child_pb.update(gettext('removing file'),
1821
if trans_id == self._new_root:
1822
file_id = self._tree.path2id('')
1824
file_id = self.tree_file_id(trans_id)
1825
# File-id isn't really being deleted, just moved
1826
if file_id in self._r_new_id:
1828
path = self._tree_id_paths[trans_id]
1829
inventory_delta.append((path, None, file_id, None))
1830
new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1832
for num, (path, trans_id) in enumerate(new_paths):
1834
child_pb.update(gettext('adding file'),
1835
num + len(self._removed_id), total_entries)
1836
file_id = new_path_file_ids[trans_id]
1839
kind = self.final_kind(trans_id)
1841
kind = self._tree.stored_kind(self._tree.id2path(file_id))
1842
parent_trans_id = self.final_parent(trans_id)
1843
parent_file_id = new_path_file_ids.get(parent_trans_id)
1844
if parent_file_id is None:
1845
parent_file_id = self.final_file_id(parent_trans_id)
1846
if trans_id in self._new_reference_revision:
1847
new_entry = inventory.TreeReference(
1849
self._new_name[trans_id],
1850
self.final_file_id(self._new_parent[trans_id]),
1851
None, self._new_reference_revision[trans_id])
1853
new_entry = inventory.make_entry(kind,
1854
self.final_name(trans_id),
1855
parent_file_id, file_id)
1857
old_path = self._tree.id2path(new_entry.file_id)
1858
except errors.NoSuchId:
1860
new_executability = self._new_executability.get(trans_id)
1861
if new_executability is not None:
1862
new_entry.executable = new_executability
1863
inventory_delta.append(
1864
(old_path, path, new_entry.file_id, new_entry))
1865
return inventory_delta
1867
def _apply_removals(self, mover):
1868
"""Perform tree operations that remove directory/inventory names.
1870
That is, delete files that are to be deleted, and put any files that
1871
need renaming into limbo. This must be done in strict child-to-parent
1874
If inventory_delta is None, no inventory delta generation is performed.
1876
tree_paths = sorted(self._tree_path_ids.items(), reverse=True)
1877
with ui.ui_factory.nested_progress_bar() as child_pb:
1878
for num, (path, trans_id) in enumerate(tree_paths):
1879
# do not attempt to move root into a subdirectory of itself.
1882
child_pb.update(gettext('removing file'), num, len(tree_paths))
1883
full_path = self._tree.abspath(path)
1884
if trans_id in self._removed_contents:
1885
delete_path = os.path.join(self._deletiondir, trans_id)
1886
mover.pre_delete(full_path, delete_path)
1887
elif (trans_id in self._new_name or
1888
trans_id in self._new_parent):
1890
mover.rename(full_path, self._limbo_name(trans_id))
1891
except errors.TransformRenameFailed as e:
1892
if e.errno != errno.ENOENT:
1895
self.rename_count += 1
1897
def _apply_insertions(self, mover):
1898
"""Perform tree operations that insert directory/inventory names.
1900
That is, create any files that need to be created, and restore from
1901
limbo any files that needed renaming. This must be done in strict
1902
parent-to-child order.
1904
If inventory_delta is None, no inventory delta is calculated, and
1905
no list of modified paths is returned.
1907
new_paths = self.new_paths(filesystem_only=True)
1909
with ui.ui_factory.nested_progress_bar() as child_pb:
1910
for num, (path, trans_id) in enumerate(new_paths):
1912
child_pb.update(gettext('adding file'),
1913
num, len(new_paths))
1914
full_path = self._tree.abspath(path)
1915
if trans_id in self._needs_rename:
1917
mover.rename(self._limbo_name(trans_id), full_path)
1918
except errors.TransformRenameFailed as e:
1919
# We may be renaming a dangling inventory id
1920
if e.errno != errno.ENOENT:
1923
self.rename_count += 1
1924
# TODO: if trans_id in self._observed_sha1s, we should
1925
# re-stat the final target, since ctime will be
1926
# updated by the change.
1927
if (trans_id in self._new_contents
1928
or self.path_changed(trans_id)):
1929
if trans_id in self._new_contents:
1930
modified_paths.append(full_path)
1931
if trans_id in self._new_executability:
1932
self._set_executability(path, trans_id)
1933
if trans_id in self._observed_sha1s:
1934
o_sha1, o_st_val = self._observed_sha1s[trans_id]
1935
st = osutils.lstat(full_path)
1936
self._observed_sha1s[trans_id] = (o_sha1, st)
1937
for path, trans_id in new_paths:
1938
# new_paths includes stuff like workingtree conflicts. Only the
1939
# stuff in new_contents actually comes from limbo.
1940
if trans_id in self._limbo_files:
1941
del self._limbo_files[trans_id]
1942
self._new_contents.clear()
1943
return modified_paths
1945
def _apply_observed_sha1s(self):
1946
"""After we have finished renaming everything, update observed sha1s
1948
This has to be done after self._tree.apply_inventory_delta, otherwise
1949
it doesn't know anything about the files we are updating. Also, we want
1950
to do this as late as possible, so that most entries end up cached.
1952
# TODO: this doesn't update the stat information for directories. So
1953
# the first 'bzr status' will still need to rewrite
1954
# .bzr/checkout/dirstate. However, we at least don't need to
1955
# re-read all of the files.
1956
# TODO: If the operation took a while, we could do a time.sleep(3) here
1957
# to allow the clock to tick over and ensure we won't have any
1958
# problems. (we could observe start time, and finish time, and if
1959
# it is less than eg 10% overhead, add a sleep call.)
1960
paths = FinalPaths(self)
1961
for trans_id, observed in self._observed_sha1s.items():
1962
path = paths.get_path(trans_id)
1963
self._tree._observed_sha1(path, observed)
1966
class TransformPreview(DiskTreeTransform):
1967
"""A TreeTransform for generating preview trees.
1969
Unlike TreeTransform, this version works when the input tree is a
1970
RevisionTree, rather than a WorkingTree. As a result, it tends to ignore
1971
unversioned files in the input tree.
1974
def __init__(self, tree, pb=None, case_sensitive=True):
1976
limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
1977
DiskTreeTransform.__init__(self, tree, limbodir, pb, case_sensitive)
1979
def canonical_path(self, path):
1982
def tree_kind(self, trans_id):
1983
path = self._tree_id_paths.get(trans_id)
1986
kind = self._tree.path_content_summary(path)[0]
1987
if kind == 'missing':
1991
def _set_mode(self, trans_id, mode_id, typefunc):
1992
"""Set the mode of new file contents.
1993
The mode_id is the existing file to get the mode from (often the same
1994
as trans_id). The operation is only performed if there's a mode match
1995
according to typefunc.
1997
# is it ok to ignore this? probably
2000
def iter_tree_children(self, parent_id):
2001
"""Iterate through the entry's tree children, if any"""
2003
path = self._tree_id_paths[parent_id]
2007
entry = next(self._tree.iter_entries_by_dir(
2008
specific_files=[path]))[1]
2009
except StopIteration:
2011
children = getattr(entry, 'children', {})
2012
for child in children:
2013
childpath = joinpath(path, child)
2014
yield self.trans_id_tree_path(childpath)
2016
def new_orphan(self, trans_id, parent_id):
2017
raise NotImplementedError(self.new_orphan)
2020
class _PreviewTree(inventorytree.InventoryTree):
2021
"""Partial implementation of Tree to support show_diff_trees"""
2023
def __init__(self, transform):
2024
self._transform = transform
2025
self._final_paths = FinalPaths(transform)
2026
self.__by_parent = None
2027
self._parent_ids = []
2028
self._all_children_cache = {}
2029
self._path2trans_id_cache = {}
2030
self._final_name_cache = {}
2031
self._iter_changes_cache = dict((c.file_id, c) for c in
2032
self._transform.iter_changes())
2034
def supports_tree_reference(self):
2035
# TODO(jelmer): Support tree references in _PreviewTree.
2036
# return self._transform._tree.supports_tree_reference()
2039
def _content_change(self, file_id):
2040
"""Return True if the content of this file changed"""
2041
changes = self._iter_changes_cache.get(file_id)
2042
return (changes is not None and changes.changed_content)
2044
def _get_repository(self):
2045
repo = getattr(self._transform._tree, '_repository', None)
2047
repo = self._transform._tree.branch.repository
2050
def _iter_parent_trees(self):
2051
for revision_id in self.get_parent_ids():
2053
yield self.revision_tree(revision_id)
2054
except errors.NoSuchRevisionInTree:
2055
yield self._get_repository().revision_tree(revision_id)
2057
def _get_file_revision(self, path, file_id, vf, tree_revision):
2059
(file_id, t.get_file_revision(t.id2path(file_id)))
2060
for t in self._iter_parent_trees()]
2061
vf.add_lines((file_id, tree_revision), parent_keys,
2062
self.get_file_lines(path))
2063
repo = self._get_repository()
2064
base_vf = repo.texts
2065
if base_vf not in vf.fallback_versionedfiles:
2066
vf.fallback_versionedfiles.append(base_vf)
2067
return tree_revision
2069
def _stat_limbo_file(self, trans_id):
2070
name = self._transform._limbo_name(trans_id)
2071
return os.lstat(name)
2074
def _by_parent(self):
2075
if self.__by_parent is None:
2076
self.__by_parent = self._transform.by_parent()
2077
return self.__by_parent
2079
def _comparison_data(self, entry, path):
2080
kind, size, executable, link_or_sha1 = self.path_content_summary(path)
2081
if kind == 'missing':
2085
file_id = self._transform.final_file_id(self._path2trans_id(path))
2086
executable = self.is_executable(path)
2087
return kind, executable, None
2089
def is_locked(self):
2092
def lock_read(self):
2093
# Perhaps in theory, this should lock the TreeTransform?
2094
return lock.LogicalLockResult(self.unlock)
2100
def root_inventory(self):
2101
"""This Tree does not use inventory as its backing data."""
2102
raise NotImplementedError(_PreviewTree.root_inventory)
2104
def all_file_ids(self):
2105
tree_ids = set(self._transform._tree.all_file_ids())
2106
tree_ids.difference_update(self._transform.tree_file_id(t)
2107
for t in self._transform._removed_id)
2108
tree_ids.update(self._transform._new_id.values())
2111
def all_versioned_paths(self):
2112
tree_paths = set(self._transform._tree.all_versioned_paths())
2114
tree_paths.difference_update(
2115
self._transform.trans_id_tree_path(t)
2116
for t in self._transform._removed_id)
2119
self._final_paths._determine_path(t)
2120
for t in self._transform._new_id)
2124
def _path2trans_id(self, path):
2125
# We must not use None here, because that is a valid value to store.
2126
trans_id = self._path2trans_id_cache.get(path, object)
2127
if trans_id is not object:
2129
segments = splitpath(path)
2130
cur_parent = self._transform.root
2131
for cur_segment in segments:
2132
for child in self._all_children(cur_parent):
2133
final_name = self._final_name_cache.get(child)
2134
if final_name is None:
2135
final_name = self._transform.final_name(child)
2136
self._final_name_cache[child] = final_name
2137
if final_name == cur_segment:
2141
self._path2trans_id_cache[path] = None
2143
self._path2trans_id_cache[path] = cur_parent
2146
def path2id(self, path):
2147
if isinstance(path, list):
2150
path = osutils.pathjoin(*path)
2151
return self._transform.final_file_id(self._path2trans_id(path))
2153
def id2path(self, file_id, recurse='down'):
2154
trans_id = self._transform.trans_id_file_id(file_id)
2156
return self._final_paths._determine_path(trans_id)
2158
raise errors.NoSuchId(self, file_id)
2160
def _all_children(self, trans_id):
2161
children = self._all_children_cache.get(trans_id)
2162
if children is not None:
2164
children = set(self._transform.iter_tree_children(trans_id))
2165
# children in the _new_parent set are provided by _by_parent.
2166
children.difference_update(self._transform._new_parent)
2167
children.update(self._by_parent.get(trans_id, []))
2168
self._all_children_cache[trans_id] = children
2172
possible_extras = set(self._transform.trans_id_tree_path(p) for p
2173
in self._transform._tree.extras())
2174
possible_extras.update(self._transform._new_contents)
2175
possible_extras.update(self._transform._removed_id)
2176
for trans_id in possible_extras:
2177
if self._transform.final_file_id(trans_id) is None:
2178
yield self._final_paths._determine_path(trans_id)
2180
def _make_inv_entries(self, ordered_entries, specific_files=None):
2181
for trans_id, parent_file_id in ordered_entries:
2182
file_id = self._transform.final_file_id(trans_id)
2185
if (specific_files is not None
2186
and self._final_paths.get_path(trans_id) not in specific_files):
2188
kind = self._transform.final_kind(trans_id)
2190
kind = self._transform._tree.stored_kind(
2191
self._transform._tree.id2path(file_id))
2192
new_entry = inventory.make_entry(
2194
self._transform.final_name(trans_id),
2195
parent_file_id, file_id)
2196
yield new_entry, trans_id
2198
def _list_files_by_dir(self):
2199
todo = [ROOT_PARENT]
2201
while len(todo) > 0:
2203
parent_file_id = self._transform.final_file_id(parent)
2204
children = list(self._all_children(parent))
2205
paths = dict(zip(children, self._final_paths.get_paths(children)))
2206
children.sort(key=paths.get)
2207
todo.extend(reversed(children))
2208
for trans_id in children:
2209
ordered_ids.append((trans_id, parent_file_id))
2212
def iter_child_entries(self, path):
2213
trans_id = self._path2trans_id(path)
2214
if trans_id is None:
2215
raise errors.NoSuchFile(path)
2216
todo = [(child_trans_id, trans_id) for child_trans_id in
2217
self._all_children(trans_id)]
2218
for entry, trans_id in self._make_inv_entries(todo):
2221
def iter_entries_by_dir(self, specific_files=None, recurse_nested=False):
2223
raise NotImplementedError(
2224
'follow tree references not yet supported')
2226
# This may not be a maximally efficient implementation, but it is
2227
# reasonably straightforward. An implementation that grafts the
2228
# TreeTransform changes onto the tree's iter_entries_by_dir results
2229
# might be more efficient, but requires tricky inferences about stack
2231
ordered_ids = self._list_files_by_dir()
2232
for entry, trans_id in self._make_inv_entries(ordered_ids,
2234
yield self._final_paths.get_path(trans_id), entry
2236
def _iter_entries_for_dir(self, dir_path):
2237
"""Return path, entry for items in a directory without recursing down."""
2239
dir_trans_id = self._path2trans_id(dir_path)
2240
dir_id = self._transform.final_file_id(dir_trans_id)
2241
for child_trans_id in self._all_children(dir_trans_id):
2242
ordered_ids.append((child_trans_id, dir_id))
2244
for entry, trans_id in self._make_inv_entries(ordered_ids):
2245
path_entries.append((self._final_paths.get_path(trans_id), entry))
2249
def list_files(self, include_root=False, from_dir=None, recursive=True,
2250
recurse_nested=False):
2251
"""See WorkingTree.list_files."""
2253
raise NotImplementedError(
2254
'follow tree references not yet supported')
2256
# XXX This should behave like WorkingTree.list_files, but is really
2257
# more like RevisionTree.list_files.
2263
prefix = from_dir + '/'
2264
entries = self.iter_entries_by_dir()
2265
for path, entry in entries:
2266
if entry.name == '' and not include_root:
2269
if not path.startswith(prefix):
2271
path = path[len(prefix):]
2272
yield path, 'V', entry.kind, entry
2274
if from_dir is None and include_root is True:
2275
root_entry = inventory.make_entry(
2276
'directory', '', ROOT_PARENT, self.path2id(''))
2277
yield '', 'V', 'directory', root_entry
2278
entries = self._iter_entries_for_dir(from_dir or '')
2279
for path, entry in entries:
2280
yield path, 'V', entry.kind, entry
2282
def kind(self, path):
2283
trans_id = self._path2trans_id(path)
2284
if trans_id is None:
2285
raise errors.NoSuchFile(path)
2286
return self._transform.final_kind(trans_id)
2288
def stored_kind(self, path):
2289
trans_id = self._path2trans_id(path)
2290
if trans_id is None:
2291
raise errors.NoSuchFile(path)
2293
return self._transform._new_contents[trans_id]
2295
return self._transform._tree.stored_kind(path)
2297
def get_file_mtime(self, path):
2298
"""See Tree.get_file_mtime"""
2299
file_id = self.path2id(path)
2301
raise errors.NoSuchFile(path)
2302
if not self._content_change(file_id):
2303
return self._transform._tree.get_file_mtime(
2304
self._transform._tree.id2path(file_id))
2305
trans_id = self._path2trans_id(path)
2306
return self._stat_limbo_file(trans_id).st_mtime
2308
def get_file_size(self, path):
2309
"""See Tree.get_file_size"""
2310
trans_id = self._path2trans_id(path)
2311
if trans_id is None:
2312
raise errors.NoSuchFile(path)
2313
kind = self._transform.final_kind(trans_id)
2316
if trans_id in self._transform._new_contents:
2317
return self._stat_limbo_file(trans_id).st_size
2318
if self.kind(path) == 'file':
2319
return self._transform._tree.get_file_size(path)
2323
def get_file_verifier(self, path, stat_value=None):
2324
trans_id = self._path2trans_id(path)
2325
if trans_id is None:
2326
raise errors.NoSuchFile(path)
2327
kind = self._transform._new_contents.get(trans_id)
2329
return self._transform._tree.get_file_verifier(path)
2331
with self.get_file(path) as fileobj:
2332
return ("SHA1", sha_file(fileobj))
2334
def get_file_sha1(self, path, stat_value=None):
2335
trans_id = self._path2trans_id(path)
2336
if trans_id is None:
2337
raise errors.NoSuchFile(path)
2338
kind = self._transform._new_contents.get(trans_id)
2340
return self._transform._tree.get_file_sha1(path)
2342
with self.get_file(path) as fileobj:
2343
return sha_file(fileobj)
2345
def get_reference_revision(self, path):
2346
trans_id = self._path2trans_id(path)
2347
if trans_id is None:
2348
raise errors.NoSuchFile(path)
2349
reference_revision = self._transform._new_reference_revision.get(trans_id)
2350
if reference_revision is None:
2351
return self._transform._tree.get_reference_revision(path)
2352
return reference_revision
2354
def is_executable(self, path):
2355
trans_id = self._path2trans_id(path)
2356
if trans_id is None:
2359
return self._transform._new_executability[trans_id]
2362
return self._transform._tree.is_executable(path)
2363
except OSError as e:
2364
if e.errno == errno.ENOENT:
2367
except errors.NoSuchFile:
2370
def has_filename(self, path):
2371
trans_id = self._path2trans_id(path)
2372
if trans_id in self._transform._new_contents:
2374
elif trans_id in self._transform._removed_contents:
2377
return self._transform._tree.has_filename(path)
2379
def path_content_summary(self, path):
2380
trans_id = self._path2trans_id(path)
2381
tt = self._transform
2382
tree_path = tt._tree_id_paths.get(trans_id)
2383
kind = tt._new_contents.get(trans_id)
2385
if tree_path is None or trans_id in tt._removed_contents:
2386
return 'missing', None, None, None
2387
summary = tt._tree.path_content_summary(tree_path)
2388
kind, size, executable, link_or_sha1 = summary
2391
limbo_name = tt._limbo_name(trans_id)
2392
if trans_id in tt._new_reference_revision:
2393
kind = 'tree-reference'
2395
statval = os.lstat(limbo_name)
2396
size = statval.st_size
2397
if not tt._limbo_supports_executable():
2400
executable = statval.st_mode & S_IEXEC
2404
if kind == 'symlink':
2405
link_or_sha1 = os.readlink(limbo_name)
2406
if not isinstance(link_or_sha1, str):
2407
link_or_sha1 = link_or_sha1.decode(osutils._fs_enc)
2408
executable = tt._new_executability.get(trans_id, executable)
2409
return kind, size, executable, link_or_sha1
2411
def iter_changes(self, from_tree, include_unchanged=False,
2412
specific_files=None, pb=None, extra_trees=None,
2413
require_versioned=True, want_unversioned=False):
2414
"""See InterTree.iter_changes.
2416
This has a fast path that is only used when the from_tree matches
2417
the transform tree, and no fancy options are supplied.
2419
if (from_tree is not self._transform._tree or include_unchanged
2420
or specific_files or want_unversioned):
2421
return tree.InterTree(from_tree, self).iter_changes(
2422
include_unchanged=include_unchanged,
2423
specific_files=specific_files,
2425
extra_trees=extra_trees,
2426
require_versioned=require_versioned,
2427
want_unversioned=want_unversioned)
2428
if want_unversioned:
2429
raise ValueError('want_unversioned is not supported')
2430
return self._transform.iter_changes()
2432
def get_file(self, path):
2433
"""See Tree.get_file"""
2434
file_id = self.path2id(path)
2435
if not self._content_change(file_id):
2436
return self._transform._tree.get_file(path)
2437
trans_id = self._path2trans_id(path)
2438
name = self._transform._limbo_name(trans_id)
2439
return open(name, 'rb')
2441
def get_file_with_stat(self, path):
2442
return self.get_file(path), None
2444
def annotate_iter(self, path,
2445
default_revision=_mod_revision.CURRENT_REVISION):
2446
file_id = self.path2id(path)
2447
changes = self._iter_changes_cache.get(file_id)
2451
changed_content, versioned, kind = (
2452
changes.changed_content, changes.versioned, changes.kind)
2455
get_old = (kind[0] == 'file' and versioned[0])
2457
old_annotation = self._transform._tree.annotate_iter(
2458
path, default_revision=default_revision)
2462
return old_annotation
2463
if not changed_content:
2464
return old_annotation
2465
# TODO: This is doing something similar to what WT.annotate_iter is
2466
# doing, however it fails slightly because it doesn't know what
2467
# the *other* revision_id is, so it doesn't know how to give the
2468
# other as the origin for some lines, they all get
2469
# 'default_revision'
2470
# It would be nice to be able to use the new Annotator based
2471
# approach, as well.
2472
return annotate.reannotate([old_annotation],
2473
self.get_file(path).readlines(),
2476
def get_symlink_target(self, path):
2477
"""See Tree.get_symlink_target"""
2478
file_id = self.path2id(path)
2479
if not self._content_change(file_id):
2480
return self._transform._tree.get_symlink_target(path)
2481
trans_id = self._path2trans_id(path)
2482
name = self._transform._limbo_name(trans_id)
2483
return osutils.readlink(name)
2485
def walkdirs(self, prefix=''):
2486
pending = [self._transform.root]
2487
while len(pending) > 0:
2488
parent_id = pending.pop()
2491
prefix = prefix.rstrip('/')
2492
parent_path = self._final_paths.get_path(parent_id)
2493
parent_file_id = self._transform.final_file_id(parent_id)
2494
for child_id in self._all_children(parent_id):
2495
path_from_root = self._final_paths.get_path(child_id)
2496
basename = self._transform.final_name(child_id)
2497
file_id = self._transform.final_file_id(child_id)
2498
kind = self._transform.final_kind(child_id)
2499
if kind is not None:
2500
versioned_kind = kind
2503
versioned_kind = self._transform._tree.stored_kind(
2504
self._transform._tree.id2path(file_id))
2505
if versioned_kind == 'directory':
2506
subdirs.append(child_id)
2507
children.append((path_from_root, basename, kind, None,
2508
file_id, versioned_kind))
2510
if parent_path.startswith(prefix):
2511
yield (parent_path, parent_file_id), children
2512
pending.extend(sorted(subdirs, key=self._final_paths.get_path,
2515
def get_parent_ids(self):
2516
return self._parent_ids
2518
def set_parent_ids(self, parent_ids):
2519
self._parent_ids = parent_ids
2521
def get_revision_tree(self, revision_id):
2522
return self._transform._tree.get_revision_tree(revision_id)
599
2525
def joinpath(parent, child):
600
2526
"""Join tree-relative paths, handling the tree root specially"""
601
2527
if parent is None or parent == "":