/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/transform.py

  • Committer: Ian Clatworthy
  • Date: 2009-07-02 08:26:00 UTC
  • mto: (4527.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4529.
  • Revision ID: ian.clatworthy@canonical.com-20090702082600-qwb1evvvfa8ctnye
first draft of a 2.0 Upgrade Guide

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
17
17
import os
18
18
import errno
19
19
from stat import S_ISREG, S_IEXEC
20
 
import time
21
20
 
22
21
from bzrlib.lazy_import import lazy_import
23
22
lazy_import(globals(), """
25
24
    annotate,
26
25
    bencode,
27
26
    bzrdir,
28
 
    commit,
29
27
    delta,
30
28
    errors,
31
29
    inventory,
32
30
    multiparent,
33
31
    osutils,
34
32
    revision as _mod_revision,
35
 
    ui,
36
33
    )
37
34
""")
38
35
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
39
 
                           ReusingTransform, CantMoveRoot,
 
36
                           ReusingTransform, NotVersionedError, CantMoveRoot,
40
37
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
41
38
                           UnableCreateSymlink)
42
39
from bzrlib.filters import filtered_output_bytes, ContentFilterContext
51
48
    splitpath,
52
49
    supports_executable,
53
50
)
54
 
from bzrlib.progress import ProgressPhase
 
