/brz/remove-bazaar

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