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