51
from bzrlib.progress import DummyProgress, ProgressPhase
55
52
from bzrlib.symbol_versioning import (
56
53
        deprecated_function,
57
54
        deprecated_in,
81
78
class TreeTransformBase(object):
82
79
    """The base class for TreeTransform and its kin."""
83
80
 
84
 
    def __init__(self, tree, pb=None,
 
81
    def __init__(self, tree, pb=DummyProgress(),
85
82
                 case_sensitive=True):
86
83
        """Constructor.
87
84
 
88
85
        :param tree: The tree that will be transformed, but not necessarily
89
86
            the output tree.
90
 
        :param pb: ignored
 
87
        :param pb: A ProgressBar indicating how much progress is being made
91
88
        :param case_sensitive: If True, the target of the transform is
92
89
            case sensitive, not just case preserving.
93
90
        """
164
161
 
165
162
    def adjust_path(self, name, parent, trans_id):
166
163
        """Change the path that is assigned to a transaction id."""
167
 
        if parent is None:
168
 
            raise ValueError("Parent trans-id may not be None")
169
164
        if trans_id == self._new_root:
170
165
            raise CantMoveRoot
171
166
        self._new_name[trans_id] = name
172
167
        self._new_parent[trans_id] = parent
 
168
        if parent == ROOT_PARENT:
 
169
            if self._new_root is not None:
 
170
                raise ValueError("Cannot have multiple roots.")
 
171
            self._new_root = trans_id
173
172
 
174
173
    def adjust_root_path(self, name, parent):
175
174
        """Emulate moving the root by moving all children, instead.
203
202
        self.version_file(old_root_file_id, old_root)
204
203
        self.unversion_file(self._new_root)
205
204
 
206
 
    def fixup_new_roots(self):
207
 
        """Reinterpret requests to change the root directory
208
 
 
209
 
        Instead of creating a root directory, or moving an existing directory,
210
 
        all the attributes and children of the new root are applied to the
211
 
        existing root directory.
212
 
 
213
 
        This means that the old root trans-id becomes obsolete, so it is
214
 
        recommended only to invoke this after the root trans-id has become
215
 
        irrelevant.
216
 
        """
217
 
        new_roots = [k for k, v in self._new_parent.iteritems() if v is
218
 
                     ROOT_PARENT]
219
 
        if len(new_roots) < 1:
220
 
            return
221
 
        if len(new_roots) != 1:
222
 
            raise ValueError('A tree cannot have two roots!')
223
 
        if self._new_root is None:
224
 
            self._new_root = new_roots[0]
225
 
            return
226
 
        old_new_root = new_roots[0]
227
 
        # TODO: What to do if a old_new_root is present, but self._new_root is
228
 
        #       not listed as being removed? This code explicitly unversions
229
 
        #       the old root and versions it with the new file_id. Though that
230
 
        #       seems like an incomplete delta
231
 
 
232
 
        # unversion the new root's directory.
233
 
        file_id = self.final_file_id(old_new_root)
234
 
        if old_new_root in self._new_id:
235
 
            self.cancel_versioning(old_new_root)
236
 
        else:
237
 
            self.unversion_file(old_new_root)
238
 
        # if, at this stage, root still has an old file_id, zap it so we can
239
 
        # stick a new one in.
240
 
        if (self.tree_file_id(self._new_root) is not None and
241
 
            self._new_root not in self._removed_id):
242
 
            self.unversion_file(self._new_root)
243
 
        self.version_file(file_id, self._new_root)
244
 
 
245
 
        # Now move children of new root into old root directory.
246
 
        # Ensure all children are registered with the transaction, but don't
247
 
        # use directly-- some tree children have new parents
248
 
        list(self.iter_tree_children(old_new_root))
249
 
        # Move all children of new root into old root directory.
250
 
        for child in self.by_parent().get(old_new_root, []):
251
 
            self.adjust_path(self.final_name(child), self._new_root, child)
252
 
 
253
 
        # Ensure old_new_root has no directory.
254
 
        if old_new_root in self._new_contents:
255
 
            self.cancel_creation(old_new_root)
256
 
        else:
257
 
            self.delete_contents(old_new_root)
258
 
 
259
 
        # prevent deletion of root directory.
260
 
        if self._new_root in self._removed_contents:
261
 
            self.cancel_deletion(self._new_root)
262
 
 
263
 
        # destroy path info for old_new_root.
264
 
        del self._new_parent[old_new_root]
265
 
        del self._new_name[old_new_root]
266
 
 
267
205
    def trans_id_tree_file_id(self, inventory_id):
268
206
        """Determine the transaction id of a working tree file.
269
207
 
315
253
 
316
254
    def delete_contents(self, trans_id):
317
255
        """Schedule the contents of a path entry for deletion"""
318
 
        # Ensure that the object exists in the WorkingTree, this will raise an
319
 
        # exception if there is a problem
320
256
        self.tree_kind(trans_id)
321
257
        self._removed_contents.add(trans_id)
322
258
 
506
442
        conflicts.extend(self._overwrite_conflicts())
507
443
        return conflicts
508
444
 
509
 
    def _check_malformed(self):
510
 
        conflicts = self.find_conflicts()
511
 
        if len(conflicts) != 0:
512
 
            raise MalformedTransform(conflicts=conflicts)
513
 
 
514
445
    def _add_tree_children(self):
515
446
        """Add all the children of all active parents to the known paths.
516
447
 
923
854
    def get_preview_tree(self):
924
855
        """Return a tree representing the result of the transform.
925
856
 
926
 
        The tree is a snapshot, and altering the TreeTransform will invalidate
927
 
        it.
 
857
        This tree only supports the subset of Tree functionality required
 
858
        by show_diff_trees.  It must only be compared to tt._tree.
928
859
        """
929
860
        return _PreviewTree(self)
930
861
 
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.
935
 
 
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
939
 
            pending merges.
940
 
        :param strict: If True, abort the commit if there are unversioned
941
 
            files.
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
945
 
            seconds.
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.
953
 
        """
954
 
        self._check_malformed()
955
 
        if strict:
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()
960
 
 
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'
965
 
                                 ' commit.')
966
 
            parent_ids = []
967
 
        else:
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,
976
 
                                            timestamp=timestamp,
977
 
                                            timezone=timezone,
978
 
                                            committer=committer,
979
 
                                            revprops=revprops,
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)
987
 
        return revision_id
988
 
 
989
862
    def _text_parent(self, trans_id):
990
863
        file_id = self.tree_file_id(trans_id)
991
864
        try:
1085
958
class DiskTreeTransform(TreeTransformBase):
1086
959
    """Tree transform storing its contents on disk."""
1087
960
 
