/brz/remove-bazaar

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