/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4454.3.60 by John Arbash Meinel
Update copyright
1
# Copyright (C) 2006, 2007, 2008, 2009 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
16
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
17
import os
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
18
import errno
3363.2.27 by Aaron Bentley
Make path_content_summary a core API
19
from stat import S_ISREG, S_IEXEC
4934.1.1 by John Arbash Meinel
Basic implementation for windows and bug #488724.
20
import time
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
21
1551.11.12 by Aaron Bentley
Changes from review
22
from bzrlib.lazy_import import lazy_import
23
lazy_import(globals(), """
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
24
from bzrlib import (
3363.2.33 by Aaron Bentley
Implement PreviewTree.annotate_iter
25
    annotate,
2694.5.4 by Jelmer Vernooij
Move bzrlib.util.bencode to bzrlib._bencode_py.
26
    bencode,
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
27
    bzrdir,
2100.3.31 by Aaron Bentley
Merged bzr.dev (17 tests failing)
28
    delta,
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
29
    errors,
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
30
    inventory,
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
31
    multiparent,
3596.2.6 by John Arbash Meinel
Turns out that osutils wasn't imported directly into transform
32
    osutils,
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
33
    revision as _mod_revision,
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
34
    )
1551.11.12 by Aaron Bentley
Changes from review
35
""")
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
36
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
1534.7.162 by Aaron Bentley
Handle failures creating/deleting the Limbo directory
37
                           ReusingTransform, NotVersionedError, CantMoveRoot,
3006.2.1 by Alexander Belchenko
workaround for bug #81689: give a proper error message instead of traceback when symlink cannot be created (e.g. on Windows)
38
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
39
                           UnableCreateSymlink)
3368.2.19 by Ian Clatworthy
first round of changes from abentley's review
40
from bzrlib.filters import filtered_output_bytes, ContentFilterContext
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
41
from bzrlib.inventory import InventoryEntry
3363.2.19 by Aaron Bentley
Make PreviewTree.path2id correct
42
from bzrlib.osutils import (
43
    delete_any,
44
    file_kind,
45
    has_symlinks,
46
    lexists,
47
    pathjoin,
3363.15.4 by Aaron Bentley
Implement PreviewTree.get_file_sha1 properly
48
    sha_file,
3363.2.19 by Aaron Bentley
Make PreviewTree.path2id correct
49
    splitpath,
50
    supports_executable,
51
)
1551.2.34 by Aaron Bentley
Refactored the revert phases
52
from bzrlib.progress import DummyProgress, ProgressPhase
2687.2.1 by Martin Pool
Rename upcoming release from 0.19 to 0.90
53
from bzrlib.symbol_versioning import (
54
        deprecated_function,
3363.17.26 by Aaron Bentley
Deprecate create_by_entry
55
        deprecated_in,
2687.2.1 by Martin Pool
Rename upcoming release from 0.19 to 0.90
56
        )
1534.7.173 by Aaron Bentley
Added conflict warnings to revert
57
from bzrlib.trace import mutter, warning
1551.7.14 by Aaron Bentley
Use specified_file_ids instead of is_inside_any in compare_trees
58
from bzrlib import tree
2255.2.152 by Martin Pool
(broken) merge aaron's workingtree format changes
59
import bzrlib.ui
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
60
import bzrlib.urlutils as urlutils
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
61
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
62
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
63
ROOT_PARENT = "root-parent"
64
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
65
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
66
def unique_add(map, key, value):
67
    if key in map:
1534.7.5 by Aaron Bentley
Got unique_add under test
68
        raise DuplicateKey(key=key)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
69
    map[key] = value
70
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
71
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
72
class _TransformResults(object):
2502.1.5 by Aaron Bentley
Cleanup
73
    def __init__(self, modified_paths, rename_count):
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
74
        object.__init__(self)
75
        self.modified_paths = modified_paths
2502.1.5 by Aaron Bentley
Cleanup
76
        self.rename_count = rename_count
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
77
78
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
79
class TreeTransformBase(object):
4354.5.4 by Aaron Bentley
Update docs
80
    """The base class for TreeTransform and its kin."""
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
81
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
82
    def __init__(self, tree, pb=DummyProgress(),
3008.1.15 by Aaron Bentley
Make case_sensitive an aspect of the transform, not the source tree
83
                 case_sensitive=True):
3008.1.29 by Aaron Bentley
Add docstrings, rename TT.__doc
84
        """Constructor.
85
86
        :param tree: The tree that will be transformed, but not necessarily
87
            the output tree.
4463.1.1 by Martin Pool
Update docstrings for recent progress changes
88
        :param pb: A ProgressTask indicating how much progress is being made
3008.1.29 by Aaron Bentley
Add docstrings, rename TT.__doc
89
        :param case_sensitive: If True, the target of the transform is
90
            case sensitive, not just case preserving.
91
        """
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
92
        object.__init__(self)
93
        self._tree = tree
94
        self._id_number = 0
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
95
        # mapping of trans_id -> new basename
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
96
        self._new_name = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
97
        # mapping of trans_id -> new parent trans_id
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
98
        self._new_parent = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
99
        # mapping of trans_id with new contents -> new file_kind
1534.7.4 by Aaron Bentley
Unified all file types as 'contents'
100
        self._new_contents = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
101
        # Set of trans_ids whose contents will be removed
1534.7.34 by Aaron Bentley
Proper conflicts for removals
102
        self._removed_contents = set()
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
103
        # Mapping of trans_id -> new execute-bit value
1534.7.25 by Aaron Bentley
Added set_executability
104
        self._new_executability = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
105
        # Mapping of trans_id -> new tree-reference value
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
106
        self._new_reference_revision = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
107
        # Mapping of trans_id -> new file_id
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
108
        self._new_id = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
109
        # Mapping of old file-id -> trans_id
1534.7.143 by Aaron Bentley
Prevented get_trans_id from automatically versioning file ids
110
        self._non_present_ids = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
111
        # Mapping of new file_id -> trans_id
1534.7.75 by Aaron Bentley
Added reverse-lookup for versioned files and get_trans_id
112
        self._r_new_id = {}
3981.1.1 by Robert Collins
Fix bug 319790 - unshelve of deleted paths failing.
113
        # Set of trans_ids that will be removed
1534.7.39 by Aaron Bentley
Ensured that files can be unversioned (de-versioned?)
114
        self._removed_id = set()
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
115
        # Mapping of path in old tree -> trans_id
1534.7.7 by Aaron Bentley
Added support for all-file path ids
116
        self._tree_path_ids = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
117
        # Mapping trans_id -> path in old tree
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
118
        self._tree_id_paths = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
119
        # The trans_id that will be used as the tree root
3363.2.16 by Aaron Bentley
Fix root directory creation
120
        root_id = tree.get_root_id()
121
        if root_id is not None:
122
            self._new_root = self.trans_id_tree_file_id(root_id)
123
        else:
124
            self._new_root = None
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
125
        # Indictor of whether the transform has been applied
3008.1.29 by Aaron Bentley
Add docstrings, rename TT.__doc
126
        self._done = False
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
127
        # A progress bar
1534.9.1 by Aaron Bentley
Added progress bars to merge
128
        self._pb = pb
3008.1.15 by Aaron Bentley
Make case_sensitive an aspect of the transform, not the source tree
129
        # Whether the target is case sensitive
130
        self._case_sensitive_target = case_sensitive
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
131
        # A counter of how many files have been renamed
2502.1.1 by Aaron Bentley
Ensure renames only root children are renamed when building trees
132
        self.rename_count = 0
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
133
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
134
    def finalize(self):
135
        """Release the working tree lock, if held.
136
137
        This is required if apply has not been invoked, but can be invoked
138
        even after apply.
139
        """
140
        if self._tree is None:
141
            return
142
        self._tree.unlock()
143
        self._tree = None
144
1534.7.132 by Aaron Bentley
Got cooked conflicts working
145
    def __get_root(self):
146
        return self._new_root
147
148
    root = property(__get_root)
149
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
150
    def _assign_id(self):
151
        """Produce a new tranform id"""
152
        new_id = "new-%s" % self._id_number
153
        self._id_number +=1
154
        return new_id
155
156
    def create_path(self, name, parent):
157
        """Assign a transaction id to a new path"""
158
        trans_id = self._assign_id()
159
        unique_add(self._new_name, trans_id, name)
160
        unique_add(self._new_parent, trans_id, parent)
161
        return trans_id
162
1534.7.6 by Aaron Bentley
Added conflict handling
163
    def adjust_path(self, name, parent, trans_id):
1534.7.21 by Aaron Bentley
Updated docstrings
164
        """Change the path that is assigned to a transaction id."""
1534.7.66 by Aaron Bentley
Ensured we don't accidentally move the root directory
165
        if trans_id == self._new_root:
166
            raise CantMoveRoot
1534.7.6 by Aaron Bentley
Added conflict handling
167
        self._new_name[trans_id] = name
168
        self._new_parent[trans_id] = parent
3363.10.1 by Aaron Bentley
Fixes for adjust_path and path2id
169
        if parent == ROOT_PARENT:
170
            if self._new_root is not None:
171
                raise ValueError("Cannot have multiple roots.")
172
            self._new_root = trans_id
1534.7.6 by Aaron Bentley
Added conflict handling
173
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
174
    def adjust_root_path(self, name, parent):
175
        """Emulate moving the root by moving all children, instead.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
176
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
177
        We do this by undoing the association of root's transaction id with the
178
        current tree.  This allows us to create a new directory with that
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
179
        transaction id.  We unversion the root directory and version the
1534.7.69 by Aaron Bentley
Got real root moves working
180
        physically new directory, and hope someone versions the tree root
181
        later.
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
182
        """
183
        old_root = self._new_root
184
        old_root_file_id = self.final_file_id(old_root)
185
        # force moving all children of root
186
        for child_id in self.iter_tree_children(old_root):
187
            if child_id != parent:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
188
                self.adjust_path(self.final_name(child_id),
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
189
                                 self.final_parent(child_id), child_id)
1534.7.69 by Aaron Bentley
Got real root moves working
190
            file_id = self.final_file_id(child_id)
191
            if file_id is not None:
192
                self.unversion_file(child_id)