1088
 
    def __init__(self, tree, limbodir, pb=None,
 
961
    def __init__(self, tree, limbodir, pb=DummyProgress(),
1089
962
                 case_sensitive=True):
1090
963
        """Constructor.
1091
964
        :param tree: The tree that will be transformed, but not necessarily
1092
965
            the output tree.
1093
966
        :param limbodir: A directory where new files can be stored until
1094
967
            they are installed in their proper places
1095
 
        :param pb: ignored
 
968
        :param pb: A ProgressBar indicating how much progress is being made
1096
969
        :param case_sensitive: If True, the target of the transform is
1097
970
            case sensitive, not just case preserving.
1098
971
        """
1108
981
        self._limbo_children_names = {}
1109
982
        # List of transform ids that need to be renamed from limbo into place
1110
983
        self._needs_rename = set()
1111
 
        self._creation_mtime = None
1112
984
 
1113
985
    def finalize(self):
1114
986
        """Release the working tree lock, if held, clean up limbo dir.
1140
1012
    def _limbo_name(self, trans_id):
1141
1013
        """Generate the limbo name of a file"""
1142
1014
        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
 
1015
        if limbo_name is not None:
 
1016
            return limbo_name
 
1017
        parent = self._new_parent.get(trans_id)
 
1018
        # if the parent directory is already in limbo (e.g. when building a
 
1019
        # tree), choose a limbo name inside the parent, to reduce further
 
1020
        # renames.
 
1021
        use_direct_path = False
 
1022
        if self._new_contents.get(parent) == 'directory':
 
1023
            filename = self._new_name.get(trans_id)
 
1024
            if filename is not None:
 
1025
                if parent not in self._limbo_children:
 
1026
                    self._limbo_children[parent] = set()
 
1027
                    self._limbo_children_names[parent] = {}
 
1028
                    use_direct_path = True
 
1029
                # the direct path can only be used if no other file has
 
1030
                # already taken this pathname, i.e. if the name is unused, or
 
1031
                # if it is already associated with this trans_id.
 
1032
                elif self._case_sensitive_target:
 
1033
                    if (self._limbo_children_names[parent].get(filename)
 
1034
                        in (trans_id, None)):
 
1035
                        use_direct_path = True
 
1036
                else:
 
1037
                    for l_filename, l_trans_id in\
 
1038
                        self._limbo_children_names[parent].iteritems():
 
1039
                        if l_trans_id == trans_id:
 
1040
                            continue
 
1041
                        if l_filename.lower() == filename.lower():
 
1042
                            break
 
1043
                    else:
 
1044
                        use_direct_path = True
 
1045
 
 
1046
        if use_direct_path:
 
1047
            limbo_name = pathjoin(self._limbo_files[parent], filename)
 
1048
            self._limbo_children[parent].add(trans_id)
 
1049
            self._limbo_children_names[parent][filename] = trans_id
 
1050
        else:
 
1051
            limbo_name = pathjoin(self._limbodir, trans_id)
 
1052
            self._needs_rename.add(trans_id)
 
1053
        self._limbo_files[trans_id] = limbo_name
1146
1054
        return limbo_name
1147
1055
 
1148
 
    def _generate_limbo_path(self, trans_id):
1149
 
        """Generate a limbo path using the trans_id as the relative path.
1150
 
 
1151
 
        This is suitable as a fallback, and when the transform should not be
1152
 
        sensitive to the path encoding of the limbo directory.
1153
 
        """
1154
 
        self._needs_rename.add(trans_id)
1155
 
        return pathjoin(self._limbodir, trans_id)
1156
 
 
1157
1056
    def adjust_path(self, name, parent, trans_id):
1158
1057
        previous_parent = self._new_parent.get(trans_id)
1159
1058
        previous_name = self._new_name.get(trans_id)
1161
1060
        if (trans_id in self._limbo_files and
1162
1061
            trans_id not in self._needs_rename):
1163
1062
            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]
 
1063
            self._limbo_children[previous_parent].remove(trans_id)
 
1064
            del self._limbo_children_names[previous_parent][previous_name]
1168
1065
 
1169
1066
    def _rename_in_limbo(self, trans_ids):
1170
1067
        """Fix limbo names so that the right final path is produced.
1183
1080
                continue
1184
1081
            new_path = self._limbo_name(trans_id)
1185
1082
            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
1190
 
 
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))
1196
 
        return descendants
1197
1083
 
1198
1084
    def create_file(self, contents, trans_id, mode_id=None):
