/brz/remove-bazaar

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