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