1199
1085
        """Schedule creation of a new file.
1221
1107
            f.writelines(contents)
1222
1108
        finally:
1223
1109
            f.close()
1224
 
        self._set_mtime(name)
1225
1110
        self._set_mode(trans_id, mode_id, S_ISREG)
1226
1111
 
1227
1112
    def _read_file_chunks(self, trans_id):
1234
1119
    def _read_symlink_target(self, trans_id):
1235
1120
        return os.readlink(self._limbo_name(trans_id))
1236
1121
 
1237
 
    def _set_mtime(self, path):
1238
 
        """All files that are created get the same mtime.
1239
 
 
1240
 
        This time is set by the first object to be created.
1241
 
        """
1242
 
        if self._creation_mtime is None:
1243
 
            self._creation_mtime = time.time()
1244
 
        os.utime(path, (self._creation_mtime, self._creation_mtime))
1245
 
 
1246
1122
    def create_hardlink(self, path, trans_id):
1247
1123
        """Schedule creation of a hard link"""
1248
1124
        name = self._limbo_name(trans_id)
1362
1238
    FileMover does not delete files until it is sure that a rollback will not
1363
1239
    happen.
1364
1240
    """
1365
 
    def __init__(self, tree, pb=None):
 
1241
    def __init__(self, tree, pb=DummyProgress()):
1366
1242
        """Note: a tree_write lock is taken on the tree.
1367
1243
 
1368
1244
        Use TreeTransform.finalize() to release the lock (can be omitted if
1478
1354
                continue
1479
1355
            yield self.trans_id_tree_path(childpath)
1480
1356
 
1481
 
    def _generate_limbo_path(self, trans_id):
1482
 
        """Generate a limbo path using the final path if possible.
1483
 
 
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.
1487
 
 
1488
 
        If the final path cannot be used, falls back to using the trans_id as
1489
 
        the relpath.
1490
 
        """
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
1494
 
        # renames.
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
1510
 
                else:
1511
 
                    for l_filename, l_trans_id in\
1512
 
                        self._limbo_children_names[parent].iteritems():
1513
 
                        if l_trans_id == trans_id:
1514
 
                            continue
1515
 
                        if l_filename.lower() == filename.lower():
1516
 
                            break
1517
 
                    else:
1518
 
                        use_direct_path = True
1519
 
 
1520
 
        if not use_direct_path:
1521
 
            return DiskTreeTransform._generate_limbo_path(self, trans_id)
1522
 
 
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
1526
 
        return limbo_name
1527
 
 
1528
1357
 
1529
1358
    def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
1530
1359
        """Apply all changes to the inventory and filesystem.
1541
1370
        :param _mover: Supply an alternate FileMover, for testing
1542
1371
        """
1543
1372
        if not no_conflicts:
1544
 
            self._check_malformed()
 
1373
            conflicts = self.find_conflicts()
 
1374
            if len(conflicts) != 0:
 
1375
                raise MalformedTransform(conflicts=conflicts)
1545
1376
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1546
1377
        try:
1547
1378
            if precomputed_delta is None:
1651
1482
                child_pb.update('removing file', num, len(tree_paths))
1652
1483
                full_path = self._tree.abspath(path)
1653
1484
                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):
 
1485
                    mover.pre_delete(full_path, os.path.join(self._deletiondir,
 
1486
                                     trans_id))
 
1487
                elif trans_id in self._new_name or trans_id in \
 
1488
                    self._new_parent:
1658
1489
                    try:
1659
1490
                        mover.rename(full_path, self._limbo_name(trans_id))
1660
 
                    except errors.TransformRenameFailed, e:
 
1491
                    except OSError, e:
1661
1492
                        if e.errno != errno.ENOENT:
1662
1493
                            raise
1663
1494
                    else:
1688
1519
                if trans_id in self._needs_rename:
1689
1520
                    try:
1690
1521
                        mover.rename(self._limbo_name(trans_id), full_path)
1691
 
                    except errors.TransformRenameFailed, e:
 
1522
                    except OSError, e:
1692
1523
                        # We may be renaming a dangling inventory id
1693
1524
                        if e.errno != errno.ENOENT:
1694
1525
                            raise
1714
1545
    unversioned files in the input tree.
1715
1546
    """
1716
1547
 
1717
 
    def __init__(self, tree, pb=None, case_sensitive=True):
 
