/brz/remove-bazaar

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