/brz/remove-bazaar

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