1548
    def __init__(self, tree, pb=DummyProgress(), case_sensitive=True):
1718
1549
        tree.lock_read()
1719
1550
        limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
1720
1551
        DiskTreeTransform.__init__(self, tree, limbodir, pb, case_sensitive)
1765
1596
        self._all_children_cache = {}
1766
1597
        self._path2trans_id_cache = {}
1767
1598
        self._final_name_cache = {}
1768
 
        self._iter_changes_cache = dict((c[0], c) for c in
1769
 
                                        self._transform.iter_changes())
 
1599
 
 
1600
    def _changes(self, file_id):
 
1601
        for changes in self._transform.iter_changes():
 
1602
            if changes[0] == file_id:
 
1603
                return changes
1770
1604
 
1771
1605
    def _content_change(self, file_id):
1772
1606
        """Return True if the content of this file changed"""
1773
 
        changes = self._iter_changes_cache.get(file_id)
 
1607
        changes = self._changes(file_id)
1774
1608
        # changes[2] is true if the file content changed.  See
1775
1609
        # InterTree.iter_changes.
1776
1610
        return (changes is not None and changes[2])
1792
1626
        parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
1793
1627
                       self._iter_parent_trees()]
1794
1628
        vf.add_lines((file_id, tree_revision), parent_keys,
1795
 
                     self.get_file_lines(file_id))
 
1629
                     self.get_file(file_id).readlines())
1796
1630
        repo = self._get_repository()
1797
1631
        base_vf = repo.texts
1798
1632
        if base_vf not in vf.fallback_versionedfiles:
1820
1654
            executable = self.is_executable(file_id, path)
1821
1655
        return kind, executable, None
1822
1656
 
1823
 
    def is_locked(self):
1824
 
        return False
1825
 
 
1826
1657
    def lock_read(self):
1827
1658
        # Perhaps in theory, this should lock the TreeTransform?
1828
 
        return self
 
1659
        pass
1829
1660
 
1830
1661
    def unlock(self):
1831
1662
        pass
1848
1679
    def __iter__(self):
1849
1680
        return iter(self.all_file_ids())
1850
1681
 
1851
 
    def _has_id(self, file_id, fallback_check):
 
1682
    def has_id(self, file_id):
1852
1683
        if file_id in self._transform._r_new_id:
1853
1684
            return True
1854
1685
        elif file_id in set([self._transform.tree_file_id(trans_id) for
1855
1686
            trans_id in self._transform._removed_id]):
1856
1687
            return False
1857
1688
        else:
1858
 
            return fallback_check(file_id)
1859
 
 
1860
 
    def has_id(self, file_id):
1861
 
        return self._has_id(file_id, self._transform._tree.has_id)
1862
 
 
1863
 
    def has_or_had_id(self, file_id):
1864
 
        return self._has_id(file_id, self._transform._tree.has_or_had_id)
 
1689
            return self._transform._tree.has_id(file_id)
1865
1690
 
1866
1691
    def _path2trans_id(self, path):
1867
1692
        # We must not use None here, because that is a valid value to store.
1920
1745
            if self._transform.final_file_id(trans_id) is None:
1921
1746
                yield self._final_paths._determine_path(trans_id)
1922
1747
 
1923
 
    def _make_inv_entries(self, ordered_entries, specific_file_ids=None,
1924
 
        yield_parents=False):
 
1748
    def _make_inv_entries(self, ordered_entries, specific_file_ids=None):
1925
1749
        for trans_id, parent_file_id in ordered_entries:
1926
1750
            file_id = self._transform.final_file_id(trans_id)
1927
1751
            if file_id is None:
1953
1777
                ordered_ids.append((trans_id, parent_file_id))
1954
1778
        return ordered_ids
1955
1779
 
1956
 
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
 
1780
    def iter_entries_by_dir(self, specific_file_ids=None):
1957
1781
        # This may not be a maximally efficient implementation, but it is
1958
1782
        # reasonably straightforward.  An implementation that grafts the
1959
1783
        # TreeTransform changes onto the tree's iter_entries_by_dir results
1961
1785
        # position.
1962
1786
        ordered_ids = self._list_files_by_dir()