193
            self.version_file(file_id, child_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
194
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
195
        # the physical root needs a new transaction id
196
        self._tree_path_ids.pop("")
197
        self._tree_id_paths.pop(old_root)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
198
        self._new_root = self.trans_id_tree_file_id(self._tree.get_root_id())
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
199
        if parent == old_root:
200
            parent = self._new_root
201
        self.adjust_path(name, parent, old_root)
202
        self.create_directory(old_root)
1534.7.69 by Aaron Bentley
Got real root moves working
203
        self.version_file(old_root_file_id, old_root)
204
        self.unversion_file(self._new_root)
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
205
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
206
    def trans_id_tree_file_id(self, inventory_id):
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
207
        """Determine the transaction id of a working tree file.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
208
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
209
        This reflects only files that already exist, not ones that will be
210
        added by transactions.
211
        """
3363.2.16 by Aaron Bentley
Fix root directory creation
212
        if inventory_id is None:
213
            raise ValueError('None is not a valid file id')
3146.8.1 by Aaron Bentley
Fix two tree.inventory uses in checkout
214
        path = self._tree.id2path(inventory_id)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
215
        return self.trans_id_tree_path(path)
1534.7.7 by Aaron Bentley
Added support for all-file path ids
216
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
217
    def trans_id_file_id(self, file_id):
1534.7.156 by Aaron Bentley
PEP8 fixes
218
        """Determine or set the transaction id associated with a file ID.
1534.7.75 by Aaron Bentley
Added reverse-lookup for versioned files and get_trans_id
219
        A new id is only created for file_ids that were never present.  If
220
        a transaction has been unversioned, it is deliberately still returned.
221
        (this will likely lead to an unversioned parent conflict.)
222
        """
3363.2.16 by Aaron Bentley
Fix root directory creation
223
        if file_id is None:
224
            raise ValueError('None is not a valid file id')
1534.7.75 by Aaron Bentley
Added reverse-lookup for versioned files and get_trans_id
225
        if file_id in self._r_new_id and self._r_new_id[file_id] is not None:
226
            return self._r_new_id[file_id]
227
        else:
3363.17.1 by Aaron Bentley
Avoid inventory for merge and transform code
228
            try:
229
                self._tree.iter_entries_by_dir([file_id]).next()
230
            except StopIteration:
231
                if file_id in self._non_present_ids:
232
                    return self._non_present_ids[file_id]
233
                else:
234
                    trans_id = self._assign_id()
235
                    self._non_present_ids[file_id] = trans_id
236
                    return trans_id
237
            else:
238
                return self.trans_id_tree_file_id(file_id)
1534.7.75 by Aaron Bentley
Added reverse-lookup for versioned files and get_trans_id
239
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
240
    def trans_id_tree_path(self, path):
1534.7.7 by Aaron Bentley
Added support for all-file path ids
241
        """Determine (and maybe set) the transaction ID for a tree path."""
1534.7.12 by Aaron Bentley
Added canonical_path function
242
        path = self.canonical_path(path)
1534.7.7 by Aaron Bentley
Added support for all-file path ids
243
        if path not in self._tree_path_ids:
244
            self._tree_path_ids[path] = self._assign_id()
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
245
            self._tree_id_paths[self._tree_path_ids[path]] = path
1534.7.7 by Aaron Bentley
Added support for all-file path ids
246
        return self._tree_path_ids[path]
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
247
1534.7.16 by Aaron Bentley
Added get_tree_parent
248
    def get_tree_parent(self, trans_id):
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
249
        """Determine id of the parent in the tree."""
1534.7.16 by Aaron Bentley
Added get_tree_parent
250
        path = self._tree_id_paths[trans_id]
251
        if path == "":
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
252
            return ROOT_PARENT
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
253
        return self.trans_id_tree_path(os.path.dirname(path))
1534.7.16 by Aaron Bentley
Added get_tree_parent
254
1534.7.34 by Aaron Bentley
Proper conflicts for removals
255
    def delete_contents(self, trans_id):
256
        """Schedule the contents of a path entry for deletion"""
1534.7.130 by Aaron Bentley
More conflict handling, test porting
257
        self.tree_kind(trans_id)
1534.7.34 by Aaron Bentley
Proper conflicts for removals
258
        self._removed_contents.add(trans_id)
259
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
260
    def cancel_deletion(self, trans_id):
261
        """Cancel a scheduled deletion"""
262
        self._removed_contents.remove(trans_id)
263
1534.7.39 by Aaron Bentley
Ensured that files can be unversioned (de-versioned?)
264
    def unversion_file(self, trans_id):
265
        """Schedule a path entry to become unversioned"""
266
        self._removed_id.add(trans_id)
267
268
    def delete_versioned(self, trans_id):
269
        """Delete and unversion a versioned file"""
270
        self.delete_contents(trans_id)
271
        self.unversion_file(trans_id)
272
1534.7.25 by Aaron Bentley
Added set_executability
273
    def set_executability(self, executability, trans_id):
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
274
        """Schedule setting of the 'execute' bit
275
        To unschedule, set to None
276
        """
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
277
        if executability is None:
278
            del self._new_executability[trans_id]
279
        else:
280
            unique_add(self._new_executability, trans_id, executability)
1534.7.25 by Aaron Bentley
Added set_executability
281
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
282
    def set_tree_reference(self, revision_id, trans_id):
283
        """Set the reference associated with a directory"""
284
        unique_add(self._new_reference_revision, trans_id, revision_id)
285
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
286
    def version_file(self, file_id, trans_id):
1534.7.21 by Aaron Bentley
Updated docstrings
287
        """Schedule a file to become versioned."""
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
288
        if file_id is None:
289
            raise ValueError()
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
290
        unique_add(self._new_id, trans_id, file_id)
1534.7.75 by Aaron Bentley
Added reverse-lookup for versioned files and get_trans_id
291
        unique_add(self._r_new_id, file_id, trans_id)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
292
1534.7.105 by Aaron Bentley
Got merge with rename working
293
    def cancel_versioning(self, trans_id):
294
        """Undo a previous versioning of a file"""
295
        file_id = self._new_id[trans_id]
296
        del self._new_id[trans_id]
297
        del self._r_new_id[file_id]
298
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
299
    def new_paths(self, filesystem_only=False):
300
        """Determine the paths of all new and changed files.
301
3453.2.11 by Aaron Bentley
Updates from review
302
        :param filesystem_only: if True, only calculate values for files
303
            that require renames or execute bit changes.
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
304
        """
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
305
        new_ids = set()
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
306
        if filesystem_only:
3619.2.11 by Aaron Bentley
Tweak new_paths logic
307
            stale_ids = self._needs_rename.difference(self._new_name)
308
            stale_ids.difference_update(self._new_parent)
309
            stale_ids.difference_update(self._new_contents)
310
            stale_ids.difference_update(self._new_id)
311
            needs_rename = self._needs_rename.difference(stale_ids)
3619.2.10 by Aaron Bentley
Compensate for stale entries in TT._needs_rename
312
            id_sets = (needs_rename, self._new_executability)
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
313
        else:
314
            id_sets = (self._new_name, self._new_parent, self._new_contents,
315
                       self._new_id, self._new_executability)
316
        for id_set in id_sets:
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
317
            new_ids.update(id_set)
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
318
        return sorted(FinalPaths(self).get_paths(new_ids))
1534.7.6 by Aaron Bentley
Added conflict handling
319
3619.2.6 by Aaron Bentley
More tweaking
320
    def _inventory_altered(self):
321
        """Get the trans_ids and paths of files needing new inv entries."""
3619.2.5 by Aaron Bentley
Reduce set tests
322
        new_ids = set()
3619.2.6 by Aaron Bentley
More tweaking
323
        for id_set in [self._new_name, self._new_parent, self._new_id,
324
                       self._new_executability]:
3619.2.5 by Aaron Bentley
Reduce set tests
325
            new_ids.update(id_set)
326
        changed_kind = set(self._removed_contents)
327
        changed_kind.intersection_update(self._new_contents)
328
        changed_kind.difference_update(new_ids)
329
        changed_kind = (t for t in changed_kind if self.tree_kind(t) !=
330
                        self.final_kind(t))
331
        new_ids.update(changed_kind)
332
        return sorted(FinalPaths(self).get_paths(new_ids))
333
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
334
    def final_kind(self, trans_id):
1534.7.156 by Aaron Bentley
PEP8 fixes
335
        """Determine the final file kind, after any changes applied.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
336
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
337
        Raises NoSuchFile if the file does not exist/has no contents.
338
        (It is conceivable that a path would be created without the
339
        corresponding contents insertion command)
340
        """
341
        if trans_id in self._new_contents:
1534.7.73 by Aaron Bentley
Changed model again. Now iterator is used immediately.
342
            return self._new_contents[trans_id]
1534.7.34 by Aaron Bentley
Proper conflicts for removals
343
        elif trans_id in self._removed_contents:
344
            raise NoSuchFile(None)
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
345
        else:
1534.7.34 by Aaron Bentley
Proper conflicts for removals
346
            return self.tree_kind(trans_id)
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
347
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
348
    def tree_file_id(self, trans_id):
1534.7.41 by Aaron Bentley
Got inventory ID movement working
349
        """Determine the file id associated with the trans_id in the tree"""
350
        try:
351
            path = self._tree_id_paths[trans_id]
352
        except KeyError:
353
            # the file is a new, unversioned file, or invalid trans_id
354
            return None
355
        # the file is old; the old id is still valid
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
356
        if self._new_root == trans_id:
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
357
            return self._tree.get_root_id()
3363.17.5 by Aaron Bentley
Update merge to not use inventory
358
        return self._tree.path2id(path)
1534.7.41 by Aaron Bentley
Got inventory ID movement working
359
1534.7.13 by Aaron Bentley
Implemented final_file_id
360
    def final_file_id(self, trans_id):
1534.7.156 by Aaron Bentley
PEP8 fixes
361
        """Determine the file id after any changes are applied, or None.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
362
1534.7.21 by Aaron Bentley
Updated docstrings
363
        None indicates that the file will not be versioned after changes are
364
        applied.
365
        """
1534.7.13 by Aaron Bentley
Implemented final_file_id
366
        try:
367
            return self._new_id[trans_id]
368
        except KeyError:
1534.7.39 by Aaron Bentley
Ensured that files can be unversioned (de-versioned?)
369
            if trans_id in self._removed_id:
370
                return None
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
371
        return self.tree_file_id(trans_id)
1534.7.13 by Aaron Bentley
Implemented final_file_id
372
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
373
    def inactive_file_id(self, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
374
        """Return the inactive file_id associated with a transaction id.
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
375
        That is, the one in the tree or in non_present_ids.
376
        The file_id may actually be active, too.
377
        """
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
378
        file_id = self.tree_file_id(trans_id)
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
379
        if file_id is not None:
380
            return file_id
381
        for key, value in self._non_present_ids.iteritems():
382
            if value == trans_id:
383
                return key
384
1534.7.17 by Aaron Bentley
Added final_parent function
385
    def final_parent(self, trans_id):
1534.7.156 by Aaron Bentley
PEP8 fixes
386
        """Determine the parent file_id, after any changes are applied.
1534.7.21 by Aaron Bentley
Updated docstrings
387
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
388
        ROOT_PARENT is returned for the tree root.
1534.7.21 by Aaron Bentley
Updated docstrings
389
        """
1534.7.17 by Aaron Bentley
Added final_parent function
390
        try:
391
            return self._new_parent[trans_id]
392
        except KeyError:
393
            return self.get_tree_parent(trans_id)
394
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
395
    def final_name(self, trans_id):
1534.7.40 by Aaron Bentley
Updated docs
396
        """Determine the final filename, after all changes are applied."""
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
397
        try:
398
            return self._new_name[trans_id]
399
        except KeyError:
1731.1.33 by Aaron Bentley
Revert no-special-root changes
400
            try:
401
                return os.path.basename(self._tree_id_paths[trans_id])
402
            except KeyError:
403
                raise NoFinalPath(trans_id, self)
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
404
1534.10.28 by Aaron Bentley
Use numbered backup files
405
    def by_parent(self):
1534.7.40 by Aaron Bentley
Updated docs
406
        """Return a map of parent: children for known parents.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
407
1534.7.40 by Aaron Bentley
Updated docs
408
        Only new paths and parents of tree files with assigned ids are used.
409
        """
1534.7.6 by Aaron Bentley
Added conflict handling
410
        by_parent = {}
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
411
        items = list(self._new_parent.iteritems())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
412
        items.extend((t, self.final_parent(t)) for t in
1534.7.76 by Aaron Bentley
Fixed final_parent, for the case where finding a parent adds tree id paths.
413
                      self._tree_id_paths.keys())
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
414
        for trans_id, parent_id in items:
1534.7.6 by Aaron Bentley
Added conflict handling
415
            if parent_id not in by_parent:
416
                by_parent[parent_id] = set()
417
            by_parent[parent_id].add(trans_id)
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
418
        return by_parent
1534.7.11 by Aaron Bentley
Refactored conflict handling
419
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
420
    def path_changed(self, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
421
        """Return True if a trans_id's path has changed."""
1711.9.11 by John Arbash Meinel
change return foo in bar to return (foo in bar)
422
        return (trans_id in self._new_name) or (trans_id in self._new_parent)
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
423
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
424
    def new_contents(self, trans_id):
425
        return (trans_id in self._new_contents)
426
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
427
    def find_conflicts(self):
1534.7.40 by Aaron Bentley
Updated docs
428
        """Find any violations of inventory or filesystem invariants"""
3008.1.29 by Aaron Bentley
Add docstrings, rename TT.__doc
429
        if self._done is True:
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
430
            raise ReusingTransform()
431
        conflicts = []
432
        # ensure all children of all existent parents are known
433
        # all children of non-existent parents are known, by definition.
434
        self._add_tree_children()
1534.10.28 by Aaron Bentley
Use numbered backup files
435
        by_parent = self.by_parent()
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
436
        conflicts.extend(self._unversioned_parents(by_parent))
1534.7.19 by Aaron Bentley
Added tests for parent loops
437
        conflicts.extend(self._parent_loops())
1534.7.11 by Aaron Bentley
Refactored conflict handling
438
        conflicts.extend(self._duplicate_entries(by_parent))
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
439
        conflicts.extend(self._duplicate_ids())
1534.7.11 by Aaron Bentley
Refactored conflict handling
440
        conflicts.extend(self._parent_type_conflicts(by_parent))
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
441
        conflicts.extend(self._improper_versioning())
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
442
        conflicts.extend(self._executability_conflicts())
1534.7.152 by Aaron Bentley
Fixed overwrites
443
        conflicts.extend(self._overwrite_conflicts())
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
444
        return conflicts
445
4526.8.6 by Aaron Bentley
Check for malformed transforms before committing.
446
    def _check_malformed(self):
447
        conflicts = self.find_conflicts()
448
        if len(conflicts) != 0:
449
            raise MalformedTransform(conflicts=conflicts)
450
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
451
    def _add_tree_children(self):
1534.7.156 by Aaron Bentley
PEP8 fixes
452
        """Add all the children of all active parents to the known paths.
1534.7.40 by Aaron Bentley
Updated docs
453
454
        Active parents are those which gain children, and those which are
455
        removed.  This is a necessary first step in detecting conflicts.
456
        """
1534.10.28 by Aaron Bentley
Use numbered backup files
457
        parents = self.by_parent().keys()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
458
        parents.extend([t for t in self._removed_contents if
1534.7.34 by Aaron Bentley
Proper conflicts for removals
459
                        self.tree_kind(t) == 'directory'])
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
460
        for trans_id in self._removed_id:
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
461
            file_id = self.tree_file_id(trans_id)
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
462
            if file_id is not None:
463
                if self._tree.inventory[file_id].kind == 'directory':
464
                    parents.append(trans_id)
465
            elif self.tree_kind(trans_id) == 'directory':
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
466
                parents.append(trans_id)
467
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
468
        for parent_id in parents:
1534.7.67 by Aaron Bentley
Refactored _add_tree_children
469
            # ensure that all children are registered with the transaction
470
            list(self.iter_tree_children(parent_id))
471
1534.10.28 by Aaron Bentley
Use numbered backup files
472
    def has_named_child(self, by_parent, parent_id, name):
473
        try:
474
            children = by_parent[parent_id]
475
        except KeyError:
476
            children = []
477
        for child in children:
478
            if self.final_name(child) == name:
479
                return True
480
        try:
481
            path = self._tree_id_paths[parent_id]
482
        except KeyError:
483
            return False
484
        childpath = joinpath(path, name)
485
        child_id = self._tree_path_ids.get(childpath)
486
        if child_id is None:
487
            return lexists(self._tree.abspath(childpath))
488
        else:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
489
            if self.final_parent(child_id) != parent_id:
1534.10.28 by Aaron Bentley
Use numbered backup files
490
                return False
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
491
            if child_id in self._removed_contents:
1534.10.28 by Aaron Bentley
Use numbered backup files
492
                # XXX What about dangling file-ids?
493
                return False
494
            else:
495
                return True
496
1534.7.19 by Aaron Bentley
Added tests for parent loops
497
    def _parent_loops(self):
498
        """No entry should be its own ancestor"""
499
        conflicts = []
500
        for trans_id in self._new_parent:
501
            seen = set()
502
            parent_id = trans_id
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
503
            while parent_id is not ROOT_PARENT:
1534.7.19 by Aaron Bentley
Added tests for parent loops
504
                seen.add(parent_id)
1731.1.33 by Aaron Bentley
Revert no-special-root changes
505
                try:
506
                    parent_id = self.final_parent(parent_id)
507
                except KeyError:
508
                    break
1534.7.19 by Aaron Bentley
Added tests for parent loops
509
                if parent_id == trans_id:
510
                    conflicts.append(('parent loop', trans_id))
511
                if parent_id in seen:
512
                    break
513
        return conflicts
514
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
515
    def _unversioned_parents(self, by_parent):
516
        """If parent directories are versioned, children must be versioned."""
517
        conflicts = []
518
        for parent_id, children in by_parent.iteritems():
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
519
            if parent_id is ROOT_PARENT:
520
                continue
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
521
            if self.final_file_id(parent_id) is not None:
522
                continue
523
            for child_id in children:
524
                if self.final_file_id(child_id) is not None:
525
                    conflicts.append(('unversioned parent', parent_id))
526
                    break;
527
        return conflicts
528
529
    def _improper_versioning(self):
1534.7.156 by Aaron Bentley
PEP8 fixes
530
        """Cannot version a file with no contents, or a bad type.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
531
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
532
        However, existing entries with no contents are okay.
533
        """
534
        conflicts = []
535
        for trans_id in self._new_id.iterkeys():
536
            try:
537
                kind = self.final_kind(trans_id)
538
            except NoSuchFile:
539
                conflicts.append(('versioning no contents', trans_id))
540
                continue
541
            if not InventoryEntry.versionable_kind(kind):
1534.7.20 by Aaron Bentley
Added directory handling
542
                conflicts.append(('versioning bad kind', trans_id, kind))
1534.7.11 by Aaron Bentley
Refactored conflict handling
543
        return conflicts
544
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
545
    def _executability_conflicts(self):
1534.7.40 by Aaron Bentley
Updated docs
546
        """Check for bad executability changes.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
547
1534.7.40 by Aaron Bentley
Updated docs
548
        Only versioned files may have their executability set, because
549
        1. only versioned entries can have executability under windows
550
        2. only files can be executable.  (The execute bit on a directory
551
           does not indicate searchability)
552
        """
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
553
        conflicts = []
554
        for trans_id in self._new_executability:
555
            if self.final_file_id(trans_id) is None:
556
                conflicts.append(('unversioned executability', trans_id))
1534.7.34 by Aaron Bentley
Proper conflicts for removals
557
            else:
558
                try:
559
                    non_file = self.final_kind(trans_id) != "file"
560
                except NoSuchFile:
561
                    non_file = True
562
                if non_file is True:
563
                    conflicts.append(('non-file executability', trans_id))
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
564
        return conflicts
565
1534.7.152 by Aaron Bentley
Fixed overwrites
566
    def _overwrite_conflicts(self):
567
        """Check for overwrites (not permitted on Win32)"""
568
        conflicts = []
569
        for trans_id in self._new_contents:
570
            try:
571
                self.tree_kind(trans_id)
572
            except NoSuchFile:
573
                continue
574
            if trans_id not in self._removed_contents:
575
                conflicts.append(('overwrite', trans_id,
576
                                 self.final_name(trans_id)))
577
        return conflicts
578
1534.7.11 by Aaron Bentley
Refactored conflict handling
579
    def _duplicate_entries(self, by_parent):
580
        """No directory may have two entries with the same name."""
581
        conflicts = []
2590.2.16 by Aaron Bentley
Shortcut duplicate_entries conflict check if no new names introduced
582
        if (self._new_name, self._new_parent) == ({}, {}):
583
            return conflicts
1534.7.6 by Aaron Bentley
Added conflict handling
584
        for children in by_parent.itervalues():
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
585
            name_ids = [(self.final_name(t), t) for t in children]
3008.1.15 by Aaron Bentley
Make case_sensitive an aspect of the transform, not the source tree
586
            if not self._case_sensitive_target:
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
587
                name_ids = [(n.lower(), t) for n, t in name_ids]
1534.7.6 by Aaron Bentley
Added conflict handling
588
            name_ids.sort()
589
            last_name = None
590
            last_trans_id = None
591
            for name, trans_id in name_ids:
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
592
                try:
593
                    kind = self.final_kind(trans_id)
594
                except NoSuchFile:
595
                    kind = None
596
                file_id = self.final_file_id(trans_id)
597
                if kind is None and file_id is None:
598
                    continue
1534.7.6 by Aaron Bentley
Added conflict handling
599
                if name == last_name:
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
600
                    conflicts.append(('duplicate', last_trans_id, trans_id,
601
                    name))
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
602
                last_name = name
603
                last_trans_id = trans_id
1534.7.11 by Aaron Bentley
Refactored conflict handling
604
        return conflicts
605
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
606
    def _duplicate_ids(self):
607
        """Each inventory id may only be used once"""
608
        conflicts = []
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
609
        removed_tree_ids = set((self.tree_file_id(trans_id) for trans_id in
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
610
                                self._removed_id))
3146.8.16 by Aaron Bentley
Updates from review
611
        all_ids = self._tree.all_file_ids()
612
        active_tree_ids = all_ids.difference(removed_tree_ids)
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
613
        for trans_id, file_id in self._new_id.iteritems():
614
            if file_id in active_tree_ids:
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
615
                old_trans_id = self.trans_id_tree_file_id(file_id)
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
616
                conflicts.append(('duplicate id', old_trans_id, trans_id))
617
        return conflicts
618
1534.7.11 by Aaron Bentley
Refactored conflict handling
619
    def _parent_type_conflicts(self, by_parent):
620
        """parents must have directory 'contents'."""
621
        conflicts = []
1534.7.37 by Aaron Bentley
Allowed removed dirs to have content-free children.
622
        for parent_id, children in by_parent.iteritems():
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
623
            if parent_id is ROOT_PARENT:
624
                continue
1534.7.37 by Aaron Bentley
Allowed removed dirs to have content-free children.
625
            if not self._any_contents(children):
626
                continue
627
            for child in children:
628
                try:
629
                    self.final_kind(child)
630
                except NoSuchFile:
631
                    continue
1534.7.10 by Aaron Bentley
Implemented missing parent and non-directory parent conflicts
632
            try:
633
                kind = self.final_kind(parent_id)
634
            except NoSuchFile:
635
                kind = None
636
            if kind is None:
637
                conflicts.append(('missing parent', parent_id))
638
            elif kind != "directory":
639
                conflicts.append(('non-directory parent', parent_id))
1534.7.6 by Aaron Bentley
Added conflict handling
640
        return conflicts
1534.7.37 by Aaron Bentley
Allowed removed dirs to have content-free children.
641
642
    def _any_contents(self, trans_ids):
643
        """Return true if any of the trans_ids, will have contents."""
644
        for trans_id in trans_ids:
645
            try:
646
                kind = self.final_kind(trans_id)
647
            except NoSuchFile:
648
                continue
649
            return True
650
        return False
1534.7.35 by Aaron Bentley
Got file renaming working
651
3619.2.8 by Aaron Bentley
Reorganize execute-bit handling
652
    def _set_executability(self, path, trans_id):
1534.7.40 by Aaron Bentley
Updated docs
653
        """Set the executability of versioned files """
1534.7.25 by Aaron Bentley
Added set_executability
654
        if supports_executable():
3619.2.8 by Aaron Bentley
Reorganize execute-bit handling
655
            new_executability = self._new_executability[trans_id]
1534.7.25 by Aaron Bentley
Added set_executability
656
            abspath = self._tree.abspath(path)
657
            current_mode = os.stat(abspath).st_mode
658
            if new_executability:
659
                umask = os.umask(0)
660
                os.umask(umask)
661
                to_mode = current_mode | (0100 & ~umask)
662
                # Enable x-bit for others only if they can read it.
663
                if current_mode & 0004:
664
                    to_mode |= 0001 & ~umask
665
                if current_mode & 0040:
666
                    to_mode |= 0010 & ~umask
667
            else:
668
                to_mode = current_mode & ~0111
669
            os.chmod(abspath, to_mode)
670
1534.7.23 by Aaron Bentley
Transform.new_entry -> Transform._new_entry
671
    def _new_entry(self, name, parent_id, file_id):
1534.7.21 by Aaron Bentley
Updated docstrings
672
        """Helper function to create a new filesystem entry."""
1534.7.2 by Aaron Bentley
Added convenience function
673
        trans_id = self.create_path(name, parent_id)
674
        if file_id is not None:
675
            self.version_file(file_id, trans_id)
676
        return trans_id
677
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
678
    def new_file(self, name, parent_id, contents, file_id=None,
1534.7.27 by Aaron Bentley
Added execute bit to new_file method
679
                 executable=None):
1534.7.156 by Aaron Bentley
PEP8 fixes
680
        """Convenience method to create files.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
681
1534.7.21 by Aaron Bentley
Updated docstrings
682
        name is the name of the file to create.
683
        parent_id is the transaction id of the parent directory of the file.
684
        contents is an iterator of bytestrings, which will be used to produce
685
        the file.
1740.2.4 by Aaron Bentley
Update transform tests and docs
686
        :param file_id: The inventory ID of the file, if it is to be versioned.
687
        :param executable: Only valid when a file_id has been supplied.
1534.7.21 by Aaron Bentley
Updated docstrings
688
        """
1534.7.23 by Aaron Bentley
Transform.new_entry -> Transform._new_entry
689
        trans_id = self._new_entry(name, parent_id, file_id)
1740.2.4 by Aaron Bentley
Update transform tests and docs
690
        # TODO: rather than scheduling a set_executable call,
691
        # have create_file create the file with the right mode.
1534.7.20 by Aaron Bentley
Added directory handling
692
        self.create_file(contents, trans_id)
1534.7.27 by Aaron Bentley
Added execute bit to new_file method
693
        if executable is not None:
694
            self.set_executability(executable, trans_id)
1534.7.20 by Aaron Bentley
Added directory handling
695
        return trans_id
696
697
    def new_directory(self, name, parent_id, file_id=None):
1534.7.156 by Aaron Bentley
PEP8 fixes
698
        """Convenience method to create directories.
1534.7.21 by Aaron Bentley
Updated docstrings
699
700
        name is the name of the directory to create.
701
        parent_id is the transaction id of the parent directory of the
702
        directory.
703
        file_id is the inventory ID of the directory, if it is to be versioned.
704
        """
1534.7.23 by Aaron Bentley
Transform.new_entry -> Transform._new_entry
705
        trans_id = self._new_entry(name, parent_id, file_id)
1534.7.20 by Aaron Bentley
Added directory handling
706
        self.create_directory(trans_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
707
        return trans_id
1534.7.20 by Aaron Bentley
Added directory handling
708
1534.7.22 by Aaron Bentley
Added symlink support
709
    def new_symlink(self, name, parent_id, target, file_id=None):
1534.7.156 by Aaron Bentley
PEP8 fixes
710
        """Convenience method to create symbolic link.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
711
1534.7.22 by Aaron Bentley
Added symlink support
712
        name is the name of the symlink to create.
713
        parent_id is the transaction id of the parent directory of the symlink.
714
        target is a bytestring of the target of the symlink.
715
        file_id is the inventory ID of the file, if it is to be versioned.
716
        """
1534.7.23 by Aaron Bentley
Transform.new_entry -> Transform._new_entry
717
        trans_id = self._new_entry(name, parent_id, file_id)
1534.7.22 by Aaron Bentley
Added symlink support
718
        self.create_symlink(target, trans_id)
719
        return trans_id
720
1551.11.12 by Aaron Bentley
Changes from review
721
    def _affected_ids(self):
722
        """Return the set of transform ids affected by the transform"""
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
723
        trans_ids = set(self._removed_id)
724
        trans_ids.update(self._new_id.keys())
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
725
        trans_ids.update(self._removed_contents)
726
        trans_ids.update(self._new_contents.keys())
727
        trans_ids.update(self._new_executability.keys())
728
        trans_ids.update(self._new_name.keys())
729
        trans_ids.update(self._new_parent.keys())
1551.11.12 by Aaron Bentley
Changes from review
730
        return trans_ids
731
732
    def _get_file_id_maps(self):
733
        """Return mapping of file_ids to trans_ids in the to and from states"""
734
        trans_ids = self._affected_ids()
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
735
        from_trans_ids = {}
736
        to_trans_ids = {}
737
        # Build up two dicts: trans_ids associated with file ids in the
738
        # FROM state, vs the TO state.
739
        for trans_id in trans_ids:
740
            from_file_id = self.tree_file_id(trans_id)
741
            if from_file_id is not None:
742
                from_trans_ids[from_file_id] = trans_id
743
            to_file_id = self.final_file_id(trans_id)
744
            if to_file_id is not None:
745
                to_trans_ids[to_file_id] = trans_id
1551.11.12 by Aaron Bentley
Changes from review
746
        return from_trans_ids, to_trans_ids
747
748
    def _from_file_data(self, from_trans_id, from_versioned, file_id):
749
        """Get data about a file in the from (tree) state
750
751
        Return a (name, parent, kind, executable) tuple
752
        """
753
        from_path = self._tree_id_paths.get(from_trans_id)
754
        if from_versioned:
755
            # get data from working tree if versioned
3363.17.5 by Aaron Bentley
Update merge to not use inventory
756
            from_entry = self._tree.iter_entries_by_dir([file_id]).next()[1]
1551.11.12 by Aaron Bentley
Changes from review
757
            from_name = from_entry.name
758
            from_parent = from_entry.parent_id
759
        else:
760
            from_entry = None
761
            if from_path is None:
762
                # File does not exist in FROM state
763
                from_name = None
764
                from_parent = None
765
            else:
766
                # File exists, but is not versioned.  Have to use path-
767
                # splitting stuff
768
                from_name = os.path.basename(from_path)
769
                tree_parent = self.get_tree_parent(from_trans_id)
770
                from_parent = self.tree_file_id(tree_parent)
771
        if from_path is not None:
772
            from_kind, from_executable, from_stats = \
773
                self._tree._comparison_data(from_entry, from_path)
774
        else:
775
            from_kind = None
776
            from_executable = False
777
        return from_name, from_parent, from_kind, from_executable
778
779
    def _to_file_data(self, to_trans_id, from_trans_id, from_executable):
780
        """Get data about a file in the to (target) state
781
782
        Return a (name, parent, kind, executable) tuple
783
        """
784
        to_name = self.final_name(to_trans_id)
785
        try:
786
            to_kind = self.final_kind(to_trans_id)
787
        except NoSuchFile:
788
            to_kind = None
789
        to_parent = self.final_file_id(self.final_parent(to_trans_id))
790
        if to_trans_id in self._new_executability:
791
            to_executable = self._new_executability[to_trans_id]
792
        elif to_trans_id == from_trans_id:
793
            to_executable = from_executable
794
        else:
795
            to_executable = False
796
        return to_name, to_parent, to_kind, to_executable
797
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
798
    def iter_changes(self):
799
        """Produce output in the same format as Tree.iter_changes.
1551.11.12 by Aaron Bentley
Changes from review
800
801
        Will produce nonsensical results if invoked while inventory/filesystem
802
        conflicts (as reported by TreeTransform.find_conflicts()) are present.
803
804
        This reads the Transform, but only reproduces changes involving a
805
        file_id.  Files that are not versioned in either of the FROM or TO
806
        states are not reflected.
807
        """
808
        final_paths = FinalPaths(self)
809
        from_trans_ids, to_trans_ids = self._get_file_id_maps()
1551.11.4 by Aaron Bentley
Sort output of Transform.iter_changes by path
810
        results = []
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
811
        # Now iterate through all active file_ids
812
        for file_id in set(from_trans_ids.keys() + to_trans_ids.keys()):
1551.11.7 by Aaron Bentley
Stop modified flag bleeding into later changes
813
            modified = False
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
814
            from_trans_id = from_trans_ids.get(file_id)
815
            # find file ids, and determine versioning state
816
            if from_trans_id is None:
817
                from_versioned = False
818
                from_trans_id = to_trans_ids[file_id]
819
            else:
820
                from_versioned = True
821
            to_trans_id = to_trans_ids.get(file_id)
822
            if to_trans_id is None:
823
                to_versioned = False
824
                to_trans_id = from_trans_id
825
            else:
826
                to_versioned = True
1551.11.12 by Aaron Bentley
Changes from review
827
828
            from_name, from_parent, from_kind, from_executable = \
829
                self._from_file_data(from_trans_id, from_versioned, file_id)
830
831
            to_name, to_parent, to_kind, to_executable = \
832
                self._to_file_data(to_trans_id, from_trans_id, from_executable)
833
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
834
            if not from_versioned:
835
                from_path = None
836
            else:
837
                from_path = self._tree_id_paths.get(from_trans_id)
838
            if not to_versioned:
839
                to_path = None
840
            else:
841
                to_path = final_paths.get_path(to_trans_id)
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
842
            if from_kind != to_kind:
843
                modified = True
1551.10.37 by Aaron Bentley
recommit of TreeTransform._iter_changes fix with missing files
844
            elif to_kind in ('file', 'symlink') and (
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
845
                to_trans_id != from_trans_id or
846
                to_trans_id in self._new_contents):
847
                modified = True
848
            if (not modified and from_versioned == to_versioned and
849
                from_parent==to_parent and from_name == to_name and
850
                from_executable == to_executable):
851
                continue
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
852
            results.append((file_id, (from_path, to_path), modified,
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
853
                   (from_versioned, to_versioned),
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
854
                   (from_parent, to_parent),
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
855
                   (from_name, to_name),
856
                   (from_kind, to_kind),
1551.11.4 by Aaron Bentley
Sort output of Transform.iter_changes by path
857
                   (from_executable, to_executable)))
858
        return iter(sorted(results, key=lambda x:x[1]))
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
859
4354.4.4 by Aaron Bentley
Simplify by using CommitBuilder directly
860
    def get_preview_tree(self):
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
861
        """Return a tree representing the result of the transform.
862
4634.57.4 by Aaron Bentley
Update docs
863
        The tree is a snapshot, and altering the TreeTransform will invalidate
864
        it.
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
865
        """
4354.4.4 by Aaron Bentley
Simplify by using CommitBuilder directly
866
        return _PreviewTree(self)
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
867
4526.8.2 by Aaron Bentley
Proved strict commit handling.
868
    def commit(self, branch, message, merge_parents=None, strict=False):
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
869
        """Commit the result of this TreeTransform to a branch.
870
871
        :param branch: The branch to commit to.
872
        :param message: The message to attach to the commit.
873
        :param merge_parents: Additional parents specified by pending merges.
874
        :return: The revision_id of the revision committed.
875
        """
4526.8.6 by Aaron Bentley
Check for malformed transforms before committing.
876
        self._check_malformed()
4526.8.2 by Aaron Bentley
Proved strict commit handling.
877
        if strict:
878
            unversioned = set(self._new_contents).difference(set(self._new_id))
879
            for trans_id in unversioned:
880
                if self.final_file_id(trans_id) is None:
881
                    raise errors.StrictCommitFailed()
4526.8.3 by Aaron Bentley
Clean up merge parent handling.
882
883
        revno, last_rev_id = branch.last_revision_info()
884
        if last_rev_id == _mod_revision.NULL_REVISION:
885
            if merge_parents is not None:
4526.8.5 by Aaron Bentley
Updates from review.
886
                raise ValueError('Cannot supply merge parents for first'
887
                                 ' commit.')
4526.8.3 by Aaron Bentley
Clean up merge parent handling.
888
            parent_ids = []
889
        else:
890
            parent_ids = [last_rev_id]
891
            if merge_parents is not None:
892
                parent_ids.extend(merge_parents)
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
893
        if self._tree.get_revision_id() != last_rev_id:
4526.8.5 by Aaron Bentley
Updates from review.
894
            raise ValueError('TreeTransform not based on branch basis: %s' %
895
                             self._tree.get_revision_id())
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
896
        builder = branch.get_commit_builder(parent_ids)
897
        preview = self.get_preview_tree()
898
        list(builder.record_iter_changes(preview, last_rev_id,
899
                                         self.iter_changes()))
900
        builder.finish_inventory()
901
        revision_id = builder.commit(message)
902
        branch.set_last_revision_info(revno + 1, revision_id)
903
        return revision_id
904
0.13.24 by Aaron Bentley
Update to use Tree.readlines, if possible.
905
    def _text_parent(self, trans_id):
906
        file_id = self.tree_file_id(trans_id)
907
        try:
908
            if file_id is None or self._tree.kind(file_id) != 'file':
909
                return None
910
        except errors.NoSuchFile:
911
            return None
912
        return file_id
913
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
914
    def _get_parents_texts(self, trans_id):
0.13.9 by Aaron Bentley
Update docs
915
        """Get texts for compression parents of this file."""
0.13.24 by Aaron Bentley
Update to use Tree.readlines, if possible.
916
        file_id = self._text_parent(trans_id)
917
        if file_id is None:
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
918
            return ()
919
        return (self._tree.get_file_text(file_id),)
920
921
    def _get_parents_lines(self, trans_id):
0.13.9 by Aaron Bentley
Update docs
922
        """Get lines for compression parents of this file."""
0.13.24 by Aaron Bentley
Update to use Tree.readlines, if possible.
923
        file_id = self._text_parent(trans_id)
924
        if file_id is None:
925
            return ()
926
        return (self._tree.get_file_lines(file_id),)
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
927
928
    def serialize(self, serializer):
0.13.9 by Aaron Bentley
Update docs
929
        """Serialize this TreeTransform.
930
931
        :param serializer: A Serialiser like pack.ContainerSerializer.
932
        """
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
933
        new_name = dict((k, v.encode('utf-8')) for k, v in
934
                        self._new_name.items())
935
        new_executability = dict((k, int(v)) for k, v in
936
                                 self._new_executability.items())
937
        tree_path_ids = dict((k.encode('utf-8'), v)
938
                             for k, v in self._tree_path_ids.items())
939
        attribs = {
940
            '_id_number': self._id_number,
941
            '_new_name': new_name,
942
            '_new_parent': self._new_parent,
943
            '_new_executability': new_executability,
944
            '_new_id': self._new_id,
945
            '_tree_path_ids': tree_path_ids,
946
            '_removed_id': list(self._removed_id),
947
            '_removed_contents': list(self._removed_contents),
948
            '_non_present_ids': self._non_present_ids,
949
            }
950
        yield serializer.bytes_record(bencode.bencode(attribs),
951
                                      (('attribs',),))
952
        for trans_id, kind in self._new_contents.items():
953
            if kind == 'file':
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
954
                lines = osutils.chunks_to_lines(
955
                    self._read_file_chunks(trans_id))
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
956
                parents = self._get_parents_lines(trans_id)
957
                mpdiff = multiparent.MultiParent.from_lines(lines, parents)
958
                content = ''.join(mpdiff.to_patch())
959
            if kind == 'directory':
960
                content = ''
961
            if kind == 'symlink':
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
962
                content = self._read_symlink_target(trans_id)
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
963
            yield serializer.bytes_record(content, ((trans_id, kind),))
964
965
    def deserialize(self, records):
0.13.9 by Aaron Bentley
Update docs
966
        """Deserialize a stored TreeTransform.
967
968
        :param records: An iterable of (names, content) tuples, as per
969
            pack.ContainerPushParser.
970
        """
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
971
        names, content = records.next()
972
        attribs = bencode.bdecode(content)
973
        self._id_number = attribs['_id_number']
974
        self._new_name = dict((k, v.decode('utf-8'))
975
                            for k, v in attribs['_new_name'].items())
976
        self._new_parent = attribs['_new_parent']
977
        self._new_executability = dict((k, bool(v)) for k, v in
978
            attribs['_new_executability'].items())
979
        self._new_id = attribs['_new_id']
980
        self._r_new_id = dict((v, k) for k, v in self._new_id.items())
981
        self._tree_path_ids = {}
982
        self._tree_id_paths = {}
983
        for bytepath, trans_id in attribs['_tree_path_ids'].items():
984
            path = bytepath.decode('utf-8')
985
            self._tree_path_ids[path] = trans_id
986
            self._tree_id_paths[trans_id] = path
987
        self._removed_id = set(attribs['_removed_id'])
988
        self._removed_contents = set(attribs['_removed_contents'])
989
        self._non_present_ids = attribs['_non_present_ids']
990
        for ((trans_id, kind),), content in records:
991
            if kind == 'file':
992
                mpdiff = multiparent.MultiParent.from_patch(content)
993
                lines = mpdiff.to_lines(self._get_parents_texts(trans_id))
994
                self.create_file(lines, trans_id)
995
            if kind == 'directory':
996
                self.create_directory(trans_id)
997
            if kind == 'symlink':
0.13.16 by Aaron Bentley
Add unicode symlink targets to tests
998
                self.create_symlink(content.decode('utf-8'), trans_id)
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
999
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1000
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1001
class DiskTreeTransform(TreeTransformBase):
1002
    """Tree transform storing its contents on disk."""
1003
1004
    def __init__(self, tree, limbodir, pb=DummyProgress(),
1005
                 case_sensitive=True):
1006
        """Constructor.
1007
        :param tree: The tree that will be transformed, but not necessarily
1008
            the output tree.
1009
        :param limbodir: A directory where new files can be stored until
1010
            they are installed in their proper places
1011
        :param pb: A ProgressBar indicating how much progress is being made
1012
        :param case_sensitive: If True, the target of the transform is
1013
            case sensitive, not just case preserving.
1014
        """
1015
        TreeTransformBase.__init__(self, tree, pb, case_sensitive)
1016
        self._limbodir = limbodir
1017
        self._deletiondir = None
1018
        # A mapping of transform ids to their limbo filename
1019
        self._limbo_files = {}
1020
        # A mapping of transform ids to a set of the transform ids of children
1021
        # that their limbo directory has
1022
        self._limbo_children = {}
1023
        # Map transform ids to maps of child filename to child transform id
1024
        self._limbo_children_names = {}
1025
        # List of transform ids that need to be renamed from limbo into place
1026
        self._needs_rename = set()
4934.1.2 by John Arbash Meinel
Move the functionality into osutils / extensions.
1027
        self._creation_mtime = None
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1028
1029
    def finalize(self):
1030
        """Release the working tree lock, if held, clean up limbo dir.
1031
1032
        This is required if apply has not been invoked, but can be invoked
1033
        even after apply.
1034
        """
1035
        if self._tree is None:
1036
            return
1037
        try:
1038
            entries = [(self._limbo_name(t), t, k) for t, k in
1039
                       self._new_contents.iteritems()]
1040
            entries.sort(reverse=True)
1041
            for path, trans_id, kind in entries:
4440.1.1 by Craig Hewetson
bug fixes for:
1042
                delete_any(path)
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1043
            try:
4440.1.1 by Craig Hewetson
bug fixes for:
1044
                delete_any(self._limbodir)
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1045
            except OSError:
1046
                # We don't especially care *why* the dir is immortal.
1047
                raise ImmortalLimbo(self._limbodir)
1048
            try:
1049
                if self._deletiondir is not None:
4440.1.1 by Craig Hewetson
bug fixes for:
1050
                    delete_any(self._deletiondir)
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1051
            except OSError:
1052
                raise errors.ImmortalPendingDeletion(self._deletiondir)
1053
        finally:
1054
            TreeTransformBase.finalize(self)
1055
1056
    def _limbo_name(self, trans_id):
1057
        """Generate the limbo name of a file"""
1058
        limbo_name = self._limbo_files.get(trans_id)
4634.79.1 by Aaron Bentley
TransformPreview uses ascii-only filenames.
1059
        if limbo_name is None:
1060
            limbo_name = self._generate_limbo_path(trans_id)
1061
            self._limbo_files[trans_id] = limbo_name
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1062
        return limbo_name
1063
4634.79.1 by Aaron Bentley
TransformPreview uses ascii-only filenames.
1064
    def _generate_limbo_path(self, trans_id):
1065
        """Generate a limbo path using the trans_id as the relative path.
1066
1067
        This is suitable as a fallback, and when the transform should not be
1068
        sensitive to the path encoding of the limbo directory.
1069
        """
1070
        self._needs_rename.add(trans_id)
1071
        return pathjoin(self._limbodir, trans_id)
1072
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1073
    def adjust_path(self, name, parent, trans_id):
1074
        previous_parent = self._new_parent.get(trans_id)
1075
        previous_name = self._new_name.get(trans_id)
1076
        TreeTransformBase.adjust_path(self, name, parent, trans_id)
1077
        if (trans_id in self._limbo_files and
1078
            trans_id not in self._needs_rename):
1079
            self._rename_in_limbo([trans_id])
1080
            self._limbo_children[previous_parent].remove(trans_id)
1081
            del self._limbo_children_names[previous_parent][previous_name]
1082
4634.78.3 by Aaron Bentley
Remove spurious change.
1083
    def _rename_in_limbo(self, trans_ids):
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1084
        """Fix limbo names so that the right final path is produced.
1085
1086
        This means we outsmarted ourselves-- we tried to avoid renaming
1087
        these files later by creating them with their final names in their
1088
        final parents.  But now the previous name or parent is no longer
1089
        suitable, so we have to rename them.
1090
1091
        Even for trans_ids that have no new contents, we must remove their
1092
        entries from _limbo_files, because they are now stale.
1093
        """
1094
        for trans_id in trans_ids:
1095
            old_path = self._limbo_files.pop(trans_id)
1096
            if trans_id not in self._new_contents:
1097
                continue
1098
            new_path = self._limbo_name(trans_id)
1099
            os.rename(old_path, new_path)
4634.78.1 by Aaron Bentley
adjust_path updatest limbo paths.
1100
            for descendant in self._limbo_descendants(trans_id):
1101
                desc_path = self._limbo_files[descendant]
1102
                desc_path = new_path + desc_path[len(old_path):]
1103
                self._limbo_files[descendant] = desc_path
1104
1105
    def _limbo_descendants(self, trans_id):
1106
        """Return the set of trans_ids whose limbo paths descend from this."""
1107
        descendants = set(self._limbo_children.get(trans_id, []))
1108
        for descendant in list(descendants):
1109
            descendants.update(self._limbo_descendants(descendant))
1110
        return descendants
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1111
1112
    def create_file(self, contents, trans_id, mode_id=None):
1113
        """Schedule creation of a new file.
1114
1115
        See also new_file.
1116
1117
        Contents is an iterator of strings, all of which will be written
1118
        to the target destination.
1119
1120
        New file takes the permissions of any existing file with that id,
1121
        unless mode_id is specified.
1122
        """
1123
        name = self._limbo_name(trans_id)
1124
        f = open(name, 'wb')
1125
        try:
1126
            try:
1127
                unique_add(self._new_contents, trans_id, 'file')
1128
            except:
1129
                # Clean up the file, it never got registered so
1130
                # TreeTransform.finalize() won't clean it up.
1131
                f.close()
1132
                os.unlink(name)
1133
                raise
1134
1135
            f.writelines(contents)
1136
        finally:
1137
            f.close()
4934.1.12 by John Arbash Meinel
Revert all of the extension code.
1138
        self._set_mtime(name)
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1139
        self._set_mode(trans_id, mode_id, S_ISREG)
1140
1141
    def _read_file_chunks(self, trans_id):
1142
        cur_file = open(self._limbo_name(trans_id), 'rb')
1143
        try:
1144
            return cur_file.readlines()
1145
        finally:
1146
            cur_file.close()
1147
1148
    def _read_symlink_target(self, trans_id):
1149
        return os.readlink(self._limbo_name(trans_id))
1150
4934.1.12 by John Arbash Meinel
Revert all of the extension code.
1151
    def _set_mtime(self, path):
4934.1.2 by John Arbash Meinel
Move the functionality into osutils / extensions.
1152
        """All files that are created get the same mtime.
1153
1154
        This time is set by the first object to be created.
1155
        """
1156
        if self._creation_mtime is None:
1157
            self._creation_mtime = time.time()
4934.1.12 by John Arbash Meinel
Revert all of the extension code.
1158
        os.utime(path, (self._creation_mtime, self._creation_mtime))
4934.1.2 by John Arbash Meinel
Move the functionality into osutils / extensions.
1159
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1160
    def create_hardlink(self, path, trans_id):
1161
        """Schedule creation of a hard link"""
1162
        name = self._limbo_name(trans_id)
1163
        try:
1164
            os.link(path, name)
1165
        except OSError, e:
1166
            if e.errno != errno.EPERM:
1167
                raise
1168
            raise errors.HardLinkNotSupported(path)
1169
        try:
1170
            unique_add(self._new_contents, trans_id, 'file')
1171
        except:
1172
            # Clean up the file, it never got registered so
1173
            # TreeTransform.finalize() won't clean it up.
1174
            os.unlink(name)
1175
            raise
1176
1177
    def create_directory(self, trans_id):
1178
        """Schedule creation of a new directory.
1179
1180
        See also new_directory.
1181
        """
1182
        os.mkdir(self._limbo_name(trans_id))
1183
        unique_add(self._new_contents, trans_id, 'directory')
1184
1185
    def create_symlink(self, target, trans_id):
1186
        """Schedule creation of a new symbolic link.
1187
1188
        target is a bytestring.
1189
        See also new_symlink.
1190
        """
1191
        if has_symlinks():
1192
            os.symlink(target, self._limbo_name(trans_id))
1193
            unique_add(self._new_contents, trans_id, 'symlink')
1194
        else:
1195
            try:
1196
                path = FinalPaths(self).get_path(trans_id)
1197
            except KeyError:
1198
                path = None
1199
            raise UnableCreateSymlink(path=path)
1200
1201
    def cancel_creation(self, trans_id):
1202
        """Cancel the creation of new file contents."""
1203
        del self._new_contents[trans_id]
1204
        children = self._limbo_children.get(trans_id)
1205
        # if this is a limbo directory with children, move them before removing
1206
        # the directory
1207
        if children is not None:
1208
            self._rename_in_limbo(children)
1209
            del self._limbo_children[trans_id]
1210
            del self._limbo_children_names[trans_id]
1211
        delete_any(self._limbo_name(trans_id))
1212
1213
1214
class TreeTransform(DiskTreeTransform):
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1215
    """Represent a tree transformation.
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1216
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1217
    This object is designed to support incremental generation of the transform,
1218
    in any order.
1219
1220
    However, it gives optimum performance when parent directories are created
1221
    before their contents.  The transform is then able to put child files
1222
    directly in their parent directory, avoiding later renames.
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1223
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1224
    It is easy to produce malformed transforms, but they are generally
1225
    harmless.  Attempting to apply a malformed transform will cause an
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1226
    exception to be raised before any modifications are made to the tree.
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1227
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1228
    Many kinds of malformed transforms can be corrected with the
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1229
    resolve_conflicts function.  The remaining ones indicate programming error,
1230
    such as trying to create a file with no path.
1231
1232
    Two sets of file creation methods are supplied.  Convenience methods are:
1233
     * new_file
1234
     * new_directory
1235
     * new_symlink
1236
1237
    These are composed of the low-level methods:
1238
     * create_path
1239
     * create_file or create_directory or create_symlink
1240
     * version_file
1241
     * set_executability
3008.1.13 by Michael Hudson
merge bzr.dev
1242
1243
    Transform/Transaction ids
1244
    -------------------------
1245
    trans_ids are temporary ids assigned to all files involved in a transform.
1246
    It's possible, even common, that not all files in the Tree have trans_ids.
1247
1248
    trans_ids are used because filenames and file_ids are not good enough
1249
    identifiers; filenames change, and not all files have file_ids.  File-ids
1250
    are also associated with trans-ids, so that moving a file moves its
1251
    file-id.
1252
1253
    trans_ids are only valid for the TreeTransform that generated them.
1254
1255
    Limbo
1256
    -----
1257
    Limbo is a temporary directory use to hold new versions of files.
1258
    Files are added to limbo by create_file, create_directory, create_symlink,
1259
    and their convenience variants (new_*).  Files may be removed from limbo
1260
    using cancel_creation.  Files are renamed from limbo into their final
1261
    location as part of TreeTransform.apply
1262
1263
    Limbo must be cleaned up, by either calling TreeTransform.apply or
1264
    calling TreeTransform.finalize.
1265
1266
    Files are placed into limbo inside their parent directories, where
1267
    possible.  This reduces subsequent renames, and makes operations involving
1268
    lots of files faster.  This optimization is only possible if the parent
1269
    directory is created *before* creating any of its children, so avoid
1270
    creating children before parents, where possible.
1271
1272
    Pending-deletion
1273
    ----------------
1274
    This temporary directory is used by _FileMover for storing files that are
1275
    about to be deleted.  In case of rollback, the files will be restored.
1276
    FileMover does not delete files until it is sure that a rollback will not
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1277
    happen.
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1278
    """
1279
    def __init__(self, tree, pb=DummyProgress()):
1280
        """Note: a tree_write lock is taken on the tree.
1281
1282
        Use TreeTransform.finalize() to release the lock (can be omitted if
1283
        TreeTransform.apply() called).
1284
        """
1285
        tree.lock_tree_write()
3008.1.13 by Michael Hudson
merge bzr.dev
1286
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1287
        try:
1288
            limbodir = urlutils.local_path_from_url(
3407.2.8 by Martin Pool
Deprecate LockableFiles.controlfilename
1289
                tree._transport.abspath('limbo'))
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1290
            try:
1291
                os.mkdir(limbodir)
1292
            except OSError, e:
1293
                if e.errno == errno.EEXIST:
1294
                    raise ExistingLimbo(limbodir)
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
1295
            deletiondir = urlutils.local_path_from_url(
3407.2.8 by Martin Pool
Deprecate LockableFiles.controlfilename
1296
                tree._transport.abspath('pending-deletion'))
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1297
            try:
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
1298
                os.mkdir(deletiondir)
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1299
            except OSError, e:
1300
                if e.errno == errno.EEXIST:
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
1301
                    raise errors.ExistingPendingDeletion(deletiondir)
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1302
        except:
1303
            tree.unlock()
1304
            raise
3008.1.13 by Michael Hudson
merge bzr.dev
1305
4354.5.2 by Aaron Bentley
Move WorkingTree-specific code out of BaseTreeTransform
1306
        # Cache of realpath results, to speed up canonical_path
1307
        self._realpaths = {}
1308
        # Cache of relpath results, to speed up canonical_path
1309
        self._relpaths = {}
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1310
        DiskTreeTransform.__init__(self, tree, limbodir, pb,
3008.1.15 by Aaron Bentley
Make case_sensitive an aspect of the transform, not the source tree
1311
                                   tree.case_sensitive)
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
1312
        self._deletiondir = deletiondir
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1313
4354.5.2 by Aaron Bentley
Move WorkingTree-specific code out of BaseTreeTransform
1314
    def canonical_path(self, path):
1315
        """Get the canonical tree-relative path"""
1316
        # don't follow final symlinks
1317
        abs = self._tree.abspath(path)
1318
        if abs in self._relpaths:
1319
            return self._relpaths[abs]
1320
        dirname, basename = os.path.split(abs)
1321
        if dirname not in self._realpaths:
1322
            self._realpaths[dirname] = os.path.realpath(dirname)
1323
        dirname = self._realpaths[dirname]
1324
        abs = pathjoin(dirname, basename)
1325
        if dirname in self._relpaths:
1326
            relpath = pathjoin(self._relpaths[dirname], basename)
1327
            relpath = relpath.rstrip('/\\')
1328
        else:
1329
            relpath = self._tree.relpath(abs)
1330
        self._relpaths[abs] = relpath
1331
        return relpath
1332
1333
    def tree_kind(self, trans_id):
1334
        """Determine the file kind in the working tree.
1335
1336
        Raises NoSuchFile if the file does not exist
1337
        """
1338
        path = self._tree_id_paths.get(trans_id)
1339
        if path is None:
1340
            raise NoSuchFile(None)
1341
        try:
1342
            return file_kind(self._tree.abspath(path))
1343
        except OSError, e:
1344
            if e.errno != errno.ENOENT:
1345
                raise
1346
            else:
1347
                raise NoSuchFile(path)
1348
1349
    def _set_mode(self, trans_id, mode_id, typefunc):
1350
        """Set the mode of new file contents.
1351
        The mode_id is the existing file to get the mode from (often the same
1352
        as trans_id).  The operation is only performed if there's a mode match
1353
        according to typefunc.
1354
        """
1355
        if mode_id is None:
1356
            mode_id = trans_id
1357
        try:
1358
            old_path = self._tree_id_paths[mode_id]
1359
        except KeyError:
1360
            return
1361
        try:
1362
            mode = os.stat(self._tree.abspath(old_path)).st_mode
1363
        except OSError, e:
1364
            if e.errno in (errno.ENOENT, errno.ENOTDIR):
1365
                # Either old_path doesn't exist, or the parent of the
1366
                # target is not a directory (but will be one eventually)
1367
                # Either way, we know it doesn't exist *right now*
1368
                # See also bug #248448
1369
                return
1370
            else:
1371
                raise
1372
        if typefunc(mode):
1373
            os.chmod(self._limbo_name(trans_id), mode)
1374
1375
    def iter_tree_children(self, parent_id):
1376
        """Iterate through the entry's tree children, if any"""
1377
        try:
1378
            path = self._tree_id_paths[parent_id]
1379
        except KeyError:
1380
            return
1381
        try:
1382
            children = os.listdir(self._tree.abspath(path))
1383
        except OSError, e:
1384
            if not (osutils._is_error_enotdir(e)
1385
                    or e.errno in (errno.ENOENT, errno.ESRCH)):
1386
                raise
1387
            return
1388
1389
        for child in children:
1390
            childpath = joinpath(path, child)
1391
            if self._tree.is_control_filename(childpath):
1392
                continue
1393
            yield self.trans_id_tree_path(childpath)
1394
4634.79.1 by Aaron Bentley
TransformPreview uses ascii-only filenames.
1395
    def _generate_limbo_path(self, trans_id):
1396
        """Generate a limbo path using the final path if possible.
1397
1398
        This optimizes the performance of applying the tree transform by
1399
        avoiding renames.  These renames can be avoided only when the parent
1400
        directory is already scheduled for creation.
1401
1402
        If the final path cannot be used, falls back to using the trans_id as
1403
        the relpath.
1404
        """
1405
        parent = self._new_parent.get(trans_id)
1406
        # if the parent directory is already in limbo (e.g. when building a
1407
        # tree), choose a limbo name inside the parent, to reduce further
1408
        # renames.
1409
        use_direct_path = False
1410
        if self._new_contents.get(parent) == 'directory':
1411
            filename = self._new_name.get(trans_id)
1412
            if filename is not None:
1413
                if parent not in self._limbo_children:
1414
                    self._limbo_children[parent] = set()
1415
                    self._limbo_children_names[parent] = {}
1416
                    use_direct_path = True
1417
                # the direct path can only be used if no other file has
1418
                # already taken this pathname, i.e. if the name is unused, or
1419
                # if it is already associated with this trans_id.
1420
                elif self._case_sensitive_target:
1421
                    if (self._limbo_children_names[parent].get(filename)
1422
                        in (trans_id, None)):
1423
                        use_direct_path = True
1424
                else:
1425
                    for l_filename, l_trans_id in\
1426
                        self._limbo_children_names[parent].iteritems():
1427
                        if l_trans_id == trans_id:
1428
                            continue
1429
                        if l_filename.lower() == filename.lower():
1430
                            break
1431
                    else:
1432
                        use_direct_path = True
1433
1434
        if not use_direct_path:
1435
            return DiskTreeTransform._generate_limbo_path(self, trans_id)
1436
1437
        limbo_name = pathjoin(self._limbo_files[parent], filename)
1438
        self._limbo_children[parent].add(trans_id)
1439
        self._limbo_children_names[parent][filename] = trans_id
1440
        return limbo_name
1441
1442
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
1443
    def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1444
        """Apply all changes to the inventory and filesystem.
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1445
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1446
        If filesystem or inventory conflicts are present, MalformedTransform
1447
        will be thrown.
1448
1449
        If apply succeeds, finalize is not necessary.
1450
1451
        :param no_conflicts: if True, the caller guarantees there are no
1452
            conflicts, so no check is made.
3453.2.11 by Aaron Bentley
Updates from review
1453
        :param precomputed_delta: An inventory delta to use instead of
1454
            calculating one.
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1455
        :param _mover: Supply an alternate FileMover, for testing
1456
        """
1457
        if not no_conflicts:
4526.8.6 by Aaron Bentley
Check for malformed transforms before committing.
1458
            self._check_malformed()
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1459
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1460
        try:
3619.2.7 by Aaron Bentley
Fix progress handling
1461
            if precomputed_delta is None:
1462
                child_pb.update('Apply phase', 0, 2)
1463
                inventory_delta = self._generate_inventory_delta()
1464
                offset = 1
1465
            else:
1466
                inventory_delta = precomputed_delta
1467
                offset = 0
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1468
            if _mover is None:
1469
                mover = _FileMover()
1470
            else:
1471
                mover = _mover
1472
            try:
3619.2.7 by Aaron Bentley
Fix progress handling
1473
                child_pb.update('Apply phase', 0 + offset, 2 + offset)
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1474
                self._apply_removals(mover)
3619.2.7 by Aaron Bentley
Fix progress handling
1475
                child_pb.update('Apply phase', 1 + offset, 2 + offset)
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1476
                modified_paths = self._apply_insertions(mover)
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1477
            except:
1478
                mover.rollback()
1479
                raise
1480
            else:
1481
                mover.apply_deletions()
1482
        finally:
1483
            child_pb.finished()
1484
        self._tree.apply_inventory_delta(inventory_delta)
3008.1.29 by Aaron Bentley
Add docstrings, rename TT.__doc
1485
        self._done = True
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1486
        self.finalize()
1487
        return _TransformResults(modified_paths, self.rename_count)
1488
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1489
    def _generate_inventory_delta(self):
3619.2.9 by Aaron Bentley
Update docs
1490
        """Generate an inventory delta for the current transform."""
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1491
        inventory_delta = []
1492
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
3619.2.7 by Aaron Bentley
Fix progress handling
1493
        new_paths = self._inventory_altered()
1494
        total_entries = len(new_paths) + len(self._removed_id)
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1495
        try:
3619.2.2 by Aaron Bentley
Further cleanup
1496
            for num, trans_id in enumerate(self._removed_id):
3619.2.7 by Aaron Bentley
Fix progress handling
1497
                if (num % 10) == 0:
1498
                    child_pb.update('removing file', num, total_entries)
3619.2.2 by Aaron Bentley
Further cleanup
1499
                if trans_id == self._new_root:
1500
                    file_id = self._tree.get_root_id()
1501
                else:
1502
                    file_id = self.tree_file_id(trans_id)
1503
                # File-id isn't really being deleted, just moved
1504
                if file_id in self._r_new_id:
1505
                    continue
1506
                path = self._tree_id_paths[trans_id]
1507
                inventory_delta.append((path, None, file_id, None))
3619.2.7 by Aaron Bentley
Fix progress handling
1508
            new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1509
                                     new_paths)
1510
            entries = self._tree.iter_entries_by_dir(
1511
                new_path_file_ids.values())
1512
            old_paths = dict((e.file_id, p) for p, e in entries)
1513
            final_kinds = {}
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1514
            for num, (path, trans_id) in enumerate(new_paths):
1515
                if (num % 10) == 0:
3619.2.7 by Aaron Bentley
Fix progress handling
1516
                    child_pb.update('adding file',
1517
                                    num + len(self._removed_id), total_entries)
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1518
                file_id = new_path_file_ids[trans_id]
3619.2.2 by Aaron Bentley
Further cleanup
1519
                if file_id is None:
1520
                    continue
1521
                needs_entry = False
3619.2.5 by Aaron Bentley
Reduce set tests
1522
                try:
1523
                    kind = self.final_kind(trans_id)
1524
                except NoSuchFile:
1525
                    kind = self._tree.stored_kind(file_id)
3619.2.4 by Aaron Bentley
Further restructuring
1526
                parent_trans_id = self.final_parent(trans_id)
1527
                parent_file_id = new_path_file_ids.get(parent_trans_id)
1528
                if parent_file_id is None:
1529
                    parent_file_id = self.final_file_id(parent_trans_id)
1530
                if trans_id in self._new_reference_revision:
1531
                    new_entry = inventory.TreeReference(
1532
                        file_id,
1533
                        self._new_name[trans_id],
1534
                        self.final_file_id(self._new_parent[trans_id]),
1535
                        None, self._new_reference_revision[trans_id])
1536
                else:
1537
                    new_entry = inventory.make_entry(kind,
1538
                        self.final_name(trans_id),
1539
                        parent_file_id, file_id)
1540
                old_path = old_paths.get(new_entry.file_id)
3619.2.8 by Aaron Bentley
Reorganize execute-bit handling
1541
                new_executability = self._new_executability.get(trans_id)
1542
                if new_executability is not None:
1543
                    new_entry.executable = new_executability
3619.2.4 by Aaron Bentley
Further restructuring
1544
                inventory_delta.append(
1545
                    (old_path, path, new_entry.file_id, new_entry))
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1546
        finally:
1547
            child_pb.finished()
1548
        return inventory_delta
1549
1550
    def _apply_removals(self, mover):
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1551
        """Perform tree operations that remove directory/inventory names.
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1552
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1553
        That is, delete files that are to be deleted, and put any files that
1554
        need renaming into limbo.  This must be done in strict child-to-parent
1555
        order.
3453.2.11 by Aaron Bentley
Updates from review
1556
1557
        If inventory_delta is None, no inventory delta generation is performed.
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1558
        """
1559
        tree_paths = list(self._tree_path_ids.iteritems())
1560
        tree_paths.sort(reverse=True)
1561
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1562
        try:
1563
            for num, data in enumerate(tree_paths):
1564
                path, trans_id = data
1565
                child_pb.update('removing file', num, len(tree_paths))
1566
                full_path = self._tree.abspath(path)
1567
                if trans_id in self._removed_contents:
1568
                    mover.pre_delete(full_path, os.path.join(self._deletiondir,
1569
                                     trans_id))
1570
                elif trans_id in self._new_name or trans_id in \
1571
                    self._new_parent:
1572
                    try:
1573
                        mover.rename(full_path, self._limbo_name(trans_id))
1574
                    except OSError, e:
1575
                        if e.errno != errno.ENOENT:
1576
                            raise
1577
                    else:
1578
                        self.rename_count += 1
1579
        finally:
1580
            child_pb.finished()
1581
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1582
    def _apply_insertions(self, mover):
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1583
        """Perform tree operations that insert directory/inventory names.
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1584
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1585
        That is, create any files that need to be created, and restore from
1586
        limbo any files that needed renaming.  This must be done in strict
1587
        parent-to-child order.
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
1588
1589
        If inventory_delta is None, no inventory delta is calculated, and
1590
        no list of modified paths is returned.
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1591
        """
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1592
        new_paths = self.new_paths(filesystem_only=True)
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1593
        modified_paths = []
3453.2.2 by Aaron Bentley
Avoid unnecessary file_id lookups
1594
        new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1595
                                 new_paths)
3453.2.1 by Aaron Bentley
Speed up apply_insertions using iter_entries_by_dir instead of id2path
1596
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1597
        try:
1598
            for num, (path, trans_id) in enumerate(new_paths):
3453.2.1 by Aaron Bentley
Speed up apply_insertions using iter_entries_by_dir instead of id2path
1599
                if (num % 10) == 0:
1600
                    child_pb.update('adding file', num, len(new_paths))
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
1601
                full_path = self._tree.abspath(path)
1602
                if trans_id in self._needs_rename:
1603
                    try:
1604
                        mover.rename(self._limbo_name(trans_id), full_path)
1605
                    except OSError, e:
1606
                        # We may be renaming a dangling inventory id
1607
                        if e.errno != errno.ENOENT:
1608
                            raise
1609
                    else:
1610
                        self.rename_count += 1
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1611
                if (trans_id in self._new_contents or
1612
                    self.path_changed(trans_id)):
1613
                    if trans_id in self._new_contents:
1614
                        modified_paths.append(full_path)
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1615
                if trans_id in self._new_executability:
3619.2.8 by Aaron Bentley
Reorganize execute-bit handling
1616
                    self._set_executability(path, trans_id)
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1617
        finally:
1618
            child_pb.finished()
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1619
        self._new_contents.clear()
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1620
        return modified_paths
1621
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1622
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1623
class TransformPreview(DiskTreeTransform):
3008.1.29 by Aaron Bentley
Add docstrings, rename TT.__doc
1624
    """A TreeTransform for generating preview trees.
1625
1626
    Unlike TreeTransform, this version works when the input tree is a
1627
    RevisionTree, rather than a WorkingTree.  As a result, it tends to ignore
1628
    unversioned files in the input tree.
1629
    """
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1630
3008.1.15 by Aaron Bentley
Make case_sensitive an aspect of the transform, not the source tree
1631
    def __init__(self, tree, pb=DummyProgress(), case_sensitive=True):
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
1632
        tree.lock_read()
3638.3.2 by Vincent Ladeuil
Fix all calls to tempfile.mkdtemp to osutils.mkdtemp.
1633
        limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1634
        DiskTreeTransform.__init__(self, tree, limbodir, pb, case_sensitive)
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1635
1636
    def canonical_path(self, path):
1637
        return path
1638
3008.1.9 by Michael Hudson
wanton hacking that lets me write an efficient version of get_diff_as_merged
1639
    def tree_kind(self, trans_id):
1640
        path = self._tree_id_paths.get(trans_id)
3008.2.1 by Aaron Bentley
Ensure conflict resolution works
1641
        if path is None:
1642
            raise NoSuchFile(None)
3008.1.9 by Michael Hudson
wanton hacking that lets me write an efficient version of get_diff_as_merged
1643
        file_id = self._tree.path2id(path)
1644
        return self._tree.kind(file_id)
1645
1646
    def _set_mode(self, trans_id, mode_id, typefunc):
1647
        """Set the mode of new file contents.
1648
        The mode_id is the existing file to get the mode from (often the same
1649
        as trans_id).  The operation is only performed if there's a mode match
1650
        according to typefunc.
1651
        """
1652
        # is it ok to ignore this?  probably
1653
        pass
1654
1655
    def iter_tree_children(self, parent_id):
1656
        """Iterate through the entry's tree children, if any"""
3008.2.1 by Aaron Bentley
Ensure conflict resolution works
1657
        try:
1658
            path = self._tree_id_paths[parent_id]
1659
        except KeyError:
1660
            return
1661
        file_id = self.tree_file_id(parent_id)
3363.5.2 by Aaron Bentley
Massive simplification of path2id
1662
        if file_id is None:
1663
            return
3363.17.5 by Aaron Bentley
Update merge to not use inventory
1664
        entry = self._tree.iter_entries_by_dir([file_id]).next()[1]
1665
        children = getattr(entry, 'children', {})
3363.2.23 by Aaron Bentley
Fix iter_entries_by_dir ordering
1666
        for child in children:
3008.2.1 by Aaron Bentley
Ensure conflict resolution works
1667
            childpath = joinpath(path, child)
1668
            yield self.trans_id_tree_path(childpath)
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1669
3008.1.29 by Aaron Bentley
Add docstrings, rename TT.__doc
1670
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1671
class _PreviewTree(tree.Tree):
3008.1.29 by Aaron Bentley
Add docstrings, rename TT.__doc
1672
    """Partial implementation of Tree to support show_diff_trees"""
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1673
4354.4.4 by Aaron Bentley
Simplify by using CommitBuilder directly
1674
    def __init__(self, transform):
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1675
        self._transform = transform
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1676
        self._final_paths = FinalPaths(transform)
3363.2.21 by Aaron Bentley
Implement iter_entries_by_dir
1677
        self.__by_parent = None
3571.1.1 by Aaron Bentley
Allow set/get of parent_ids in PreviewTree
1678
        self._parent_ids = []
3363.17.22 by Aaron Bentley
Cache expensive operations
1679
        self._all_children_cache = {}
1680
        self._path2trans_id_cache = {}
1681
        self._final_name_cache = {}
4634.57.1 by Aaron Bentley
Cache iter_changes values instead of re-running.
1682
        self._iter_changes_cache = dict((c[0], c) for c in
1683
                                        self._transform.iter_changes())
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1684
1685
    def _content_change(self, file_id):
3363.3.3 by Aaron Bentley
Updates from review
1686
        """Return True if the content of this file changed"""
4634.57.1 by Aaron Bentley
Cache iter_changes values instead of re-running.
1687
        changes = self._iter_changes_cache.get(file_id)
3363.3.3 by Aaron Bentley
Updates from review
1688
        # changes[2] is true if the file content changed.  See
1689
        # InterTree.iter_changes.
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1690
        return (changes is not None and changes[2])
1691
3363.9.1 by Aaron Bentley
Implement plan_merge, refactoring various bits
1692
    def _get_repository(self):
1693
        repo = getattr(self._transform._tree, '_repository', None)
1694
        if repo is None:
1695
            repo = self._transform._tree.branch.repository
1696
        return repo
1697
1698
    def _iter_parent_trees(self):
1699
        for revision_id in self.get_parent_ids():
1700
            try:
1701
                yield self.revision_tree(revision_id)
1702
            except errors.NoSuchRevisionInTree:
1703
                yield self._get_repository().revision_tree(revision_id)
1704
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1705
    def _get_file_revision(self, file_id, vf, tree_revision):
3363.9.1 by Aaron Bentley
Implement plan_merge, refactoring various bits
1706
        parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
1707
                       self._iter_parent_trees()]
1708
        vf.add_lines((file_id, tree_revision), parent_keys,
1709
                     self.get_file(file_id).readlines())
1710
        repo = self._get_repository()
1711
        base_vf = repo.texts
1712
        if base_vf not in vf.fallback_versionedfiles:
1713
            vf.fallback_versionedfiles.append(base_vf)
1714
        return tree_revision
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1715
3363.2.9 by Aaron Bentley
Fix up some refactorings
1716
    def _stat_limbo_file(self, file_id):
3363.2.7 by Aaron Bentley
Implement alterntative-to-inventory tests
1717
        trans_id = self._transform.trans_id_file_id(file_id)
1718
        name = self._transform._limbo_name(trans_id)
1719
        return os.lstat(name)
1720
3363.2.21 by Aaron Bentley
Implement iter_entries_by_dir
1721
    @property
1722
    def _by_parent(self):
1723
        if self.__by_parent is None:
1724
            self.__by_parent = self._transform.by_parent()
1725
        return self.__by_parent
1726
3363.14.1 by Aaron Bentley
Update to support comparison
1727
    def _comparison_data(self, entry, path):
4595.11.13 by Martin Pool
Remove get_kind_and_executable_by_path; go back to using plain path_content_summary
1728
        kind, size, executable, link_or_sha1 = self.path_content_summary(path)
3363.14.3 by Aaron Bentley
Handle missing files better
1729
        if kind == 'missing':
1730
            kind = None
1731
            executable = False
1732
        else:
1733
            file_id = self._transform.final_file_id(self._path2trans_id(path))
1734
            executable = self.is_executable(file_id, path)
3363.14.1 by Aaron Bentley
Update to support comparison
1735
        return kind, executable, None
1736
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1737
    def lock_read(self):
3008.1.18 by Aaron Bentley
Get supported PreviewTree functionality under test
1738
        # Perhaps in theory, this should lock the TreeTransform?
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1739
        pass
1740
1741
    def unlock(self):
1742
        pass
1743
3363.2.7 by Aaron Bentley
Implement alterntative-to-inventory tests
1744
    @property
1745
    def inventory(self):
1746
        """This Tree does not use inventory as its backing data."""
1747
        raise NotImplementedError(_PreviewTree.inventory)
1748
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1749
    def get_root_id(self):
1750
        return self._transform.final_file_id(self._transform.root)
1751
1752
    def all_file_ids(self):
3363.2.18 by Aaron Bentley
Implement correct all_file_ids for PreviewTree
1753
        tree_ids = set(self._transform._tree.all_file_ids())
1754
        tree_ids.difference_update(self._transform.tree_file_id(t)
1755
                                   for t in self._transform._removed_id)
1756
        tree_ids.update(self._transform._new_id.values())
1757
        return tree_ids
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1758
1759
    def __iter__(self):
1760
        return iter(self.all_file_ids())
1761
4544.2.1 by Robert Collins
Add interface enforcement for the behaviour of iter_changes with missing subtrees with explicit paths - the whole subtree is returned.
1762
    def _has_id(self, file_id, fallback_check):
3363.12.1 by Aaron Bentley
Remove new implementation of paths2ids, implement has_id
1763
        if file_id in self._transform._r_new_id:
1764
            return True
3981.1.1 by Robert Collins
Fix bug 319790 - unshelve of deleted paths failing.
1765
        elif file_id in set([self._transform.tree_file_id(trans_id) for
1766
            trans_id in self._transform._removed_id]):
3363.12.1 by Aaron Bentley
Remove new implementation of paths2ids, implement has_id
1767
            return False
1768
        else:
4544.2.1 by Robert Collins
Add interface enforcement for the behaviour of iter_changes with missing subtrees with explicit paths - the whole subtree is returned.
1769
            return fallback_check(file_id)
1770
1771
    def has_id(self, file_id):
1772
        return self._has_id(file_id, self._transform._tree.has_id)
1773
1774
    def has_or_had_id(self, file_id):
1775
        return self._has_id(file_id, self._transform._tree.has_or_had_id)
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1776
3363.5.2 by Aaron Bentley
Massive simplification of path2id
1777
    def _path2trans_id(self, path):
3363.17.22 by Aaron Bentley
Cache expensive operations
1778
        # We must not use None here, because that is a valid value to store.
1779
        trans_id = self._path2trans_id_cache.get(path, object)
1780
        if trans_id is not object:
1781
            return trans_id
3363.5.2 by Aaron Bentley
Massive simplification of path2id
1782
        segments = splitpath(path)
3363.2.19 by Aaron Bentley
Make PreviewTree.path2id correct
1783
        cur_parent = self._transform.root
3363.5.2 by Aaron Bentley
Massive simplification of path2id
1784
        for cur_segment in segments:
1785
            for child in self._all_children(cur_parent):
3363.17.22 by Aaron Bentley
Cache expensive operations
1786
                final_name = self._final_name_cache.get(child)
1787
                if final_name is None:
1788
                    final_name = self._transform.final_name(child)
1789
                    self._final_name_cache[child] = final_name
1790
                if final_name == cur_segment:
3363.2.19 by Aaron Bentley
Make PreviewTree.path2id correct
1791
                    cur_parent = child
1792
                    break
1793
            else:
3363.17.22 by Aaron Bentley
Cache expensive operations
1794
                self._path2trans_id_cache[path] = None
3363.5.2 by Aaron Bentley
Massive simplification of path2id
1795
                return None
3363.17.22 by Aaron Bentley
Cache expensive operations
1796
        self._path2trans_id_cache[path] = cur_parent
3363.5.2 by Aaron Bentley
Massive simplification of path2id
1797
        return cur_parent
3363.2.26 by Aaron Bentley
Get symlinks working
1798
3363.2.20 by Aaron Bentley
Split path2id into smaller pieces
1799
    def path2id(self, path):
3363.5.2 by Aaron Bentley
Massive simplification of path2id
1800
        return self._transform.final_file_id(self._path2trans_id(path))
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1801
1802
    def id2path(self, file_id):
1803
        trans_id = self._transform.trans_id_file_id(file_id)
1804
        try:
1805
            return self._final_paths._determine_path(trans_id)
1806
        except NoFinalPath:
1807
            raise errors.NoSuchId(self, file_id)
1808
3363.2.21 by Aaron Bentley
Implement iter_entries_by_dir
1809
    def _all_children(self, trans_id):
3363.17.22 by Aaron Bentley
Cache expensive operations
1810
        children = self._all_children_cache.get(trans_id)
1811
        if children is not None:
1812
            return children
3363.2.21 by Aaron Bentley
Implement iter_entries_by_dir
1813
        children = set(self._transform.iter_tree_children(trans_id))
1814
        # children in the _new_parent set are provided by _by_parent.
1815
        children.difference_update(self._transform._new_parent.keys())
1816
        children.update(self._by_parent.get(trans_id, []))
3363.17.22 by Aaron Bentley
Cache expensive operations
1817
        self._all_children_cache[trans_id] = children
3363.2.21 by Aaron Bentley
Implement iter_entries_by_dir
1818
        return children
1819
3363.12.2 by Aaron Bentley
Implement tree.iter_children to instead of adjusting InventoryEntry handling
1820
    def iter_children(self, file_id):
1821
        trans_id = self._transform.trans_id_file_id(file_id)
1822
        for child_trans_id in self._all_children(trans_id):
1823
            yield self._transform.final_file_id(child_trans_id)
1824
3363.13.1 by Aaron Bentley
Implement PreviewTree.extras
1825
    def extras(self):
1826
        possible_extras = set(self._transform.trans_id_tree_path(p) for p
1827
                              in self._transform._tree.extras())
3363.13.2 by Aaron Bentley
Test specific cases for PreviewTree.extras
1828
        possible_extras.update(self._transform._new_contents)
3363.13.1 by Aaron Bentley
Implement PreviewTree.extras
1829
        possible_extras.update(self._transform._removed_id)
1830
        for trans_id in possible_extras:
1831
            if self._transform.final_file_id(trans_id) is None:
1832
                yield self._final_paths._determine_path(trans_id)
1833
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1834
    def _make_inv_entries(self, ordered_entries, specific_file_ids=None,
1835
        yield_parents=False):
3363.2.21 by Aaron Bentley
Implement iter_entries_by_dir
1836
        for trans_id, parent_file_id in ordered_entries:
1837
            file_id = self._transform.final_file_id(trans_id)
1838
            if file_id is None:
1839
                continue
1840
            if (specific_file_ids is not None
1841
                and file_id not in specific_file_ids):
1842
                continue
1843
            try:
1844
                kind = self._transform.final_kind(trans_id)
1845
            except NoSuchFile:
1846
                kind = self._transform._tree.stored_kind(file_id)
1847
            new_entry = inventory.make_entry(
1848
                kind,
1849
                self._transform.final_name(trans_id),
1850
                parent_file_id, file_id)
1851
            yield new_entry, trans_id
1852
3363.11.1 by Aaron Bentley
Cheap implementation of list_files
1853
    def _list_files_by_dir(self):
3363.2.21 by Aaron Bentley
Implement iter_entries_by_dir
1854
        todo = [ROOT_PARENT]
1855
        ordered_ids = []
1856
        while len(todo) > 0:
1857
            parent = todo.pop()
1858
            parent_file_id = self._transform.final_file_id(parent)
3363.2.23 by Aaron Bentley
Fix iter_entries_by_dir ordering
1859
            children = list(self._all_children(parent))
1860
            paths = dict(zip(children, self._final_paths.get_paths(children)))
1861
            children.sort(key=paths.get)
3363.5.4 by Aaron Bentley
Fix iteration order of iter_entries_by_dir
1862
            todo.extend(reversed(children))
3363.2.21 by Aaron Bentley
Implement iter_entries_by_dir
1863
            for trans_id in children:
1864
                ordered_ids.append((trans_id, parent_file_id))
3363.11.1 by Aaron Bentley
Cheap implementation of list_files
1865
        return ordered_ids
1866
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1867
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
3363.11.1 by Aaron Bentley
Cheap implementation of list_files
1868
        # This may not be a maximally efficient implementation, but it is
1869
        # reasonably straightforward.  An implementation that grafts the
1870
        # TreeTransform changes onto the tree's iter_entries_by_dir results
1871
        # might be more efficient, but requires tricky inferences about stack
1872
        # position.
1873
        ordered_ids = self._list_files_by_dir()
3363.2.21 by Aaron Bentley
Implement iter_entries_by_dir
1874
        for entry, trans_id in self._make_inv_entries(ordered_ids,
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1875
            specific_file_ids, yield_parents=yield_parents):
3363.2.23 by Aaron Bentley
Fix iter_entries_by_dir ordering
1876
            yield unicode(self._final_paths.get_path(trans_id)), entry
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1877
4370.5.2 by Ian Clatworthy
extend list_files() with from_dir and recursive parameters
1878
    def _iter_entries_for_dir(self, dir_path):
1879
        """Return path, entry for items in a directory without recursing down."""
1880
        dir_file_id = self.path2id(dir_path)
1881
        ordered_ids = []
1882
        for file_id in self.iter_children(dir_file_id):
1883
            trans_id = self._transform.trans_id_file_id(file_id)
1884
            ordered_ids.append((trans_id, file_id))
1885
        for entry, trans_id in self._make_inv_entries(ordered_ids):
1886
            yield unicode(self._final_paths.get_path(trans_id)), entry
1887
1888
    def list_files(self, include_root=False, from_dir=None, recursive=True):
1889
        """See WorkingTree.list_files."""
3363.11.1 by Aaron Bentley
Cheap implementation of list_files
1890
        # XXX This should behave like WorkingTree.list_files, but is really
1891
        # more like RevisionTree.list_files.
4370.5.2 by Ian Clatworthy
extend list_files() with from_dir and recursive parameters
1892
        if recursive:
1893
            prefix = None
1894
            if from_dir:
1895
                prefix = from_dir + '/'
1896
            entries = self.iter_entries_by_dir()
1897
            for path, entry in entries:
1898
                if entry.name == '' and not include_root:
1899
                    continue
1900
                if prefix:
1901
                    if not path.startswith(prefix):
1902
                        continue
1903
                    path = path[len(prefix):]
1904
                yield path, 'V', entry.kind, entry.file_id, entry
1905
        else:
1906
            if from_dir is None and include_root is True:
1907
                root_entry = inventory.make_entry('directory', '',
1908
                    ROOT_PARENT, self.get_root_id())
1909
                yield '', 'V', 'directory', root_entry.file_id, root_entry
1910
            entries = self._iter_entries_for_dir(from_dir or '')
1911
            for path, entry in entries:
1912
                yield path, 'V', entry.kind, entry.file_id, entry
3363.11.1 by Aaron Bentley
Cheap implementation of list_files
1913
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1914
    def kind(self, file_id):
1915
        trans_id = self._transform.trans_id_file_id(file_id)
1916
        return self._transform.final_kind(trans_id)
1917
1918
    def stored_kind(self, file_id):
3363.2.36 by Aaron Bentley
Fix PreviewTree.stored_kind
1919
        trans_id = self._transform.trans_id_file_id(file_id)
1920
        try:
1921
            return self._transform._new_contents[trans_id]
1922
        except KeyError:
1923
            return self._transform._tree.stored_kind(file_id)
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1924
1925
    def get_file_mtime(self, file_id, path=None):
1926
        """See Tree.get_file_mtime"""
1927
        if not self._content_change(file_id):
4635.1.1 by Aaron Bentley
Fix OSError with renamed files in PreviewTree.
1928
            return self._transform._tree.get_file_mtime(file_id)
3363.2.9 by Aaron Bentley
Fix up some refactorings
1929
        return self._stat_limbo_file(file_id).st_mtime
3363.2.7 by Aaron Bentley
Implement alterntative-to-inventory tests
1930
3363.14.5 by Aaron Bentley
Add _file_size for comparison
1931
    def _file_size(self, entry, stat_value):
1932
        return self.get_file_size(entry.file_id)
1933
3363.2.7 by Aaron Bentley
Implement alterntative-to-inventory tests
1934
    def get_file_size(self, file_id):
3363.3.3 by Aaron Bentley
Updates from review
1935
        """See Tree.get_file_size"""
3363.2.7 by Aaron Bentley
Implement alterntative-to-inventory tests
1936
        if self.kind(file_id) == 'file':
1937
            return self._transform._tree.get_file_size(file_id)
3363.3.3 by Aaron Bentley
Updates from review
1938
        else:
1939
            return None
3363.2.7 by Aaron Bentley
Implement alterntative-to-inventory tests
1940
1941
    def get_file_sha1(self, file_id, path=None, stat_value=None):
3363.15.4 by Aaron Bentley
Implement PreviewTree.get_file_sha1 properly
1942
        trans_id = self._transform.trans_id_file_id(file_id)
1943
        kind = self._transform._new_contents.get(trans_id)
1944
        if kind is None:
1945
            return self._transform._tree.get_file_sha1(file_id)
1946
        if kind == 'file':
1947
            fileobj = self.get_file(file_id)
1948
            try:
1949
                return sha_file(fileobj)
1950
            finally:
1951
                fileobj.close()
3363.2.7 by Aaron Bentley
Implement alterntative-to-inventory tests
1952
1953
    def is_executable(self, file_id, path=None):
3363.14.8 by Aaron Bentley
Fix more tests
1954
        if file_id is None:
1955
            return False
3363.2.37 by Aaron Bentley
Fix is_executable
1956
        trans_id = self._transform.trans_id_file_id(file_id)
1957
        try:
1958
            return self._transform._new_executability[trans_id]
1959
        except KeyError:
3363.17.17 by Aaron Bentley
Start testing merging PreviewTree as OTHER
1960
            try:
1961
                return self._transform._tree.is_executable(file_id, path)
1962
            except OSError, e:
1963
                if e.errno == errno.ENOENT:
1964
                    return False
1965
                raise
3363.17.18 by Aaron Bentley
Fix is_executable for PreviewTree
1966
            except errors.NoSuchId:
1967
                return False
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1968
1969
    def path_content_summary(self, path):
3363.6.1 by Aaron Bentley
Merge with preview-tree-changed
1970
        trans_id = self._path2trans_id(path)
3363.2.27 by Aaron Bentley
Make path_content_summary a core API
1971
        tt = self._transform
3363.6.1 by Aaron Bentley
Merge with preview-tree-changed
1972
        tree_path = tt._tree_id_paths.get(trans_id)
3363.2.27 by Aaron Bentley
Make path_content_summary a core API
1973
        kind = tt._new_contents.get(trans_id)
1974
        if kind is None:
3363.6.1 by Aaron Bentley
Merge with preview-tree-changed
1975
            if tree_path is None or trans_id in tt._removed_contents:
3363.2.27 by Aaron Bentley
Make path_content_summary a core API
1976
                return 'missing', None, None, None
1977
            summary = tt._tree.path_content_summary(tree_path)
1978
            kind, size, executable, link_or_sha1 = summary
1979
        else:
1980
            link_or_sha1 = None
1981
            limbo_name = tt._limbo_name(trans_id)
1982
            if trans_id in tt._new_reference_revision:
1983
                kind = 'tree-reference'
1984
            if kind == 'file':
1985
                statval = os.lstat(limbo_name)
1986
                size = statval.st_size
1987
                if not supports_executable():
4789.16.1 by John Arbash Meinel
Tweak the PreviewTree.path_content_summary tests for executablity on windows.
1988
                    executable = False
3363.2.27 by Aaron Bentley
Make path_content_summary a core API
1989
                else:
1990
                    executable = statval.st_mode & S_IEXEC
1991
            else:
1992
                size = None
1993
                executable = None
1994
            if kind == 'symlink':
4095.3.1 by Vincent Ladeuil
Fix #339055 and #277444 by handling non ascii symlink targets.
1995
                link_or_sha1 = os.readlink(limbo_name).decode(osutils._fs_enc)
4789.16.1 by John Arbash Meinel
Tweak the PreviewTree.path_content_summary tests for executablity on windows.
1996
        executable = tt._new_executability.get(trans_id, executable)
3363.2.27 by Aaron Bentley
Make path_content_summary a core API
1997
        return kind, size, executable, link_or_sha1
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
1998
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1999
    def iter_changes(self, from_tree, include_unchanged=False,
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
2000
                      specific_files=None, pb=None, extra_trees=None,
2001
                      require_versioned=True, want_unversioned=False):
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2002
        """See InterTree.iter_changes.
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
2003
3363.19.1 by Aaron Bentley
Make PreviewTree.iter_changes accept all options.
2004
        This has a fast path that is only used when the from_tree matches
2005
        the transform tree, and no fancy options are supplied.
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
2006
        """
3363.19.1 by Aaron Bentley
Make PreviewTree.iter_changes accept all options.
2007
        if (from_tree is not self._transform._tree or include_unchanged or
2008
            specific_files or want_unversioned):
3363.14.1 by Aaron Bentley
Update to support comparison
2009
            return tree.InterTree(from_tree, self).iter_changes(
2010
                include_unchanged=include_unchanged,
2011
                specific_files=specific_files,
2012
                pb=pb,
2013
                extra_trees=extra_trees,
2014
                require_versioned=require_versioned,
2015
                want_unversioned=want_unversioned)
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
2016
        if want_unversioned:
2017
            raise ValueError('want_unversioned is not supported')
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2018
        return self._transform.iter_changes()
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
2019
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
2020
    def get_file(self, file_id, path=None):
3008.1.20 by Aaron Bentley
Add some docstrings
2021
        """See Tree.get_file"""
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
2022
        if not self._content_change(file_id):
2023
            return self._transform._tree.get_file(file_id, path)
3008.1.3 by Aaron Bentley
Support basic diff
2024
        trans_id = self._transform.trans_id_file_id(file_id)
2025
        name = self._transform._limbo_name(trans_id)
2026
        return open(name, 'rb')
2027
4354.4.5 by Aaron Bentley
Ensure Tree.get_file_with_stat is provided.
2028
    def get_file_with_stat(self, file_id, path=None):
4354.4.2 by Aaron Bentley
Allow committing a file add to a PreviewTree.
2029
        return self.get_file(file_id, path), None
2030
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
2031
    def annotate_iter(self, file_id,
2032
                      default_revision=_mod_revision.CURRENT_REVISION):
4634.57.1 by Aaron Bentley
Cache iter_changes values instead of re-running.
2033
        changes = self._iter_changes_cache.get(file_id)
3363.2.35 by Aaron Bentley
Update to get tests passing
2034
        if changes is None:
2035
            get_old = True
3363.2.33 by Aaron Bentley
Implement PreviewTree.annotate_iter
2036
        else:
3363.2.35 by Aaron Bentley
Update to get tests passing
2037
            changed_content, versioned, kind = (changes[2], changes[3],
2038
                                                changes[6])
2039
            if kind[1] is None:
2040
                return None
2041
            get_old = (kind[0] == 'file' and versioned[0])
2042
        if get_old:
3363.2.33 by Aaron Bentley
Implement PreviewTree.annotate_iter
2043
            old_annotation = self._transform._tree.annotate_iter(file_id,
2044
                default_revision=default_revision)
3363.2.35 by Aaron Bentley
Update to get tests passing
2045
        else:
2046
            old_annotation = []
2047
        if changes is None:
2048
            return old_annotation
3363.2.33 by Aaron Bentley
Implement PreviewTree.annotate_iter
2049
        if not changed_content:
2050
            return old_annotation
4454.3.70 by John Arbash Meinel
Some comments about the PreviewTree.annotate_iter implementation.
2051
        # TODO: This is doing something similar to what WT.annotate_iter is
2052
        #       doing, however it fails slightly because it doesn't know what
2053
        #       the *other* revision_id is, so it doesn't know how to give the
2054
        #       other as the origin for some lines, they all get
2055
        #       'default_revision'
2056
        #       It would be nice to be able to use the new Annotator based
2057
        #       approach, as well.
3363.2.33 by Aaron Bentley
Implement PreviewTree.annotate_iter
2058
        return annotate.reannotate([old_annotation],
2059
                                   self.get_file(file_id).readlines(),
2060
                                   default_revision)
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
2061
3228.1.1 by James Henstridge
* Add get_symlink_target() method to bzrlib.transform._PreviewTree, so
2062
    def get_symlink_target(self, file_id):
2063
        """See Tree.get_symlink_target"""
3363.2.29 by Aaron Bentley
Remove unneeded changes
2064
        if not self._content_change(file_id):
2065
            return self._transform._tree.get_symlink_target(file_id)
3228.1.1 by James Henstridge
* Add get_symlink_target() method to bzrlib.transform._PreviewTree, so
2066
        trans_id = self._transform.trans_id_file_id(file_id)
3363.2.29 by Aaron Bentley
Remove unneeded changes
2067
        name = self._transform._limbo_name(trans_id)
4241.14.16 by Vincent Ladeuil
Fix _PreviewTree.get_symlink_target for unicode symlinks.
2068
        return osutils.readlink(name)
3228.1.1 by James Henstridge
* Add get_symlink_target() method to bzrlib.transform._PreviewTree, so
2069
3363.9.9 by Aaron Bentley
Implement walkdirs in terms of TreeTransform
2070
    def walkdirs(self, prefix=''):
2071
        pending = [self._transform.root]
2072
        while len(pending) > 0:
2073
            parent_id = pending.pop()
2074
            children = []
2075
            subdirs = []
2076
            prefix = prefix.rstrip('/')
2077
            parent_path = self._final_paths.get_path(parent_id)
2078
            parent_file_id = self._transform.final_file_id(parent_id)
2079
            for child_id in self._all_children(parent_id):
2080
                path_from_root = self._final_paths.get_path(child_id)
2081
                basename = self._transform.final_name(child_id)
3363.9.10 by Aaron Bentley
Handle dangling file-ids correctly
2082
                file_id = self._transform.final_file_id(child_id)
2083
                try:
2084
                    kind = self._transform.final_kind(child_id)
2085
                    versioned_kind = kind
2086
                except NoSuchFile:
2087
                    kind = 'unknown'
2088
                    versioned_kind = self._transform._tree.stored_kind(file_id)
2089
                if versioned_kind == 'directory':
3363.9.9 by Aaron Bentley
Implement walkdirs in terms of TreeTransform
2090
                    subdirs.append(child_id)
2091
                children.append((path_from_root, basename, kind, None,
3363.9.10 by Aaron Bentley
Handle dangling file-ids correctly
2092
                                 file_id, versioned_kind))
3363.9.9 by Aaron Bentley
Implement walkdirs in terms of TreeTransform
2093
            children.sort()
2094
            if parent_path.startswith(prefix):
2095
                yield (parent_path, parent_file_id), children
2096
            pending.extend(sorted(subdirs, key=self._final_paths.get_path,
2097
                                  reverse=True))
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
2098
2099
    def get_parent_ids(self):
3571.1.1 by Aaron Bentley
Allow set/get of parent_ids in PreviewTree
2100
        return self._parent_ids
2101
2102
    def set_parent_ids(self, parent_ids):
2103
        self._parent_ids = parent_ids
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
2104
2105
    def get_revision_tree(self, revision_id):
2106
        return self._transform._tree.get_revision_tree(revision_id)
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
2107
2108
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
2109
def joinpath(parent, child):
1534.7.40 by Aaron Bentley
Updated docs
2110
    """Join tree-relative paths, handling the tree root specially"""
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
2111
    if parent is None or parent == "":
2112
        return child
2113
    else:
1534.7.166 by Aaron Bentley
Swapped os.path.join for pathjoin everywhere
2114
        return pathjoin(parent, child)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
2115
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
2116
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
2117
class FinalPaths(object):
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
2118
    """Make path calculation cheap by memoizing paths.
1534.7.21 by Aaron Bentley
Updated docstrings
2119
2120
    The underlying tree must not be manipulated between calls, or else
2121
    the results will likely be incorrect.
2122
    """
1534.7.132 by Aaron Bentley
Got cooked conflicts working
2123
    def __init__(self, transform):
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
2124
        object.__init__(self)
2125
        self._known_paths = {}
1534.7.33 by Aaron Bentley
Fixed naming
2126
        self.transform = transform
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
2127
2128
    def _determine_path(self, trans_id):
4526.9.23 by Robert Collins
Change the tree transform test_first_commit test to set a root id in the new tree, and workaround an apparent bug in TreeTransform._determine_path.
2129
        if (trans_id == self.transform.root or trans_id == ROOT_PARENT):
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
2130
            return ""
1534.7.33 by Aaron Bentley
Fixed naming
2131
        name = self.transform.final_name(trans_id)
2132
        parent_id = self.transform.final_parent(trans_id)
1534.7.132 by Aaron Bentley
Got cooked conflicts working
2133
        if parent_id == self.transform.root:
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
2134
            return name
2135
        else:
1534.7.166 by Aaron Bentley
Swapped os.path.join for pathjoin everywhere
2136
            return pathjoin(self.get_path(parent_id), name)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
2137
2138
    def get_path(self, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
2139
        """Find the final path associated with a trans_id"""
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
2140
        if trans_id not in self._known_paths:
2141
            self._known_paths[trans_id] = self._determine_path(trans_id)
2142
        return self._known_paths[trans_id]
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
2143
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
2144
    def get_paths(self, trans_ids):
2145
        return [(self.get_path(t), t) for t in trans_ids]
2146
2147
3006.2.2 by Alexander Belchenko
tests added.
2148
1534.7.30 by Aaron Bentley
Factored out topological id sorting
2149
def topology_sorted_ids(tree):
1534.7.40 by Aaron Bentley
Updated docs
2150
    """Determine the topological order of the ids in a tree"""
1534.7.30 by Aaron Bentley
Factored out topological id sorting
2151
    file_ids = list(tree)
2152
    file_ids.sort(key=tree.id2path)
2153
    return file_ids
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
2154
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2155
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
2156
def build_tree(tree, wt, accelerator_tree=None, hardlink=False,
3453.2.6 by Aaron Bentley
Rename mutate_tree to delta_from_tree, add comment
2157
               delta_from_tree=False):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2158
    """Create working tree for a branch, using a TreeTransform.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2159
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2160
    This function should be used on empty trees, having a tree root at most.
2161
    (see merge and revert functionality for working with existing trees)
2162
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2163
    Existing files are handled like so:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2164
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2165
    - Existing bzrdirs take precedence over creating new items.  They are
2166
      created as '%s.diverted' % name.
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2167
    - Otherwise, if the content on disk matches the content we are building,
2168
      it is silently replaced.
2169
    - Otherwise, conflict resolution will move the old file to 'oldname.moved'.
3123.5.17 by Aaron Bentley
Update docs
2170
2171
    :param tree: The tree to convert wt into a copy of
2172
    :param wt: The working tree that files will be placed into
2173
    :param accelerator_tree: A tree which can be used for retrieving file
2174
        contents more quickly than tree itself, i.e. a workingtree.  tree
2175
        will be used for cases where accelerator_tree's content is different.
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2176
    :param hardlink: If true, hard-link files to accelerator_tree, where
3136.1.4 by Aaron Bentley
Avoid id2abspath calls
2177
        possible.  accelerator_tree must implement abspath, i.e. be a
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2178
        working tree.
3453.2.6 by Aaron Bentley
Rename mutate_tree to delta_from_tree, add comment
2179
    :param delta_from_tree: If true, build_tree may use the input Tree to
2180
        generate the inventory delta.
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2181
    """
2255.7.51 by Robert Collins
Lock build_tree trees in write-first order, to support older formats that dont do lock_tree_write nicely.
2182
    wt.lock_tree_write()
2255.7.49 by Robert Collins
Lock trees passed in to build_tree.
2183
    try:
2255.7.51 by Robert Collins
Lock build_tree trees in write-first order, to support older formats that dont do lock_tree_write nicely.
2184
        tree.lock_read()
2255.7.49 by Robert Collins
Lock trees passed in to build_tree.
2185
        try:
3123.5.1 by Aaron Bentley
Make build-tree able to use an additional 'accelerator' tree
2186
            if accelerator_tree is not None:
2187
                accelerator_tree.lock_read()
2188
            try:
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
2189
                return _build_tree(tree, wt, accelerator_tree, hardlink,
3453.2.6 by Aaron Bentley
Rename mutate_tree to delta_from_tree, add comment
2190
                                   delta_from_tree)
3123.5.1 by Aaron Bentley
Make build-tree able to use an additional 'accelerator' tree
2191
            finally:
2192
                if accelerator_tree is not None:
2193
                    accelerator_tree.unlock()
2255.7.49 by Robert Collins
Lock trees passed in to build_tree.
2194
        finally:
2255.7.51 by Robert Collins
Lock build_tree trees in write-first order, to support older formats that dont do lock_tree_write nicely.
2195
            tree.unlock()
2255.7.49 by Robert Collins
Lock trees passed in to build_tree.
2196
    finally:
2255.7.51 by Robert Collins
Lock build_tree trees in write-first order, to support older formats that dont do lock_tree_write nicely.
2197
        wt.unlock()
2255.7.49 by Robert Collins
Lock trees passed in to build_tree.
2198
3006.2.2 by Alexander Belchenko
tests added.
2199
3453.2.6 by Aaron Bentley
Rename mutate_tree to delta_from_tree, add comment
2200
def _build_tree(tree, wt, accelerator_tree, hardlink, delta_from_tree):
2255.7.49 by Robert Collins
Lock trees passed in to build_tree.
2201
    """See build_tree."""
3146.8.17 by Aaron Bentley
Change to explicit file_id list
2202
    for num, _unused in enumerate(wt.all_file_ids()):
3146.8.16 by Aaron Bentley
Updates from review
2203
        if num > 0:  # more than just a root
2204
            raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
3453.2.5 by Aaron Bentley
Avoid statting tons of non-existant files when building from scratch
2205
    existing_files = set()
2206
    for dir, files in wt.walkdirs():
2207
        existing_files.update(f[0] for f in files)
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
2208
    file_trans_id = {}
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
2209
    top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2210
    pp = ProgressPhase("Build phase", 2, top_pb)
2255.2.183 by Martin Pool
add missing _must_be_locked and a better message
2211
    if tree.inventory.root is not None:
2502.1.6 by Aaron Bentley
Update from review comments
2212
        # This is kind of a hack: we should be altering the root
2213
        # as part of the regular tree shape diff logic.
2214
        # The conditional test here is to avoid doing an
2255.2.194 by Robert Collins
[BROKEN] Many updates to stop using experimental formats in tests.
2215
        # expensive operation (flush) every time the root id
2216
        # is set within the tree, nor setting the root and thus
2217
        # marking the tree as dirty, because we use two different
2218
        # idioms here: tree interfaces and inventory interfaces.
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
2219
        if wt.get_root_id() != tree.get_root_id():
2220
            wt.set_root_id(tree.get_root_id())
2255.2.194 by Robert Collins
[BROKEN] Many updates to stop using experimental formats in tests.
2221
            wt.flush()
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
2222
    tt = TreeTransform(wt)
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2223
    divert = set()
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
2224
    try:
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
2225
        pp.next_phase()
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2226
        file_trans_id[wt.get_root_id()] = \
2227
            tt.trans_id_tree_file_id(wt.get_root_id())
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
2228
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
2229
        try:
2708.1.2 by Aaron Bentley
Use extract_files_bytes for build_tree
2230
            deferred_contents = []
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2231
            num = 0
3483.1.1 by Ian Clatworthy
minor _build_tree cleanups
2232
            total = len(tree.inventory)
3453.2.6 by Aaron Bentley
Rename mutate_tree to delta_from_tree, add comment
2233
            if delta_from_tree:
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
2234
                precomputed_delta = []
2235
            else:
2236
                precomputed_delta = None
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2237
            for num, (tree_path, entry) in \
2238
                enumerate(tree.inventory.iter_entries_by_dir()):
3483.1.1 by Ian Clatworthy
minor _build_tree cleanups
2239
                pb.update("Building tree", num - len(deferred_contents), total)
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
2240
                if entry.parent_id is None:
2241
                    continue
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2242
                reparent = False
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2243
                file_id = entry.file_id
3453.2.6 by Aaron Bentley
Rename mutate_tree to delta_from_tree, add comment
2244
                if delta_from_tree:
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
2245
                    precomputed_delta.append((None, tree_path, file_id, entry))
3453.2.5 by Aaron Bentley
Avoid statting tons of non-existant files when building from scratch
2246
                if tree_path in existing_files:
2247
                    target_path = wt.abspath(tree_path)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2248
                    kind = file_kind(target_path)
2249
                    if kind == "directory":
2250
                        try:
2251
                            bzrdir.BzrDir.open(target_path)
2252
                        except errors.NotBranchError:
2253
                            pass
2254
                        else:
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2255
                            divert.add(file_id)
2256
                    if (file_id not in divert and
2257
                        _content_match(tree, entry, file_id, kind,
2258
                        target_path)):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2259
                        tt.delete_contents(tt.trans_id_tree_path(tree_path))
2260
                        if kind == 'directory':
2261
                            reparent = True
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
2262
                parent_id = file_trans_id[entry.parent_id]
2708.1.8 by Aaron Bentley
rename extract_files_bytest to iter_files_bytes, fix build_tree / progress
2263
                if entry.kind == 'file':
2708.1.2 by Aaron Bentley
Use extract_files_bytes for build_tree
2264
                    # We *almost* replicate new_by_entry, so that we can defer
2265
                    # getting the file text, and get them all at once.
2266
                    trans_id = tt.create_path(entry.name, parent_id)
2708.1.8 by Aaron Bentley
rename extract_files_bytest to iter_files_bytes, fix build_tree / progress
2267
                    file_trans_id[file_id] = trans_id
3483.1.1 by Ian Clatworthy
minor _build_tree cleanups
2268
                    tt.version_file(file_id, trans_id)
2269
                    executable = tree.is_executable(file_id, tree_path)
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
2270
                    if executable:
2708.1.8 by Aaron Bentley
rename extract_files_bytest to iter_files_bytes, fix build_tree / progress
2271
                        tt.set_executability(executable, trans_id)
3368.2.20 by Ian Clatworthy
move filtering up the layers in TreeTransform
2272
                    trans_data = (trans_id, tree_path)
3368.2.27 by Ian Clatworthy
merge bzr.dev r3564
2273
                    deferred_contents.append((file_id, trans_data))
2708.1.2 by Aaron Bentley
Use extract_files_bytes for build_tree
2274
                else:
2275
                    file_trans_id[file_id] = new_by_entry(tt, entry, parent_id,
2276
                                                          tree)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2277
                if reparent:
2278
                    new_trans_id = file_trans_id[file_id]
2279
                    old_parent = tt.trans_id_tree_path(tree_path)
2280
                    _reparent_children(tt, old_parent, new_trans_id)
3136.1.11 by Aaron Bentley
Updates from review
2281
            offset = num + 1 - len(deferred_contents)
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2282
            _create_files(tt, tree, deferred_contents, pb, offset,
2283
                          accelerator_tree, hardlink)
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
2284
        finally:
2285
            pb.finished()
2286
        pp.next_phase()
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2287
        divert_trans = set(file_trans_id[f] for f in divert)
2288
        resolver = lambda t, c: resolve_checkout(t, c, divert_trans)
2289
        raw_conflicts = resolve_conflicts(tt, pass_func=resolver)
3453.2.4 by Aaron Bentley
Disable fast-path when conflicts are encountered
2290
        if len(raw_conflicts) > 0:
2291
            precomputed_delta = None
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2292
        conflicts = cook_conflicts(raw_conflicts, tt)
2293
        for conflict in conflicts:
2294
            warning(conflict)
2295
        try:
2296
            wt.add_conflicts(conflicts)
2297
        except errors.UnsupportedOperation:
2298
            pass
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
2299
        result = tt.apply(no_conflicts=True,
2300
                          precomputed_delta=precomputed_delta)
1534.7.47 by Aaron Bentley
Started work on 'revert'
2301
    finally:
2302
        tt.finalize()
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
2303
        top_pb.finished()
2502.1.5 by Aaron Bentley
Cleanup
2304
    return result
1534.7.47 by Aaron Bentley
Started work on 'revert'
2305
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2306
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2307
def _create_files(tt, tree, desired_files, pb, offset, accelerator_tree,
2308
                  hardlink):
2309
    total = len(desired_files) + offset
4208.4.1 by Ian Clatworthy
eol conversion support
2310
    wt = tt._tree
3123.5.5 by Aaron Bentley
Split out _iter_files_bytes_accelerated
2311
    if accelerator_tree is None:
2312
        new_desired_files = desired_files
2313
    else:
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2314
        iter = accelerator_tree.iter_changes(tree, include_unchanged=True)
4826.1.1 by Andrew Bennetts
Quick change to allow hardlinking from a tree that supports content filtering for files that are unaffected by filters.
2315
        unchanged = [(f, p[1]) for (f, p, c, v, d, n, k, e)
2316
                     in iter if not (c or e[0] != e[1])]
2317
        if accelerator_tree.supports_content_filtering():
2318
            unchanged = [(f, p) for (f, p) in unchanged
2319
                         if not accelerator_tree.iter_search_rules([p]).next()]
2320
        unchanged = dict(unchanged)
3123.5.5 by Aaron Bentley
Split out _iter_files_bytes_accelerated
2321
        new_desired_files = []
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2322
        count = 0
3368.2.20 by Ian Clatworthy
move filtering up the layers in TreeTransform
2323
        for file_id, (trans_id, tree_path) in desired_files:
3123.5.13 by Aaron Bentley
Accelerate further by using iter_changes
2324
            accelerator_path = unchanged.get(file_id)
3123.5.12 by Aaron Bentley
Try to optimize iter_changes_accelerated
2325
            if accelerator_path is None:
3368.2.20 by Ian Clatworthy
move filtering up the layers in TreeTransform
2326
                new_desired_files.append((file_id, (trans_id, tree_path)))
3123.5.12 by Aaron Bentley
Try to optimize iter_changes_accelerated
2327
                continue
3136.1.11 by Aaron Bentley
Updates from review
2328
            pb.update('Adding file contents', count + offset, total)
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2329
            if hardlink:
3136.1.4 by Aaron Bentley
Avoid id2abspath calls
2330
                tt.create_hardlink(accelerator_tree.abspath(accelerator_path),
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2331
                                   trans_id)
2332
            else:
2333
                contents = accelerator_tree.get_file(file_id, accelerator_path)
4208.4.1 by Ian Clatworthy
eol conversion support
2334
                if wt.supports_content_filtering():
2335
                    filters = wt._content_filter_stack(tree_path)
3368.2.45 by Ian Clatworthy
add and use supports_content_filtering API
2336
                    contents = filtered_output_bytes(contents, filters,
2337
                        ContentFilterContext(tree_path, tree))
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2338
                try:
2339
                    tt.create_file(contents, trans_id)
2340
                finally:
3368.2.29 by Ian Clatworthy
access rules via get_special_file to fix recursion bug
2341
                    try:
2342
                        contents.close()
2343
                    except AttributeError:
2344
                        # after filtering, contents may no longer be file-like
2345
                        pass
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2346
            count += 1
2347
        offset += count
3368.2.20 by Ian Clatworthy
move filtering up the layers in TreeTransform
2348
    for count, ((trans_id, tree_path), contents) in enumerate(
2349
            tree.iter_files_bytes(new_desired_files)):
4208.4.1 by Ian Clatworthy
eol conversion support
2350
        if wt.supports_content_filtering():
2351
            filters = wt._content_filter_stack(tree_path)
3368.2.45 by Ian Clatworthy
add and use supports_content_filtering API
2352
            contents = filtered_output_bytes(contents, filters,
2353
                ContentFilterContext(tree_path, tree))
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2354
        tt.create_file(contents, trans_id)
3136.1.11 by Aaron Bentley
Updates from review
2355
        pb.update('Adding file contents', count + offset, total)
3123.5.5 by Aaron Bentley
Split out _iter_files_bytes_accelerated
2356
2357
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2358
def _reparent_children(tt, old_parent, new_parent):
2359
    for child in tt.iter_tree_children(old_parent):
2360
        tt.adjust_path(tt.final_name(child), new_parent, child)
2361
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
2362
def _reparent_transform_children(tt, old_parent, new_parent):
2363
    by_parent = tt.by_parent()
2364
    for child in by_parent[old_parent]:
2365
        tt.adjust_path(tt.final_name(child), new_parent, child)
1551.19.32 by Aaron Bentley
Don't traceback when adding files to a deleted root (abentley, #210092)
2366
    return by_parent[old_parent]
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2367
2368
def _content_match(tree, entry, file_id, kind, target_path):
2369
    if entry.kind != kind:
2370
        return False
2371
    if entry.kind == "directory":
2372
        return True
2373
    if entry.kind == "file":
2374
        if tree.get_file(file_id).read() == file(target_path, 'rb').read():
2375
            return True
2376
    elif entry.kind == "symlink":
2377
        if tree.get_symlink_target(file_id) == os.readlink(target_path):
2378
            return True
2379
    return False
2380
2381
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2382
def resolve_checkout(tt, conflicts, divert):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2383
    new_conflicts = set()
2384
    for c_type, conflict in ((c[0], c) for c in conflicts):
2385
        # Anything but a 'duplicate' would indicate programmer error
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2386
        if c_type != 'duplicate':
2387
            raise AssertionError(c_type)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2388
        # Now figure out which is new and which is old
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2389
        if tt.new_contents(conflict[1]):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2390
            new_file = conflict[1]
2391
            old_file = conflict[2]
2392
        else:
2393
            new_file = conflict[2]
2394
            old_file = conflict[1]
2395
2396
        # We should only get here if the conflict wasn't completely
2397
        # resolved
2398
        final_parent = tt.final_parent(old_file)
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2399
        if new_file in divert:
2400
            new_name = tt.final_name(old_file)+'.diverted'
2401
            tt.adjust_path(new_name, final_parent, new_file)
2402
            new_conflicts.add((c_type, 'Diverted to',
2403
                               new_file, old_file))
2404
        else:
2405
            new_name = tt.final_name(old_file)+'.moved'
2406
            tt.adjust_path(new_name, final_parent, old_file)
2407
            new_conflicts.add((c_type, 'Moved existing file to',
2408
                               old_file, new_file))
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2409
    return new_conflicts
2410
2411
1534.7.47 by Aaron Bentley
Started work on 'revert'
2412
def new_by_entry(tt, entry, parent_id, tree):
1534.7.157 by Aaron Bentley
Added more docs
2413
    """Create a new file according to its inventory entry"""
1534.7.47 by Aaron Bentley
Started work on 'revert'
2414
    name = entry.name
2415
    kind = entry.kind
2416
    if kind == 'file':
1534.7.79 by Aaron Bentley
Stopped calling get_file_lines on WorkingTree
2417
        contents = tree.get_file(entry.file_id).readlines()
1534.7.47 by Aaron Bentley
Started work on 'revert'
2418
        executable = tree.is_executable(entry.file_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2419
        return tt.new_file(name, parent_id, contents, entry.file_id,
1534.7.47 by Aaron Bentley
Started work on 'revert'
2420
                           executable)
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
2421
    elif kind in ('directory', 'tree-reference'):
2422
        trans_id = tt.new_directory(name, parent_id, entry.file_id)
2423
        if kind == 'tree-reference':
2424
            tt.set_tree_reference(entry.reference_revision, trans_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2425
        return trans_id
1534.7.47 by Aaron Bentley
Started work on 'revert'
2426
    elif kind == 'symlink':
1534.7.183 by Aaron Bentley
Fixed build_tree with symlinks
2427
        target = tree.get_symlink_target(entry.file_id)
2428
        return tt.new_symlink(name, parent_id, target, entry.file_id)
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
2429
    else:
2430
        raise errors.BadFileKindError(name, kind)
1534.7.47 by Aaron Bentley
Started work on 'revert'
2431
3006.2.2 by Alexander Belchenko
tests added.
2432
3363.17.26 by Aaron Bentley
Deprecate create_by_entry
2433
@deprecated_function(deprecated_in((1, 9, 0)))
1534.7.117 by Aaron Bentley
Simplified permission handling of existing files in transform.
2434
def create_by_entry(tt, entry, tree, trans_id, lines=None, mode_id=None):
3363.17.26 by Aaron Bentley
Deprecate create_by_entry
2435
    """Create new file contents according to an inventory entry.
2436
2437
    DEPRECATED.  Use create_from_tree instead.
2438
    """
1534.7.47 by Aaron Bentley
Started work on 'revert'
2439
    if entry.kind == "file":
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
2440
        if lines is None:
1534.7.97 by Aaron Bentley
Ensured foo.BASE is a directory if there's a conflict
2441
            lines = tree.get_file(entry.file_id).readlines()
1534.7.117 by Aaron Bentley
Simplified permission handling of existing files in transform.
2442
        tt.create_file(lines, trans_id, mode_id=mode_id)
1534.7.47 by Aaron Bentley
Started work on 'revert'
2443
    elif entry.kind == "symlink":
1534.7.101 by Aaron Bentley
Got conflicts on symlinks working properly
2444
        tt.create_symlink(tree.get_symlink_target(entry.file_id), trans_id)
1534.7.47 by Aaron Bentley
Started work on 'revert'
2445
    elif entry.kind == "directory":
1534.7.51 by Aaron Bentley
New approach to revert
2446
        tt.create_directory(trans_id)
1534.7.47 by Aaron Bentley
Started work on 'revert'
2447
3006.2.2 by Alexander Belchenko
tests added.
2448
4443.2.1 by Ian Clatworthy
apply content filters when merging new files
2449
def create_from_tree(tt, trans_id, tree, file_id, bytes=None,
2450
    filter_tree_path=None):
2451
    """Create new file contents according to tree contents.
2452
    
2453
    :param filter_tree_path: the tree path to use to lookup
2454
      content filters to apply to the bytes output in the working tree.
2455
      This only applies if the working tree supports content filtering.
2456
    """
3363.17.24 by Aaron Bentley
Implement create_by_tree
2457
    kind = tree.kind(file_id)
2458
    if kind == 'directory':
2459
        tt.create_directory(trans_id)
2460
    elif kind == "file":
3363.17.25 by Aaron Bentley
remove get_inventory_entry, replace with create_from_tree
2461
        if bytes is None:
2462
            tree_file = tree.get_file(file_id)
2463
            try:
2464
                bytes = tree_file.readlines()
2465
            finally:
2466
                tree_file.close()
4443.2.1 by Ian Clatworthy
apply content filters when merging new files
2467
        wt = tt._tree
2468
        if wt.supports_content_filtering() and filter_tree_path is not None:
2469
            filters = wt._content_filter_stack(filter_tree_path)
2470
            bytes = filtered_output_bytes(bytes, filters,
2471
                ContentFilterContext(filter_tree_path, tree))
3363.17.25 by Aaron Bentley
remove get_inventory_entry, replace with create_from_tree
2472
        tt.create_file(bytes, trans_id)
3363.17.24 by Aaron Bentley
Implement create_by_tree
2473
    elif kind == "symlink":
2474
        tt.create_symlink(tree.get_symlink_target(file_id), trans_id)
3363.17.27 by Aaron Bentley
Add default case for create_from_tree
2475
    else:
2476
        raise AssertionError('Unknown kind %r' % kind)
3363.17.24 by Aaron Bentley
Implement create_by_tree
2477
2478
1534.7.89 by Aaron Bentley
Handle all content types in three-way
2479
def create_entry_executability(tt, entry, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
2480
    """Set the executability of a trans_id according to an inventory entry"""
1534.7.89 by Aaron Bentley
Handle all content types in three-way
2481
    if entry.kind == "file":
2482
        tt.set_executability(entry.executable, trans_id)
1534.7.47 by Aaron Bentley
Started work on 'revert'
2483
1534.7.157 by Aaron Bentley
Added more docs
2484
1534.10.28 by Aaron Bentley
Use numbered backup files
2485
def get_backup_name(entry, by_parent, parent_trans_id, tt):
2012.1.12 by Aaron Bentley
Use iter_changes for revert
2486
    return _get_backup_name(entry.name, by_parent, parent_trans_id, tt)
2487
2488
2489
def _get_backup_name(name, by_parent, parent_trans_id, tt):
1534.10.28 by Aaron Bentley
Use numbered backup files
2490
    """Produce a backup-style name that appears to be available"""
2491
    def name_gen():
2492
        counter = 1
2493
        while True:
2012.1.12 by Aaron Bentley
Use iter_changes for revert
2494
            yield "%s.~%d~" % (name, counter)
1534.10.28 by Aaron Bentley
Use numbered backup files
2495
            counter += 1
2012.1.12 by Aaron Bentley
Use iter_changes for revert
2496
    for new_name in name_gen():
2497
        if not tt.has_named_child(by_parent, parent_trans_id, new_name):
2498
            return new_name
2499
1534.10.28 by Aaron Bentley
Use numbered backup files
2500
1534.7.55 by Aaron Bentley
Fixed up the change detection
2501
def _entry_changes(file_id, entry, working_tree):
1534.7.156 by Aaron Bentley
PEP8 fixes
2502
    """Determine in which ways the inventory entry has changed.
1534.7.55 by Aaron Bentley
Fixed up the change detection
2503
2504
    Returns booleans: has_contents, content_mod, meta_mod
2505
    has_contents means there are currently contents, but they differ
2506
    contents_mod means contents need to be modified
2507
    meta_mod means the metadata needs to be modified
2508
    """
2509
    cur_entry = working_tree.inventory[file_id]
2510
    try:
2511
        working_kind = working_tree.kind(file_id)
2512
        has_contents = True
1757.2.4 by Robert Collins
Teach file_kind about NoSuchFile, reducing duplicate code, and add user files before entering the main loop in smart_add.
2513
    except NoSuchFile:
1534.7.55 by Aaron Bentley
Fixed up the change detection
2514
        has_contents = False
2515
        contents_mod = True
2516
        meta_mod = False
2517
    if has_contents is True:
1731.1.1 by Aaron Bentley
Make root entry an InventoryDirectory, make EmptyTree really empty
2518
        if entry.kind != working_kind:
1534.7.55 by Aaron Bentley
Fixed up the change detection
2519
            contents_mod, meta_mod = True, False
2520
        else:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2521
            cur_entry._read_tree_state(working_tree.id2path(file_id),
1534.7.55 by Aaron Bentley
Fixed up the change detection
2522
                                       working_tree)
2523
            contents_mod, meta_mod = entry.detect_changes(cur_entry)
1534.7.175 by Aaron Bentley
Ensured revert writes a normal inventory
2524
            cur_entry._forget_tree_state()
1534.7.55 by Aaron Bentley
Fixed up the change detection
2525
    return has_contents, contents_mod, meta_mod
2526
1534.7.56 by Aaron Bentley
Implemented the backup file detritus
2527
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2528
def revert(working_tree, target_tree, filenames, backups=False,
2225.1.1 by Aaron Bentley
Added revert change display, with tests
2529
           pb=DummyProgress(), change_reporter=None):
1534.7.157 by Aaron Bentley
Added more docs
2530
    """Revert a working tree's contents to those of a target tree."""
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2531
    target_tree.lock_read()
1534.9.7 by Aaron Bentley
Show progress bars in revert
2532
    tt = TreeTransform(working_tree, pb)
1534.7.47 by Aaron Bentley
Started work on 'revert'
2533
    try:
2012.1.12 by Aaron Bentley
Use iter_changes for revert
2534
        pp = ProgressPhase("Revert phase", 3, pb)
3363.2.10 by Aaron Bentley
Refactor _prepare_revert_transform out of revert
2535
        conflicts, merge_modified = _prepare_revert_transform(
2536
            working_tree, target_tree, tt, filenames, backups, pp)
1551.11.5 by Aaron Bentley
cleanup
2537
        if change_reporter:
1551.10.25 by Aaron Bentley
Make ChangeReporter private
2538
            change_reporter = delta._ChangeReporter(
2255.7.98 by Robert Collins
Merge bzr.dev.
2539
                unversioned_filter=working_tree.is_ignored)
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2540
            delta.report_changes(tt.iter_changes(), change_reporter)
1551.11.6 by Aaron Bentley
Emit change listings before conflict warnings
2541
        for conflict in conflicts:
2542
            warning(conflict)
2543
        pp.next_phase()
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
2544
        tt.apply()
2499.1.1 by Aaron Bentley
Revert does not try to preserve file contents produced by revert
2545
        working_tree.set_merge_modified(merge_modified)
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
2546
    finally:
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2547
        target_tree.unlock()
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
2548
        tt.finalize()
1534.9.4 by Aaron Bentley
Added progress bars to revert.
2549
        pb.clear()
1558.7.13 by Aaron Bentley
WorkingTree.revert returns conflicts
2550
    return conflicts
1534.7.51 by Aaron Bentley
New approach to revert
2551
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
2552
3363.2.10 by Aaron Bentley
Refactor _prepare_revert_transform out of revert
2553
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
3363.2.17 by Aaron Bentley
Start implementing post-change PreviewTree functionality
2554
                              backups, pp, basis_tree=None,
2555
                              merge_modified=None):
3363.2.10 by Aaron Bentley
Refactor _prepare_revert_transform out of revert
2556
    pp.next_phase()
2557
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2558
    try:
3363.2.17 by Aaron Bentley
Start implementing post-change PreviewTree functionality
2559
        if merge_modified is None:
2560
            merge_modified = working_tree.merge_modified()
3363.2.10 by Aaron Bentley
Refactor _prepare_revert_transform out of revert
2561
        merge_modified = _alter_files(working_tree, target_tree, tt,
3363.2.17 by Aaron Bentley
Start implementing post-change PreviewTree functionality
2562
                                      child_pb, filenames, backups,
2563
                                      merge_modified, basis_tree)
3363.2.10 by Aaron Bentley
Refactor _prepare_revert_transform out of revert
2564
    finally:
2565
        child_pb.finished()
2566
    pp.next_phase()
2567
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2568
    try:
2569
        raw_conflicts = resolve_conflicts(tt, child_pb,
2570
            lambda t, c: conflict_pass(t, c, target_tree))
2571
    finally:
2572
        child_pb.finished()
2573
    conflicts = cook_conflicts(raw_conflicts, tt)
2574
    return conflicts, merge_modified
2575
2576
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
2577
def _alter_files(working_tree, target_tree, tt, pb, specific_files,
3363.2.17 by Aaron Bentley
Start implementing post-change PreviewTree functionality
2578
                 backups, merge_modified, basis_tree=None):
3363.10.25 by Aaron Bentley
_alter_files locks supplied basis_tree
2579
    if basis_tree is not None:
2580
        basis_tree.lock_read()
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2581
    change_list = target_tree.iter_changes(working_tree,
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
2582
        specific_files=specific_files, pb=pb)
3363.10.5 by Aaron Bentley
Fix locking issue
2583
    if target_tree.get_root_id() is None:
2012.1.12 by Aaron Bentley
Use iter_changes for revert
2584
        skip_root = True
2585
    else:
2586
        skip_root = False
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2587
    try:
2708.1.5 by Aaron Bentley
Use Tree.extract_files_bytes in revert
2588
        deferred_files = []
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2589
        for id_num, (file_id, path, changed_content, versioned, parent, name,
2590
                kind, executable) in enumerate(change_list):
2591
            if skip_root and file_id[0] is not None and parent[0] is None:
2592
                continue
2593
            trans_id = tt.trans_id_file_id(file_id)
2594
            mode_id = None
2595
            if changed_content:
2596
                keep_content = False
2597
                if kind[0] == 'file' and (backups or kind[1] is None):
2598
                    wt_sha1 = working_tree.get_file_sha1(file_id)
2599
                    if merge_modified.get(file_id) != wt_sha1:
2502.1.6 by Aaron Bentley
Update from review comments
2600
                        # acquire the basis tree lazily to prevent the
2601
                        # expense of accessing it when it's not needed ?
2602
                        # (Guessing, RBC, 200702)
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2603
                        if basis_tree is None:
2604
                            basis_tree = working_tree.basis_tree()
2605
                            basis_tree.lock_read()
2606
                        if file_id in basis_tree:
2607
                            if wt_sha1 != basis_tree.get_file_sha1(file_id):
2608
                                keep_content = True
2609
                        elif kind[1] is None and not versioned[1]:
2012.1.12 by Aaron Bentley
Use iter_changes for revert
2610
                            keep_content = True
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2611
                if kind[0] is not None:
2612
                    if not keep_content:
2613
                        tt.delete_contents(trans_id)
2614
                    elif kind[1] is not None:
2615
                        parent_trans_id = tt.trans_id_file_id(parent[0])
2616
                        by_parent = tt.by_parent()
2617
                        backup_name = _get_backup_name(name[0], by_parent,
2618
                                                       parent_trans_id, tt)
2619
                        tt.adjust_path(backup_name, parent_trans_id, trans_id)
2620
                        new_trans_id = tt.create_path(name[0], parent_trans_id)
2621
                        if versioned == (True, True):
2622
                            tt.unversion_file(trans_id)
2623
                            tt.version_file(file_id, new_trans_id)
2624
                        # New contents should have the same unix perms as old
2625
                        # contents
2626
                        mode_id = trans_id
2627
                        trans_id = new_trans_id
3363.11.3 by Aaron Bentley
Handle adding tree references in revert
2628
                if kind[1] in ('directory', 'tree-reference'):
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2629
                    tt.create_directory(trans_id)
3363.11.3 by Aaron Bentley
Handle adding tree references in revert
2630
                    if kind[1] == 'tree-reference':
2631
                        revision = target_tree.get_reference_revision(file_id,
2632
                                                                      path[1])
2633
                        tt.set_tree_reference(revision, trans_id)
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2634
                elif kind[1] == 'symlink':
2635
                    tt.create_symlink(target_tree.get_symlink_target(file_id),
2636
                                      trans_id)
2637
                elif kind[1] == 'file':
2708.1.6 by Aaron Bentley
Turn extract_files_bytes into an iterator
2638
                    deferred_files.append((file_id, (trans_id, mode_id)))
2499.1.1 by Aaron Bentley
Revert does not try to preserve file contents produced by revert
2639
                    if basis_tree is None:
2640
                        basis_tree = working_tree.basis_tree()
2641
                        basis_tree.lock_read()
2642
                    new_sha1 = target_tree.get_file_sha1(file_id)
2643
                    if (file_id in basis_tree and new_sha1 ==
2644
                        basis_tree.get_file_sha1(file_id)):
2645
                        if file_id in merge_modified:
2646
                            del merge_modified[file_id]
2647
                    else:
2648
                        merge_modified[file_id] = new_sha1
2649
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2650
                    # preserve the execute bit when backing up
2651
                    if keep_content and executable[0] == executable[1]:
2652
                        tt.set_executability(executable[1], trans_id)
3376.2.11 by Martin Pool
Compare to None using is/is not not ==
2653
                elif kind[1] is not None:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2654
                    raise AssertionError(kind[1])
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2655
            if versioned == (False, True):
2656
                tt.version_file(file_id, trans_id)
2657
            if versioned == (True, False):
2658
                tt.unversion_file(trans_id)
3363.2.16 by Aaron Bentley
Fix root directory creation
2659
            if (name[1] is not None and
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2660
                (name[0] != name[1] or parent[0] != parent[1])):
3363.2.16 by Aaron Bentley
Fix root directory creation
2661
                if name[1] == '' and parent[1] is None:
2662
                    parent_trans = ROOT_PARENT
2663
                else:
2664
                    parent_trans = tt.trans_id_file_id(parent[1])
2665
                tt.adjust_path(name[1], parent_trans, trans_id)
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2666
            if executable[0] != executable[1] and kind[1] == "file":
2667
                tt.set_executability(executable[1], trans_id)
4443.2.7 by Ian Clatworthy
test and fix for revert with content filtering
2668
        if working_tree.supports_content_filtering():
2669
            for index, ((trans_id, mode_id), bytes) in enumerate(
2670
                target_tree.iter_files_bytes(deferred_files)):
2671
                file_id = deferred_files[index][0]
4634.102.4 by Ian Clatworthy
Explain why we're using the target tree to look up the path when reverting
2672
                # We're reverting a tree to the target tree so using the
2673
                # target tree to find the file path seems the best choice
2674
                # here IMO - Ian C 27/Oct/2009
4443.2.7 by Ian Clatworthy
test and fix for revert with content filtering
2675
                filter_tree_path = target_tree.id2path(file_id)
2676
                filters = working_tree._content_filter_stack(filter_tree_path)
2677
                bytes = filtered_output_bytes(bytes, filters,
2678
                    ContentFilterContext(filter_tree_path, working_tree))
2679
                tt.create_file(bytes, trans_id, mode_id)
2680
        else:
2681
            for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
2682
                deferred_files):
2683
                tt.create_file(bytes, trans_id, mode_id)
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2684
    finally:
2685
        if basis_tree is not None:
2686
            basis_tree.unlock()
2499.1.1 by Aaron Bentley
Revert does not try to preserve file contents produced by revert
2687
    return merge_modified
2012.1.12 by Aaron Bentley
Use iter_changes for revert
2688
2689
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2690
def resolve_conflicts(tt, pb=DummyProgress(), pass_func=None):
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
2691
    """Make many conflict-resolution attempts, but die if they fail"""
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2692
    if pass_func is None:
2693
        pass_func = conflict_pass
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
2694
    new_conflicts = set()
1534.9.1 by Aaron Bentley
Added progress bars to merge
2695
    try:
2696
        for n in range(10):
2697
            pb.update('Resolution pass', n+1, 10)
2698
            conflicts = tt.find_conflicts()
2699
            if len(conflicts) == 0:
2700
                return new_conflicts
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2701
            new_conflicts.update(pass_func(tt, conflicts))
1534.9.1 by Aaron Bentley
Added progress bars to merge
2702
        raise MalformedTransform(conflicts=conflicts)
2703
    finally:
2704
        pb.clear()
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
2705
2706
2590.2.8 by Aaron Bentley
Restore conflict handling changes
2707
def conflict_pass(tt, conflicts, path_tree=None):
2708
    """Resolve some classes of conflicts.
2709
2710
    :param tt: The transform to resolve conflicts in
2711
    :param conflicts: The conflicts to resolve
2712
    :param path_tree: A Tree to get supplemental paths from
2713
    """
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
2714
    new_conflicts = set()
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
2715
    for c_type, conflict in ((c[0], c) for c in conflicts):
2716
        if c_type == 'duplicate id':
1534.7.51 by Aaron Bentley
New approach to revert
2717
            tt.unversion_file(conflict[1])
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2718
            new_conflicts.add((c_type, 'Unversioned existing file',
2719
                               conflict[1], conflict[2], ))
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
2720
        elif c_type == 'duplicate':
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
2721
            # files that were renamed take precedence
2722
            final_parent = tt.final_parent(conflict[1])
2723
            if tt.path_changed(conflict[1]):
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
2724
                existing_file, new_file = conflict[2], conflict[1]
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
2725
            else:
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
2726
                existing_file, new_file = conflict[1], conflict[2]
2727
            new_name = tt.final_name(existing_file)+'.moved'
2728
            tt.adjust_path(new_name, final_parent, existing_file)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2729
            new_conflicts.add((c_type, 'Moved existing file to',
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
2730
                               existing_file, new_file))
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
2731
        elif c_type == 'parent loop':
2732
            # break the loop by undoing one of the ops that caused the loop
2733
            cur = conflict[1]
2734
            while not tt.path_changed(cur):
2735
                cur = tt.final_parent(cur)
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2736
            new_conflicts.add((c_type, 'Cancelled move', cur,
2737
                               tt.final_parent(cur),))
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
2738
            tt.adjust_path(tt.final_name(cur), tt.get_tree_parent(cur), cur)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2739
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
2740
        elif c_type == 'missing parent':
1534.7.128 by Aaron Bentley
Got missing contents test working
2741
            trans_id = conflict[1]
2742
            try:
2743
                tt.cancel_deletion(trans_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2744
                new_conflicts.add(('deleting parent', 'Not deleting',
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
2745
                                   trans_id))
1534.7.128 by Aaron Bentley
Got missing contents test working
2746
            except KeyError:
1551.19.32 by Aaron Bentley
Don't traceback when adding files to a deleted root (abentley, #210092)
2747
                create = True
2590.2.8 by Aaron Bentley
Restore conflict handling changes
2748
                try:
2749
                    tt.final_name(trans_id)
2750
                except NoFinalPath:
1551.19.6 by Aaron Bentley
Revert doesn't crash restoring a file from a deleted directory
2751
                    if path_tree is not None:
2752
                        file_id = tt.final_file_id(trans_id)
1551.19.32 by Aaron Bentley
Don't traceback when adding files to a deleted root (abentley, #210092)
2753
                        if file_id is None:
2754
                            file_id = tt.inactive_file_id(trans_id)
1551.19.6 by Aaron Bentley
Revert doesn't crash restoring a file from a deleted directory
2755
                        entry = path_tree.inventory[file_id]
1551.19.32 by Aaron Bentley
Don't traceback when adding files to a deleted root (abentley, #210092)
2756
                        # special-case the other tree root (move its
2757
                        # children to current root)
2758
                        if entry.parent_id is None:
2759
                            create=False
2760
                            moved = _reparent_transform_children(
2761
                                tt, trans_id, tt.root)
2762
                            for child in moved:
2763
                                new_conflicts.add((c_type, 'Moved to root',
2764
                                                   child))
2765
                        else:
2766
                            parent_trans_id = tt.trans_id_file_id(
2767
                                entry.parent_id)
2768
                            tt.adjust_path(entry.name, parent_trans_id,
2769
                                           trans_id)
2770
                if create:
2771
                    tt.create_directory(trans_id)
2772
                    new_conflicts.add((c_type, 'Created directory', trans_id))
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
2773
        elif c_type == 'unversioned parent':
1551.19.32 by Aaron Bentley
Don't traceback when adding files to a deleted root (abentley, #210092)
2774
            file_id = tt.inactive_file_id(conflict[1])
2775
            # special-case the other tree root (move its children instead)
2776
            if path_tree and file_id in path_tree:
2777
                if path_tree.inventory[file_id].parent_id is None:
2778
                    continue
2779
            tt.version_file(file_id, conflict[1])
1534.7.171 by Aaron Bentley
Implemented stringifying filesystem conflicts
2780
            new_conflicts.add((c_type, 'Versioned directory', conflict[1]))
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
2781
        elif c_type == 'non-directory parent':
2782
            parent_id = conflict[1]
2783
            parent_parent = tt.final_parent(parent_id)
2784
            parent_name = tt.final_name(parent_id)
2785
            parent_file_id = tt.final_file_id(parent_id)
2786
            new_parent_id = tt.new_directory(parent_name + '.new',
2787
                parent_parent, parent_file_id)
2788
            _reparent_transform_children(tt, parent_id, new_parent_id)
3146.8.19 by Aaron Bentley
Merge with bzr.dev
2789
            if parent_file_id is not None:
2790
                tt.unversion_file(parent_id)
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
2791
            new_conflicts.add((c_type, 'Created directory', new_parent_id))
3363.10.29 by Aaron Bentley
Treat versioned files with no contents as a conflict
2792
        elif c_type == 'versioning no contents':
2793
            tt.cancel_versioning(conflict[1])
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
2794
    return new_conflicts
2795
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
2796
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
2797
def cook_conflicts(raw_conflicts, tt):
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2798
    """Generate a list of cooked conflicts, sorted by file path"""
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
2799
    from bzrlib.conflicts import Conflict
2800
    conflict_iter = iter_cook_conflicts(raw_conflicts, tt)
2801
    return sorted(conflict_iter, key=Conflict.sort_key)
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2802
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
2803
2804
def iter_cook_conflicts(raw_conflicts, tt):
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
2805
    from bzrlib.conflicts import Conflict
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2806
    fp = FinalPaths(tt)
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
2807
    for conflict in raw_conflicts:
2808
        c_type = conflict[0]
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2809
        action = conflict[1]
2810
        modified_path = fp.get_path(conflict[2])
2811
        modified_id = tt.final_file_id(conflict[2])
2812
        if len(conflict) == 3:
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
2813
            yield Conflict.factory(c_type, action=action, path=modified_path,
2814
                                     file_id=modified_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2815
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2816
        else:
2817
            conflicting_path = fp.get_path(conflict[3])
2818
            conflicting_id = tt.final_file_id(conflict[3])
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
2819
            yield Conflict.factory(c_type, action=action, path=modified_path,
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2820
                                   file_id=modified_id,
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
2821
                                   conflict_path=conflicting_path,
2822
                                   conflict_file_id=conflicting_id)
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2823
2824
2825
class _FileMover(object):
2733.2.9 by Aaron Bentley
Update docstrings
2826
    """Moves and deletes files for TreeTransform, tracking operations"""
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2827
2828
    def __init__(self):
2829
        self.past_renames = []
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2830
        self.pending_deletions = []
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2831
2832
    def rename(self, from_, to):
2733.2.9 by Aaron Bentley
Update docstrings
2833
        """Rename a file from one path to another.  Functions like os.rename"""
3063.1.1 by Alexander Belchenko
Catch OSError 17 (file exists) in final phase of tree transform and show filename to user (#111758).
2834
        try:
2835
            os.rename(from_, to)
2836
        except OSError, e:
3063.1.3 by Aaron Bentley
Update for Linux
2837
            if e.errno in (errno.EEXIST, errno.ENOTEMPTY):
3063.1.1 by Alexander Belchenko
Catch OSError 17 (file exists) in final phase of tree transform and show filename to user (#111758).
2838
                raise errors.FileExists(to, str(e))
2839
            raise
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2840
        self.past_renames.append((from_, to))
2841
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2842
    def pre_delete(self, from_, to):
2733.2.9 by Aaron Bentley
Update docstrings
2843
        """Rename a file out of the way and mark it for deletion.
2844
2845
        Unlike os.unlink, this works equally well for files and directories.
2846
        :param from_: The current file path
2847
        :param to: A temporary path for the file
2848
        """
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2849
        self.rename(from_, to)
2850
        self.pending_deletions.append(to)
2851
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2852
    def rollback(self):
2733.2.9 by Aaron Bentley
Update docstrings
2853
        """Reverse all renames that have been performed"""
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2854
        for from_, to in reversed(self.past_renames):
2855
            os.rename(to, from_)
2733.2.12 by Aaron Bentley
Updates from review
2856
        # after rollback, don't reuse _FileMover
2857
        past_renames = None
2858
        pending_deletions = None
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2859
2860
    def apply_deletions(self):
2733.2.9 by Aaron Bentley
Update docstrings
2861
        """Apply all marked deletions"""
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2862
        for path in self.pending_deletions:
2863
            delete_any(path)
2733.2.12 by Aaron Bentley
Updates from review
2864
        # after apply_deletions, don't reuse _FileMover
2865
        past_renames = None
2866
        pending_deletions = None