1963
1787
        for entry, trans_id in self._make_inv_entries(ordered_ids,
1964
 
            specific_file_ids, yield_parents=yield_parents):
 
1788
                                                      specific_file_ids):
1965
1789
            yield unicode(self._final_paths.get_path(trans_id)), entry
1966
1790
 
1967
1791
    def _iter_entries_for_dir(self, dir_path):
2014
1838
    def get_file_mtime(self, file_id, path=None):
2015
1839
        """See Tree.get_file_mtime"""
2016
1840
        if not self._content_change(file_id):
2017
 
            return self._transform._tree.get_file_mtime(file_id)
 
1841
            return self._transform._tree.get_file_mtime(file_id, path)
2018
1842
        return self._stat_limbo_file(file_id).st_mtime
2019
1843
 
2020
1844
    def _file_size(self, entry, stat_value):
2074
1898
                statval = os.lstat(limbo_name)
2075
1899
                size = statval.st_size
2076
1900
                if not supports_executable():
2077
 
                    executable = False
 
1901
                    executable = None
2078
1902
                else:
2079
1903
                    executable = statval.st_mode & S_IEXEC
2080
1904
            else:
2082
1906
                executable = None
2083
1907
            if kind == 'symlink':
2084
1908
                link_or_sha1 = os.readlink(limbo_name).decode(osutils._fs_enc)
2085
 
        executable = tt._new_executability.get(trans_id, executable)
 
1909
        if supports_executable():
 
1910
            executable = tt._new_executability.get(trans_id, executable)
2086
1911
        return kind, size, executable, link_or_sha1
2087
1912
 
2088
1913
    def iter_changes(self, from_tree, include_unchanged=False,
2119
1944
 
2120
1945
    def annotate_iter(self, file_id,
2121
1946
                      default_revision=_mod_revision.CURRENT_REVISION):
2122
 
        changes = self._iter_changes_cache.get(file_id)
 
1947
        changes = self._changes(file_id)
2123
1948
        if changes is None:
2124
1949
            get_old = True
2125
1950
        else:
2137
1962
            return old_annotation
2138
1963
        if not changed_content:
2139
1964
            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
1965
        return annotate.reannotate([old_annotation],
2148
1966
                                   self.get_file(file_id).readlines(),
2149
1967
                                   default_revision)
2215
2033
        self.transform = transform
2216
2034
 
2217
2035
    def _determine_path(self, trans_id):
2218
 
        if (trans_id == self.transform.root or trans_id == ROOT_PARENT):
 
2036
        if trans_id == self.transform.root:
2219
2037
            return ""
2220
2038
        name = self.transform.final_name(trans_id)
2221
2039
        parent_id = self.transform.final_parent(trans_id)
2291
2109
    for num, _unused in enumerate(wt.all_file_ids()):
2292
2110
        if num > 0:  # more than just a root
2293
2111
            raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
 
2112
    existing_files = set()
 
2113
    for dir, files in wt.walkdirs():
 
2114
        existing_files.update(f[0] for f in files)
2294
2115
    file_trans_id = {}
2295
2116
    top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2296
2117
    pp = ProgressPhase("Build phase", 2, top_pb)
2320
2141
                precomputed_delta = []
2321
2142
            else:
2322
2143
                precomputed_delta = None
2323
 
            # Check if tree inventory has content. If so, we populate
2324
 
            # existing_files with the directory content. If there are no
2325
 
            # entries we skip populating existing_files as its not used.
2326
 
            # This improves performance and unncessary work on large
2327
 
            # directory trees. (#501307)
2328
 
            if total > 0:
2329
 
                existing_files = set()
2330
 
                for dir, files in wt.walkdirs():
2331
 
                    existing_files.update(f[0] for f in files)
2332
2144
            for num, (tree_path, entry) in \
2333
2145
                enumerate(tree.inventory.iter_entries_by_dir()):
2334
2146
                pb.update("Building tree", num - len(deferred_contents), total)
2407
2219
        new_desired_files = desired_files
2408
2220
    else:
2409
2221
        iter = accelerator_tree.iter_changes(tree, include_unchanged=True)
2410
 
        unchanged = [(f, p[1]) for (f, p, c, v, d, n, k, e)
2411
 
                     in iter if not (c or e[0] != e[1])]
2412
 
        if accelerator_tree.supports_content_filtering():
2413
 
            unchanged = [(f, p) for (f, p) in unchanged
2414
 
                         if not accelerator_tree.iter_search_rules([p]).next()]
2415
 
        unchanged = dict(unchanged)
 
2222
        unchanged = dict((f, p[1]) for (f, p, c, v, d, n, k, e)
 
2223
                         in iter if not (c or e[0] != e[1]))
2416
2224
        new_desired_files = []
2417
2225
        count = 0
2418
2226
        for file_id, (trans_id, tree_path) in desired_files:
2466
2274
    if entry.kind == "directory":
2467
2275
        return True
2468
2276
    if entry.kind == "file":
2469
 
        f = file(target_path, 'rb')
2470
 
        try:
2471
 
            if tree.get_file_text(file_id) == f.read():
2472
 
                return True
2473
 
        finally:
2474
 
            f.close()
 
2277
        if tree.get_file(file_id).read() == file(target_path, 'rb').read():
 
2278
            return True
2475
2279
    elif entry.kind == "symlink":
2476
2280
        if tree.get_symlink_target(file_id) == os.readlink(target_path):
2477
2281
            return True
2545
2349
        tt.create_directory(trans_id)
2546
2350
 
2547
2351
 
2548
 
def create_from_tree(tt, trans_id, tree, file_id, bytes=None,
2549
 
    filter_tree_path=None):
2550
 
    """Create new file contents according to tree contents.
2551
 
    
2552
 
    :param filter_tree_path: the tree path to use to lookup
2553
 
      content filters to apply to the bytes output in the working tree.
2554
 
      This only applies if the working tree supports content filtering.
2555
 
    """
 
2352
def create_from_tree(tt, trans_id, tree, file_id, bytes=None):
 
2353
    """Create new file contents according to tree contents."""
2556
2354
    kind = tree.kind(file_id)
2557
2355
    if kind == 'directory':
2558
2356
        tt.create_directory(trans_id)
2563
2361
                bytes = tree_file.readlines()
2564
2362
            finally:
2565
2363
                tree_file.close()
2566
 
        wt = tt._tree
2567
 
        if wt.supports_content_filtering() and filter_tree_path is not None:
2568
 
            filters = wt._content_filter_stack(filter_tree_path)
2569
 
            bytes = filtered_output_bytes(bytes, filters,
2570
 
                ContentFilterContext(filter_tree_path, tree))
2571
2364
        tt.create_file(bytes, trans_id)
2572
2365
    elif kind == "symlink":
2573
2366
        tt.create_symlink(tree.get_symlink_target(file_id), trans_id)
2625
2418
 
2626
2419
 
2627
2420
def revert(working_tree, target_tree, filenames, backups=False,
2628
 
           pb=None, change_reporter=None):
 
2421
           pb=DummyProgress(), change_reporter=None):
2629
2422
    """Revert a working tree's contents to those of a target tree."""
2630
2423
    target_tree.lock_read()
2631
 
    pb = ui.ui_factory.nested_progress_bar()
2632
2424
    tt = TreeTransform(working_tree, pb)
2633
2425
    try:
2634
2426
        pp = ProgressPhase("Revert phase", 3, pb)
2653
2445
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
2654
2446
                              backups, pp, basis_tree=None,
2655
2447
                              merge_modified=None):
 
2448
    pp.next_phase()
2656
2449
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2657
2450
    try:
2658
2451
        if merge_modified is None:
2662
2455
                                      merge_modified, basis_tree)
2663
2456
    finally:
2664
2457
        child_pb.finished()
 
2458
    pp.next_phase()
2665
2459
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2666
2460
    try:
2667
2461
        raw_conflicts = resolve_conflicts(tt, child_pb,
2760
2554
                    parent_trans = ROOT_PARENT
2761
2555
                else:
2762
2556
                    parent_trans = tt.trans_id_file_id(parent[1])
2763
 
                if parent[0] is None and versioned[0]:
2764
 
                    tt.adjust_root_path(name[1], parent_trans)
2765
 
                else:
2766
 
                    tt.adjust_path(name[1], parent_trans, trans_id)
 
2557
                tt.adjust_path(name[1], parent_trans, trans_id)
2767
2558
            if executable[0] != executable[1] and kind[1] == "file":
2768
2559
                tt.set_executability(executable[1], trans_id)
2769
 
        if working_tree.supports_content_filtering():
2770
 
            for index, ((trans_id, mode_id), bytes) in enumerate(
2771
 
                target_tree.iter_files_bytes(deferred_files)):
2772
 
                file_id = deferred_files[index][0]
2773
 
                # We're reverting a tree to the target tree so using the
2774
 
                # target tree to find the file path seems the best choice
2775
 
                # here IMO - Ian C 27/Oct/2009
2776
 
                filter_tree_path = target_tree.id2path(file_id)
2777
 
                filters = working_tree._content_filter_stack(filter_tree_path)
2778
 
                bytes = filtered_output_bytes(bytes, filters,
2779
 
                    ContentFilterContext(filter_tree_path, working_tree))
2780
 
                tt.create_file(bytes, trans_id, mode_id)
2781
 
        else:
2782
 
            for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
2783
 
                deferred_files):
2784
 
                tt.create_file(bytes, trans_id, mode_id)
2785
 
        tt.fixup_new_roots()
 
2560
        for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
 
2561
            deferred_files):
 
2562
            tt.create_file(bytes, trans_id, mode_id)
2786
2563
    finally:
2787
2564
        if basis_tree is not None:
2788
2565
            basis_tree.unlock()
2789
2566
    return merge_modified
2790
2567
 
2791
2568
 
2792
 
def resolve_conflicts(tt, pb=None, pass_func=None):
 
2569
def resolve_conflicts(tt, pb=DummyProgress(), pass_func=None):
2793
2570
    """Make many conflict-resolution attempts, but die if they fail"""
2794
2571
    if pass_func is None:
2795
2572
        pass_func = conflict_pass
2796
2573
    new_conflicts = set()
2797
 
    pb = ui.ui_factory.nested_progress_bar()
2798
2574
    try:
2799
2575
        for n in range(10):
2800
2576
            pb.update('Resolution pass', n+1, 10)
2804
2580
            new_conflicts.update(pass_func(tt, conflicts))
2805
2581
        raise MalformedTransform(conflicts=conflicts)
2806
2582
    finally:
2807
 
        pb.finished()
 
2583
        pb.clear()
2808
2584
 
2809
2585
 
2810
2586
def conflict_pass(tt, conflicts, path_tree=None):
2859
2635
                        # special-case the other tree root (move its
2860
2636
                        # children to current root)
2861
2637
                        if entry.parent_id is None:
2862
 
                            create = False
 
2638
                            create=False
2863
2639
                            moved = _reparent_transform_children(
2864
2640
                                tt, trans_id, tt.root)
2865
2641
                            for child in moved:
2933
2709
        self.pending_deletions = []
2934
2710
 
2935
2711
    def rename(self, from_, to):
2936
 
        """Rename a file from one path to another."""
 
2712
        """Rename a file from one path to another.  Functions like os.rename"""
2937
2713
        try:
2938
2714
            os.rename(from_, to)
2939
2715
        except OSError, e:
2940
2716
            if e.errno in (errno.EEXIST, errno.ENOTEMPTY):
2941
2717
                raise errors.FileExists(to, str(e))
2942
 
            # normal OSError doesn't include filenames so it's hard to see where
2943
 
            # the problem is, see https://bugs.launchpad.net/bzr/+bug/491763
2944
 
            raise errors.TransformRenameFailed(from_, to, str(e), e.errno)
 
2718
            raise
2945
2719
        self.past_renames.append((from_, to))
2946
2720
 
2947
2721
    def pre_delete(self, from_, to):
2957
2731
    def rollback(self):
2958
2732
        """Reverse all renames that have been performed"""
2959
2733
        for from_, to in reversed(self.past_renames):
2960
 
            try:
2961
 
                os.rename(to, from_)
2962
 
            except OSError, e:
2963
 
                raise errors.TransformRenameFailed(to, from_, str(e), e.errno)                
 
2734
            os.rename(to, from_)
2964
2735
        # after rollback, don't reuse _FileMover
2965
2736
        past_renames = None
2966
2737
        pending_deletions = None