/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2006-2011 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
16
6379.6.1 by Jelmer Vernooij
Import absolute_import in a few places.
17
from __future__ import absolute_import
18
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
19
import os
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
20
import errno
3363.2.27 by Aaron Bentley
Make path_content_summary a core API
21
from stat import S_ISREG, S_IEXEC
4934.1.1 by John Arbash Meinel
Basic implementation for windows and bug #488724.
22
import time
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
23
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
24
from . import (
6449.6.5 by Jelmer Vernooij
Merge bzr.transform.orphan_policy move to config stacks.
25
    config as _mod_config,
7490.83.1 by Jelmer Vernooij
Add abstract methods.
26
    controldir,
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
27
    errors,
28
    lazy_import,
7490.83.1 by Jelmer Vernooij
Add abstract methods.
29
    osutils,
5409.1.14 by Vincent Ladeuil
Prepare for more ways to handle orphans.
30
    registry,
5753.2.3 by Jelmer Vernooij
Fix transform tests.
31
    trace,
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
32
    )
33
lazy_import.lazy_import(globals(), """
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
34
from breezy import (
7356.1.2 by Jelmer Vernooij
Use ExitStack in more places.
35
    cleanup,
5988.2.1 by Vincent Ladeuil
Do not generate path conflicts if a corresponding content conflict exists
36
    conflicts,
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
37
    multiparent,
3363.2.4 by Aaron Bentley
Get significant portions of PreviewTree implemented and passing tests
38
    revision as _mod_revision,
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
39
    ui,
5582.10.4 by Jelmer Vernooij
Fix a bunch of tests.
40
    urlutils,
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
41
    )
7490.83.1 by Jelmer Vernooij
Add abstract methods.
42
from breezy.i18n import gettext
7490.83.5 by Jelmer Vernooij
Fix import tariff test.
43
""")
7490.83.1 by Jelmer Vernooij
Add abstract methods.
44
7490.69.1 by Jelmer Vernooij
Move some more tests to breezy.bzr.
45
from .errors import (DuplicateKey,
46
                     BzrError, InternalBzrError)
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
47
from .filters import filtered_output_bytes, ContentFilterContext
48
from .mutabletree import MutableTree
49
from .osutils import (
3363.2.19 by Aaron Bentley
Make PreviewTree.path2id correct
50
    delete_any,
51
    file_kind,
52
    pathjoin,
3363.15.4 by Aaron Bentley
Implement PreviewTree.get_file_sha1 properly
53
    sha_file,
3363.2.19 by Aaron Bentley
Make PreviewTree.path2id correct
54
    splitpath,
7122.6.3 by Jelmer Vernooij
Merge trunk.
55
    supports_symlinks,
5579.3.1 by Jelmer Vernooij
Remove unused imports.
56
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
57
from .progress import ProgressPhase
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
58
from .sixish import (
6973.6.2 by Jelmer Vernooij
Fix more tests.
59
    text_type,
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
60
    viewitems,
61
    viewvalues,
62
    )
6883.5.3 by Jelmer Vernooij
Add find_previous_path.
63
from .tree import (
7357.1.8 by Jelmer Vernooij
Remove the InterTree object.
64
    InterTree,
7322.1.6 by Jelmer Vernooij
Use the new attributes on TreeChange.
65
    TreeChange,
6883.5.3 by Jelmer Vernooij
Add find_previous_path.
66
    )
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
67
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
68
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
69
ROOT_PARENT = "root-parent"
70
7143.15.2 by Jelmer Vernooij
Run autopep8.
71
7490.69.1 by Jelmer Vernooij
Move some more tests to breezy.bzr.
72
class NoFinalPath(BzrError):
73
74
    _fmt = ("No final name for trans_id %(trans_id)r\n"
75
            "file-id: %(file_id)r\n"
76
            "root trans-id: %(root_trans_id)r\n")
77
78
    def __init__(self, trans_id, transform):
79
        self.trans_id = trans_id
80
        self.file_id = transform.final_file_id(trans_id)
81
        self.root_trans_id = transform.root
82
83
84
class ReusingTransform(BzrError):
85
86
    _fmt = "Attempt to reuse a transform that has already been applied."
87
88
89
class MalformedTransform(InternalBzrError):
90
91
    _fmt = "Tree transform is malformed %(conflicts)r"
92
93
7490.77.4 by Jelmer Vernooij
Move some errors around.
94
class CantMoveRoot(BzrError):
95
96
    _fmt = "Moving the root directory is not supported at this time"
97
98
7490.69.1 by Jelmer Vernooij
Move some more tests to breezy.bzr.
99
class ImmortalLimbo(BzrError):
100
101
    _fmt = """Unable to delete transform temporary directory %(limbo_dir)s.
102
    Please examine %(limbo_dir)s to see if it contains any files you wish to
103
    keep, and delete it when you are done."""
104
105
    def __init__(self, limbo_dir):
106
        BzrError.__init__(self)
107
        self.limbo_dir = limbo_dir
108
109
7490.77.4 by Jelmer Vernooij
Move some errors around.
110
class TransformRenameFailed(BzrError):
111
112
    _fmt = "Failed to rename %(from_path)s to %(to_path)s: %(why)s"
113
114
    def __init__(self, from_path, to_path, why, errno):
115
        self.from_path = from_path
116
        self.to_path = to_path
117
        self.why = why
118
        self.errno = errno
119
120
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
121
def unique_add(map, key, value):
122
    if key in map:
1534.7.5 by Aaron Bentley
Got unique_add under test
123
        raise DuplicateKey(key=key)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
124
    map[key] = value
125
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
126
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
127
class _TransformResults(object):
2502.1.5 by Aaron Bentley
Cleanup
128
    def __init__(self, modified_paths, rename_count):
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
129
        object.__init__(self)
130
        self.modified_paths = modified_paths
2502.1.5 by Aaron Bentley
Cleanup
131
        self.rename_count = rename_count
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
132
133
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
134
class TreeTransformBase(object):
4354.5.4 by Aaron Bentley
Update docs
135
    """The base class for TreeTransform and its kin."""
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
136
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
137
    def __init__(self, tree, pb=None, case_sensitive=True):
3008.1.29 by Aaron Bentley
Add docstrings, rename TT.__doc
138
        """Constructor.
139
140
        :param tree: The tree that will be transformed, but not necessarily
141
            the output tree.
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
142
        :param pb: ignored
3008.1.29 by Aaron Bentley
Add docstrings, rename TT.__doc
143
        :param case_sensitive: If True, the target of the transform is
144
            case sensitive, not just case preserving.
145
        """
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
146
        object.__init__(self)
147
        self._tree = tree
148
        self._id_number = 0
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
149
        # mapping of trans_id -> new basename
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
150
        self._new_name = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
151
        # mapping of trans_id -> new parent trans_id
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
152
        self._new_parent = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
153
        # mapping of trans_id with new contents -> new file_kind
1534.7.4 by Aaron Bentley
Unified all file types as 'contents'
154
        self._new_contents = {}
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
155
        # mapping of trans_id => (sha1 of content, stat_value)
156
        self._observed_sha1s = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
157
        # Set of trans_ids whose contents will be removed
1534.7.34 by Aaron Bentley
Proper conflicts for removals
158
        self._removed_contents = set()
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
159
        # Mapping of trans_id -> new execute-bit value
1534.7.25 by Aaron Bentley
Added set_executability
160
        self._new_executability = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
161
        # Mapping of trans_id -> new tree-reference value
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
162
        self._new_reference_revision = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
163
        # Mapping of trans_id -> new file_id
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
164
        self._new_id = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
165
        # Mapping of old file-id -> trans_id
1534.7.143 by Aaron Bentley
Prevented get_trans_id from automatically versioning file ids
166
        self._non_present_ids = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
167
        # Mapping of new file_id -> trans_id
1534.7.75 by Aaron Bentley
Added reverse-lookup for versioned files and get_trans_id
168
        self._r_new_id = {}
3981.1.1 by Robert Collins
Fix bug 319790 - unshelve of deleted paths failing.
169
        # Set of trans_ids that will be removed
1534.7.39 by Aaron Bentley
Ensured that files can be unversioned (de-versioned?)
170
        self._removed_id = set()
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
171
        # Mapping of path in old tree -> trans_id
1534.7.7 by Aaron Bentley
Added support for all-file path ids
172
        self._tree_path_ids = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
173
        # Mapping trans_id -> path in old tree
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
174
        self._tree_id_paths = {}
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
175
        # The trans_id that will be used as the tree root
6973.3.1 by Jelmer Vernooij
Avoid using file ids where possible.
176
        if tree.is_versioned(''):
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
177
            self._new_root = self.trans_id_tree_path('')
3363.2.16 by Aaron Bentley
Fix root directory creation
178
        else:
179
            self._new_root = None
4597.14.2 by Vincent Ladeuil
Implements --take-this and --take-other when resolving text conflicts
180
        # Indicator of whether the transform has been applied
3008.1.29 by Aaron Bentley
Add docstrings, rename TT.__doc
181
        self._done = False
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
182
        # A progress bar
1534.9.1 by Aaron Bentley
Added progress bars to merge
183
        self._pb = pb
3008.1.15 by Aaron Bentley
Make case_sensitive an aspect of the transform, not the source tree
184
        # Whether the target is case sensitive
185
        self._case_sensitive_target = case_sensitive
1551.19.1 by Aaron Bentley
Documentation update for TreeTransform, suggested by Michael Hudson
186
        # 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
187
        self.rename_count = 0
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
188
5954.2.1 by Aaron Bentley
Make Transform a Context Manager.
189
    def __enter__(self):
190
        """Support Context Manager API."""
191
        return self
192
193
    def __exit__(self, exc_type, exc_val, exc_tb):
194
        """Support Context Manager API."""
195
        self.finalize()
196
7490.83.1 by Jelmer Vernooij
Add abstract methods.
197
    def iter_tree_children(self, trans_id):
198
        """Iterate through the entry's tree children, if any.
199
200
        :param trans_id: trans id to iterate
201
        :returns: Iterator over paths
202
        """
203
        raise NotImplementedError(self.iter_tree_children)
204
205
    def _read_symlink_target(self, trans_id):
206
        raise NotImplementedError(self._read_symlink_target)
207
208
    def canonical_path(self, path):
209
        return path
210
211
    def tree_kind(self, trans_id):
212
        raise NotImplementedError(self.tree_kind)
213
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
214
    def finalize(self):
215
        """Release the working tree lock, if held.
216
217
        This is required if apply has not been invoked, but can be invoked
218
        even after apply.
219
        """
220
        if self._tree is None:
221
            return
6434.2.1 by Jelmer Vernooij
Add pre_transform/post_transform hooks.
222
        for hook in MutableTree.hooks['post_transform']:
6434.2.2 by Jelmer Vernooij
Add hooks for tree transforms.
223
            hook(self._tree, self)
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
224
        self._tree.unlock()
225
        self._tree = None
226
1534.7.132 by Aaron Bentley
Got cooked conflicts working
227
    def __get_root(self):
228
        return self._new_root
229
230
    root = property(__get_root)
231
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
232
    def _assign_id(self):
233
        """Produce a new tranform id"""
234
        new_id = "new-%s" % self._id_number
7143.15.2 by Jelmer Vernooij
Run autopep8.
235
        self._id_number += 1
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
236
        return new_id
237
238
    def create_path(self, name, parent):
239
        """Assign a transaction id to a new path"""
240
        trans_id = self._assign_id()
241
        unique_add(self._new_name, trans_id, name)
242
        unique_add(self._new_parent, trans_id, parent)
243
        return trans_id
244
1534.7.6 by Aaron Bentley
Added conflict handling
245
    def adjust_path(self, name, parent, trans_id):
1534.7.21 by Aaron Bentley
Updated docstrings
246
        """Change the path that is assigned to a transaction id."""
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
247
        if parent is None:
248
            raise ValueError("Parent trans-id may not be None")
1534.7.66 by Aaron Bentley
Ensured we don't accidentally move the root directory
249
        if trans_id == self._new_root:
250
            raise CantMoveRoot
1534.7.6 by Aaron Bentley
Added conflict handling
251
        self._new_name[trans_id] = name
252
        self._new_parent[trans_id] = parent
253
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
254
    def adjust_root_path(self, name, parent):
255
        """Emulate moving the root by moving all children, instead.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
256
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
257
        We do this by undoing the association of root's transaction id with the
258
        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
259
        transaction id.  We unversion the root directory and version the
1534.7.69 by Aaron Bentley
Got real root moves working
260
        physically new directory, and hope someone versions the tree root
261
        later.
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
262
        """
263
        old_root = self._new_root
264
        old_root_file_id = self.final_file_id(old_root)
265
        # force moving all children of root
266
        for child_id in self.iter_tree_children(old_root):
267
            if child_id != parent:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
268
                self.adjust_path(self.final_name(child_id),
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
269
                                 self.final_parent(child_id), child_id)
1534.7.69 by Aaron Bentley
Got real root moves working
270
            file_id = self.final_file_id(child_id)
271
            if file_id is not None:
272
                self.unversion_file(child_id)
7490.77.8 by Jelmer Vernooij
Change argument order for Transform.version_file.
273
            self.version_file(child_id, file_id=file_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
274
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
275
        # the physical root needs a new transaction id
276
        self._tree_path_ids.pop("")
277
        self._tree_id_paths.pop(old_root)
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
278
        self._new_root = self.trans_id_tree_path('')
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
279
        if parent == old_root:
280
            parent = self._new_root
281
        self.adjust_path(name, parent, old_root)
282
        self.create_directory(old_root)
7490.77.8 by Jelmer Vernooij
Change argument order for Transform.version_file.
283
        self.version_file(old_root, file_id=old_root_file_id)
1534.7.69 by Aaron Bentley
Got real root moves working
284
        self.unversion_file(self._new_root)
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
285
5993.2.4 by Jelmer Vernooij
Remove feature flag.
286
    def fixup_new_roots(self):
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
287
        """Reinterpret requests to change the root directory
288
289
        Instead of creating a root directory, or moving an existing directory,
290
        all the attributes and children of the new root are applied to the
291
        existing root directory.
292
293
        This means that the old root trans-id becomes obsolete, so it is
294
        recommended only to invoke this after the root trans-id has become
295
        irrelevant.
5993.2.3 by Jelmer Vernooij
Update NEWS, consistently use require_tree_root as argument everywhere.
296
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
297
        """
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
298
        new_roots = [k for k, v in viewitems(self._new_parent)
299
                     if v == ROOT_PARENT]
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
300
        if len(new_roots) < 1:
301
            return
302
        if len(new_roots) != 1:
303
            raise ValueError('A tree cannot have two roots!')
304
        if self._new_root is None:
305
            self._new_root = new_roots[0]
306
            return
307
        old_new_root = new_roots[0]
308
        # unversion the new root's directory.
6011.1.1 by Aaron Bentley
Merging an unrelated tree retains root.
309
        if self.final_kind(self._new_root) is None:
310
            file_id = self.final_file_id(old_new_root)
311
        else:
312
            file_id = self.final_file_id(self._new_root)
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
313
        if old_new_root in self._new_id:
314
            self.cancel_versioning(old_new_root)
315
        else:
316
            self.unversion_file(old_new_root)
317
        # if, at this stage, root still has an old file_id, zap it so we can
318
        # stick a new one in.
7143.15.2 by Jelmer Vernooij
Run autopep8.
319
        if (self.tree_file_id(self._new_root) is not None
320
                and self._new_root not in self._removed_id):
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
321
            self.unversion_file(self._new_root)
5954.4.2 by Aaron Bentley
Support merging into null tree.
322
        if file_id is not None:
7490.77.8 by Jelmer Vernooij
Change argument order for Transform.version_file.
323
            self.version_file(self._new_root, file_id=file_id)
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
324
325
        # Now move children of new root into old root directory.
326
        # Ensure all children are registered with the transaction, but don't
327
        # use directly-- some tree children have new parents
328
        list(self.iter_tree_children(old_new_root))
329
        # Move all children of new root into old root directory.
330
        for child in self.by_parent().get(old_new_root, []):
331
            self.adjust_path(self.final_name(child), self._new_root, child)
332
333
        # Ensure old_new_root has no directory.
334
        if old_new_root in self._new_contents:
335
            self.cancel_creation(old_new_root)
336
        else:
337
            self.delete_contents(old_new_root)
338
339
        # prevent deletion of root directory.
340
        if self._new_root in self._removed_contents:
341
            self.cancel_deletion(self._new_root)
342
343
        # destroy path info for old_new_root.
344
        del self._new_parent[old_new_root]
345
        del self._new_name[old_new_root]
346
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
347
    def trans_id_file_id(self, file_id):
1534.7.156 by Aaron Bentley
PEP8 fixes
348
        """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
349
        A new id is only created for file_ids that were never present.  If
350
        a transaction has been unversioned, it is deliberately still returned.
351
        (this will likely lead to an unversioned parent conflict.)
352
        """
3363.2.16 by Aaron Bentley
Fix root directory creation
353
        if file_id is None:
354
            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
355
        if file_id in self._r_new_id and self._r_new_id[file_id] is not None:
356
            return self._r_new_id[file_id]
357
        else:
3363.17.1 by Aaron Bentley
Avoid inventory for merge and transform code
358
            try:
6885.6.4 by Jelmer Vernooij
Tree transform - avoid iter_entries_by_dir(specific_file_ids=).
359
                path = self._tree.id2path(file_id)
360
            except errors.NoSuchId:
3363.17.1 by Aaron Bentley
Avoid inventory for merge and transform code
361
                if file_id in self._non_present_ids:
362
                    return self._non_present_ids[file_id]
363
                else:
364
                    trans_id = self._assign_id()
365
                    self._non_present_ids[file_id] = trans_id
366
                    return trans_id
367
            else:
6885.1.1 by Jelmer Vernooij
Get rid of TreeTransform.trans_id_tree_file_id.
368
                return self.trans_id_tree_path(path)
1534.7.75 by Aaron Bentley
Added reverse-lookup for versioned files and get_trans_id
369
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
370
    def trans_id_tree_path(self, path):
1534.7.7 by Aaron Bentley
Added support for all-file path ids
371
        """Determine (and maybe set) the transaction ID for a tree path."""
1534.7.12 by Aaron Bentley
Added canonical_path function
372
        path = self.canonical_path(path)
1534.7.7 by Aaron Bentley
Added support for all-file path ids
373
        if path not in self._tree_path_ids:
374
            self._tree_path_ids[path] = self._assign_id()
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
375
            self._tree_id_paths[self._tree_path_ids[path]] = path
1534.7.7 by Aaron Bentley
Added support for all-file path ids
376
        return self._tree_path_ids[path]
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
377
1534.7.16 by Aaron Bentley
Added get_tree_parent
378
    def get_tree_parent(self, trans_id):
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
379
        """Determine id of the parent in the tree."""
1534.7.16 by Aaron Bentley
Added get_tree_parent
380
        path = self._tree_id_paths[trans_id]
381
        if path == "":
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
382
            return ROOT_PARENT
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
383
        return self.trans_id_tree_path(os.path.dirname(path))
1534.7.16 by Aaron Bentley
Added get_tree_parent
384
1534.7.34 by Aaron Bentley
Proper conflicts for removals
385
    def delete_contents(self, trans_id):
386
        """Schedule the contents of a path entry for deletion"""
4597.9.13 by Vincent Ladeuil
bzrlib.transform.TreeTransform.tree_kind and
387
        kind = self.tree_kind(trans_id)
388
        if kind is not None:
389
            self._removed_contents.add(trans_id)
1534.7.34 by Aaron Bentley
Proper conflicts for removals
390
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
391
    def cancel_deletion(self, trans_id):
392
        """Cancel a scheduled deletion"""
393
        self._removed_contents.remove(trans_id)
394
1534.7.39 by Aaron Bentley
Ensured that files can be unversioned (de-versioned?)
395
    def unversion_file(self, trans_id):
396
        """Schedule a path entry to become unversioned"""
397
        self._removed_id.add(trans_id)
398
399
    def delete_versioned(self, trans_id):
400
        """Delete and unversion a versioned file"""
401
        self.delete_contents(trans_id)
402
        self.unversion_file(trans_id)
403
1534.7.25 by Aaron Bentley
Added set_executability
404
    def set_executability(self, executability, trans_id):
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
405
        """Schedule setting of the 'execute' bit
406
        To unschedule, set to None
407
        """
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
408
        if executability is None:
409
            del self._new_executability[trans_id]
410
        else:
411
            unique_add(self._new_executability, trans_id, executability)
1534.7.25 by Aaron Bentley
Added set_executability
412
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
413
    def set_tree_reference(self, revision_id, trans_id):
414
        """Set the reference associated with a directory"""
415
        unique_add(self._new_reference_revision, trans_id, revision_id)
416
7490.77.8 by Jelmer Vernooij
Change argument order for Transform.version_file.
417
    def version_file(self, trans_id, file_id=None):
1534.7.21 by Aaron Bentley
Updated docstrings
418
        """Schedule a file to become versioned."""
7490.77.9 by Jelmer Vernooij
Move out some file id handling functions.
419
        raise NotImplementedError(self.version_file)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
420
1534.7.105 by Aaron Bentley
Got merge with rename working
421
    def cancel_versioning(self, trans_id):
422
        """Undo a previous versioning of a file"""
7490.77.9 by Jelmer Vernooij
Move out some file id handling functions.
423
        raise NotImplementedError(self.cancel_versioning)
1534.7.105 by Aaron Bentley
Got merge with rename working
424
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
425
    def new_paths(self, filesystem_only=False):
426
        """Determine the paths of all new and changed files.
427
3453.2.11 by Aaron Bentley
Updates from review
428
        :param filesystem_only: if True, only calculate values for files
429
            that require renames or execute bit changes.
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
430
        """
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
431
        new_ids = set()
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
432
        if filesystem_only:
3619.2.11 by Aaron Bentley
Tweak new_paths logic
433
            stale_ids = self._needs_rename.difference(self._new_name)
434
            stale_ids.difference_update(self._new_parent)
435
            stale_ids.difference_update(self._new_contents)
436
            stale_ids.difference_update(self._new_id)
437
            needs_rename = self._needs_rename.difference(stale_ids)
3619.2.10 by Aaron Bentley
Compensate for stale entries in TT._needs_rename
438
            id_sets = (needs_rename, self._new_executability)
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
439
        else:
440
            id_sets = (self._new_name, self._new_parent, self._new_contents,
441
                       self._new_id, self._new_executability)
442
        for id_set in id_sets:
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
443
            new_ids.update(id_set)
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
444
        return sorted(FinalPaths(self).get_paths(new_ids))
1534.7.6 by Aaron Bentley
Added conflict handling
445
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
446
    def final_kind(self, trans_id):
1534.7.156 by Aaron Bentley
PEP8 fixes
447
        """Determine the final file kind, after any changes applied.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
448
4597.9.7 by Vincent Ladeuil
transform.final_kind() now returns None instead of raising NoSuchFile.
449
        :return: None if the file does not exist/has no contents.  (It is
450
            conceivable that a path would be created without the corresponding
451
            contents insertion command)
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
452
        """
453
        if trans_id in self._new_contents:
1534.7.73 by Aaron Bentley
Changed model again. Now iterator is used immediately.
454
            return self._new_contents[trans_id]
1534.7.34 by Aaron Bentley
Proper conflicts for removals
455
        elif trans_id in self._removed_contents:
4597.9.7 by Vincent Ladeuil
transform.final_kind() now returns None instead of raising NoSuchFile.
456
            return None
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
457
        else:
4597.9.13 by Vincent Ladeuil
bzrlib.transform.TreeTransform.tree_kind and
458
            return self.tree_kind(trans_id)
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
459
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
460
    def tree_path(self, trans_id):
461
        """Determine the tree path associated with the trans_id."""
462
        return self._tree_id_paths.get(trans_id)
463
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
464
    def tree_file_id(self, trans_id):
1534.7.41 by Aaron Bentley
Got inventory ID movement working
465
        """Determine the file id associated with the trans_id in the tree"""
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
466
        path = self.tree_path(trans_id)
467
        if path is None:
1534.7.41 by Aaron Bentley
Got inventory ID movement working
468
            return None
469
        # the file is old; the old id is still valid
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
470
        if self._new_root == trans_id:
7358.14.1 by Jelmer Vernooij
Remove Tree.get_root_id() in favour of Tree.path2id('').
471
            return self._tree.path2id('')
3363.17.5 by Aaron Bentley
Update merge to not use inventory
472
        return self._tree.path2id(path)
1534.7.41 by Aaron Bentley
Got inventory ID movement working
473
1534.7.13 by Aaron Bentley
Implemented final_file_id
474
    def final_file_id(self, trans_id):
1534.7.156 by Aaron Bentley
PEP8 fixes
475
        """Determine the file id after any changes are applied, or None.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
476
1534.7.21 by Aaron Bentley
Updated docstrings
477
        None indicates that the file will not be versioned after changes are
478
        applied.
479
        """
1534.7.13 by Aaron Bentley
Implemented final_file_id
480
        try:
481
            return self._new_id[trans_id]
482
        except KeyError:
1534.7.39 by Aaron Bentley
Ensured that files can be unversioned (de-versioned?)
483
            if trans_id in self._removed_id:
484
                return None
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
485
        return self.tree_file_id(trans_id)
1534.7.13 by Aaron Bentley
Implemented final_file_id
486
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
487
    def inactive_file_id(self, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
488
        """Return the inactive file_id associated with a transaction id.
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
489
        That is, the one in the tree or in non_present_ids.
490
        The file_id may actually be active, too.
491
        """
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
492
        file_id = self.tree_file_id(trans_id)
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
493
        if file_id is not None:
494
            return file_id
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
495
        for key, value in viewitems(self._non_present_ids):
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
496
            if value == trans_id:
497
                return key
498
1534.7.17 by Aaron Bentley
Added final_parent function
499
    def final_parent(self, trans_id):
1534.7.156 by Aaron Bentley
PEP8 fixes
500
        """Determine the parent file_id, after any changes are applied.
1534.7.21 by Aaron Bentley
Updated docstrings
501
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
502
        ROOT_PARENT is returned for the tree root.
1534.7.21 by Aaron Bentley
Updated docstrings
503
        """
1534.7.17 by Aaron Bentley
Added final_parent function
504
        try:
505
            return self._new_parent[trans_id]
506
        except KeyError:
507
            return self.get_tree_parent(trans_id)
508
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
509
    def final_name(self, trans_id):
1534.7.40 by Aaron Bentley
Updated docs
510
        """Determine the final filename, after all changes are applied."""
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
511
        try:
512
            return self._new_name[trans_id]
513
        except KeyError:
1731.1.33 by Aaron Bentley
Revert no-special-root changes
514
            try:
515
                return os.path.basename(self._tree_id_paths[trans_id])
516
            except KeyError:
517
                raise NoFinalPath(trans_id, self)
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
518
1534.10.28 by Aaron Bentley
Use numbered backup files
519
    def by_parent(self):
1534.7.40 by Aaron Bentley
Updated docs
520
        """Return a map of parent: children for known parents.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
521
1534.7.40 by Aaron Bentley
Updated docs
522
        Only new paths and parents of tree files with assigned ids are used.
523
        """
1534.7.6 by Aaron Bentley
Added conflict handling
524
        by_parent = {}
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
525
        items = list(viewitems(self._new_parent))
526
        items.extend((t, self.final_parent(t))
7143.15.2 by Jelmer Vernooij
Run autopep8.
527
                     for t in list(self._tree_id_paths))
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
528
        for trans_id, parent_id in items:
1534.7.6 by Aaron Bentley
Added conflict handling
529
            if parent_id not in by_parent:
530
                by_parent[parent_id] = set()
531
            by_parent[parent_id].add(trans_id)
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
532
        return by_parent
1534.7.11 by Aaron Bentley
Refactored conflict handling
533
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
534
    def path_changed(self, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
535
        """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)
536
        return (trans_id in self._new_name) or (trans_id in self._new_parent)
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
537
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
538
    def new_contents(self, trans_id):
539
        return (trans_id in self._new_contents)
540
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
541
    def find_conflicts(self):
1534.7.40 by Aaron Bentley
Updated docs
542
        """Find any violations of inventory or filesystem invariants"""
3008.1.29 by Aaron Bentley
Add docstrings, rename TT.__doc
543
        if self._done is True:
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
544
            raise ReusingTransform()
545
        conflicts = []
546
        # ensure all children of all existent parents are known
547
        # all children of non-existent parents are known, by definition.
548
        self._add_tree_children()
1534.10.28 by Aaron Bentley
Use numbered backup files
549
        by_parent = self.by_parent()
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
550
        conflicts.extend(self._unversioned_parents(by_parent))
1534.7.19 by Aaron Bentley
Added tests for parent loops
551
        conflicts.extend(self._parent_loops())
1534.7.11 by Aaron Bentley
Refactored conflict handling
552
        conflicts.extend(self._duplicate_entries(by_parent))
553
        conflicts.extend(self._parent_type_conflicts(by_parent))
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
554
        conflicts.extend(self._improper_versioning())
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
555
        conflicts.extend(self._executability_conflicts())
1534.7.152 by Aaron Bentley
Fixed overwrites
556
        conflicts.extend(self._overwrite_conflicts())
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
557
        return conflicts
558
4526.8.6 by Aaron Bentley
Check for malformed transforms before committing.
559
    def _check_malformed(self):
560
        conflicts = self.find_conflicts()
561
        if len(conflicts) != 0:
562
            raise MalformedTransform(conflicts=conflicts)
563
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
564
    def _add_tree_children(self):
1534.7.156 by Aaron Bentley
PEP8 fixes
565
        """Add all the children of all active parents to the known paths.
1534.7.40 by Aaron Bentley
Updated docs
566
567
        Active parents are those which gain children, and those which are
568
        removed.  This is a necessary first step in detecting conflicts.
569
        """
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
570
        parents = list(self.by_parent())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
571
        parents.extend([t for t in self._removed_contents if
1534.7.34 by Aaron Bentley
Proper conflicts for removals
572
                        self.tree_kind(t) == 'directory'])
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
573
        for trans_id in self._removed_id:
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
574
            path = self.tree_path(trans_id)
575
            if path is not None:
576
                if self._tree.stored_kind(path) == 'directory':
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
577
                    parents.append(trans_id)
578
            elif self.tree_kind(trans_id) == 'directory':
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
579
                parents.append(trans_id)
580
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
581
        for parent_id in parents:
1534.7.67 by Aaron Bentley
Refactored _add_tree_children
582
            # ensure that all children are registered with the transaction
583
            list(self.iter_tree_children(parent_id))
584
5409.1.11 by Vincent Ladeuil
Slightly cleanup bzrlib.transform and deprecate unused code.
585
    def _has_named_child(self, name, parent_id, known_children):
586
        """Does a parent already have a name child.
587
588
        :param name: The searched for name.
589
590
        :param parent_id: The parent for which the check is made.
591
592
        :param known_children: The already known children. This should have
593
            been recently obtained from `self.by_parent.get(parent_id)`
594
            (or will be if None is passed).
595
        """
596
        if known_children is None:
597
            known_children = self.by_parent().get(parent_id, [])
598
        for child in known_children:
1534.10.28 by Aaron Bentley
Use numbered backup files
599
            if self.final_name(child) == name:
600
                return True
5409.1.11 by Vincent Ladeuil
Slightly cleanup bzrlib.transform and deprecate unused code.
601
        parent_path = self._tree_id_paths.get(parent_id, None)
602
        if parent_path is None:
603
            # No parent... no children
1534.10.28 by Aaron Bentley
Use numbered backup files
604
            return False
5409.1.11 by Vincent Ladeuil
Slightly cleanup bzrlib.transform and deprecate unused code.
605
        child_path = joinpath(parent_path, name)
606
        child_id = self._tree_path_ids.get(child_path, None)
1534.10.28 by Aaron Bentley
Use numbered backup files
607
        if child_id is None:
5409.1.11 by Vincent Ladeuil
Slightly cleanup bzrlib.transform and deprecate unused code.
608
            # Not known by the tree transform yet, check the filesystem
609
            return osutils.lexists(self._tree.abspath(child_path))
1534.10.28 by Aaron Bentley
Use numbered backup files
610
        else:
5409.1.11 by Vincent Ladeuil
Slightly cleanup bzrlib.transform and deprecate unused code.
611
            raise AssertionError('child_id is missing: %s, %s, %s'
612
                                 % (name, parent_id, child_id))
613
614
    def _available_backup_name(self, name, target_id):
615
        """Find an available backup name.
616
617
        :param name: The basename of the file.
618
7195.5.1 by Martin
Fix remaining whitespace lint in codebase
619
        :param target_id: The directory trans_id where the backup should
5409.1.11 by Vincent Ladeuil
Slightly cleanup bzrlib.transform and deprecate unused code.
620
            be placed.
621
        """
622
        known_children = self.by_parent().get(target_id, [])
623
        return osutils.available_backup_name(
624
            name,
625
            lambda base: self._has_named_child(
626
                base, target_id, known_children))
1534.10.28 by Aaron Bentley
Use numbered backup files
627
1534.7.19 by Aaron Bentley
Added tests for parent loops
628
    def _parent_loops(self):
629
        """No entry should be its own ancestor"""
630
        conflicts = []
631
        for trans_id in self._new_parent:
632
            seen = set()
633
            parent_id = trans_id
6434.1.1 by Wouter van Heyst
Test for equality instead of object identity where ROOT_PARENT is concerned.
634
            while parent_id != ROOT_PARENT:
1534.7.19 by Aaron Bentley
Added tests for parent loops
635
                seen.add(parent_id)
1731.1.33 by Aaron Bentley
Revert no-special-root changes
636
                try:
637
                    parent_id = self.final_parent(parent_id)
638
                except KeyError:
639
                    break
1534.7.19 by Aaron Bentley
Added tests for parent loops
640
                if parent_id == trans_id:
641
                    conflicts.append(('parent loop', trans_id))
642
                if parent_id in seen:
643
                    break
644
        return conflicts
645
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
646
    def _unversioned_parents(self, by_parent):
647
        """If parent directories are versioned, children must be versioned."""
648
        conflicts = []
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
649
        for parent_id, children in viewitems(by_parent):
6434.1.1 by Wouter van Heyst
Test for equality instead of object identity where ROOT_PARENT is concerned.
650
            if parent_id == ROOT_PARENT:
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
651
                continue
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
652
            if self.final_file_id(parent_id) is not None:
653
                continue
654
            for child_id in children:
655
                if self.final_file_id(child_id) is not None:
656
                    conflicts.append(('unversioned parent', parent_id))
7143.15.2 by Jelmer Vernooij
Run autopep8.
657
                    break
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
658
        return conflicts
659
660
    def _improper_versioning(self):
1534.7.156 by Aaron Bentley
PEP8 fixes
661
        """Cannot version a file with no contents, or a bad type.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
662
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
663
        However, existing entries with no contents are okay.
664
        """
665
        conflicts = []
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
666
        for trans_id in self._new_id:
4597.9.7 by Vincent Ladeuil
transform.final_kind() now returns None instead of raising NoSuchFile.
667
            kind = self.final_kind(trans_id)
7122.6.3 by Jelmer Vernooij
Merge trunk.
668
            if kind == 'symlink' and not self._tree.supports_symlinks():
6469.1.1 by Parth Malwankar
initial support for checking out files with softlinks
669
                # Ignore symlinks as they are not supported on this platform
670
                continue
4597.9.7 by Vincent Ladeuil
transform.final_kind() now returns None instead of raising NoSuchFile.
671
            if kind is None:
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
672
                conflicts.append(('versioning no contents', trans_id))
673
                continue
6929.3.3 by Jelmer Vernooij
Add Tree.versionable_kind.
674
            if not self._tree.versionable_kind(kind):
1534.7.20 by Aaron Bentley
Added directory handling
675
                conflicts.append(('versioning bad kind', trans_id, kind))
1534.7.11 by Aaron Bentley
Refactored conflict handling
676
        return conflicts
677
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
678
    def _executability_conflicts(self):
1534.7.40 by Aaron Bentley
Updated docs
679
        """Check for bad executability changes.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
680
1534.7.40 by Aaron Bentley
Updated docs
681
        Only versioned files may have their executability set, because
682
        1. only versioned entries can have executability under windows
683
        2. only files can be executable.  (The execute bit on a directory
684
           does not indicate searchability)
685
        """
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
686
        conflicts = []
687
        for trans_id in self._new_executability:
688
            if self.final_file_id(trans_id) is None:
689
                conflicts.append(('unversioned executability', trans_id))
1534.7.34 by Aaron Bentley
Proper conflicts for removals
690
            else:
4597.9.7 by Vincent Ladeuil
transform.final_kind() now returns None instead of raising NoSuchFile.
691
                if self.final_kind(trans_id) != "file":
1534.7.34 by Aaron Bentley
Proper conflicts for removals
692
                    conflicts.append(('non-file executability', trans_id))
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
693
        return conflicts
694
1534.7.152 by Aaron Bentley
Fixed overwrites
695
    def _overwrite_conflicts(self):
696
        """Check for overwrites (not permitted on Win32)"""
697
        conflicts = []
698
        for trans_id in self._new_contents:
4597.9.13 by Vincent Ladeuil
bzrlib.transform.TreeTransform.tree_kind and
699
            if self.tree_kind(trans_id) is None:
1534.7.152 by Aaron Bentley
Fixed overwrites
700
                continue
701
            if trans_id not in self._removed_contents:
702
                conflicts.append(('overwrite', trans_id,
7143.15.2 by Jelmer Vernooij
Run autopep8.
703
                                  self.final_name(trans_id)))
1534.7.152 by Aaron Bentley
Fixed overwrites
704
        return conflicts
705
1534.7.11 by Aaron Bentley
Refactored conflict handling
706
    def _duplicate_entries(self, by_parent):
707
        """No directory may have two entries with the same name."""
708
        conflicts = []
2590.2.16 by Aaron Bentley
Shortcut duplicate_entries conflict check if no new names introduced
709
        if (self._new_name, self._new_parent) == ({}, {}):
710
            return conflicts
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
711
        for children in viewvalues(by_parent):
5050.51.1 by Vincent Ladeuil
Don't crash when --take-other (or --take-this) is called for a text conflict
712
            name_ids = []
713
            for child_tid in children:
714
                name = self.final_name(child_tid)
715
                if name is not None:
716
                    # Keep children only if they still exist in the end
717
                    if not self._case_sensitive_target:
718
                        name = name.lower()
719
                    name_ids.append((name, child_tid))
1534.7.6 by Aaron Bentley
Added conflict handling
720
            name_ids.sort()
721
            last_name = None
722
            last_trans_id = None
723
            for name, trans_id in name_ids:
4597.9.7 by Vincent Ladeuil
transform.final_kind() now returns None instead of raising NoSuchFile.
724
                kind = self.final_kind(trans_id)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
725
                file_id = self.final_file_id(trans_id)
726
                if kind is None and file_id is None:
727
                    continue
1534.7.6 by Aaron Bentley
Added conflict handling
728
                if name == last_name:
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
729
                    conflicts.append(('duplicate', last_trans_id, trans_id,
7143.15.2 by Jelmer Vernooij
Run autopep8.
730
                                      name))
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
731
                last_name = name
732
                last_trans_id = trans_id
1534.7.11 by Aaron Bentley
Refactored conflict handling
733
        return conflicts
734
735
    def _parent_type_conflicts(self, by_parent):
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
736
        """Children must have a directory parent"""
1534.7.11 by Aaron Bentley
Refactored conflict handling
737
        conflicts = []
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
738
        for parent_id, children in viewitems(by_parent):
6434.1.1 by Wouter van Heyst
Test for equality instead of object identity where ROOT_PARENT is concerned.
739
            if parent_id == ROOT_PARENT:
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
740
                continue
5540.3.2 by Vincent Ladeuil
Better name for the local variable/
741
            no_children = True
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
742
            for child_id in children:
743
                if self.final_kind(child_id) is not None:
5540.3.2 by Vincent Ladeuil
Better name for the local variable/
744
                    no_children = False
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
745
                    break
5540.3.2 by Vincent Ladeuil
Better name for the local variable/
746
            if no_children:
1534.7.37 by Aaron Bentley
Allowed removed dirs to have content-free children.
747
                continue
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
748
            # There is at least a child, so we need an existing directory to
749
            # contain it.
4597.9.7 by Vincent Ladeuil
transform.final_kind() now returns None instead of raising NoSuchFile.
750
            kind = self.final_kind(parent_id)
1534.7.10 by Aaron Bentley
Implemented missing parent and non-directory parent conflicts
751
            if kind is None:
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
752
                # The directory will be deleted
1534.7.10 by Aaron Bentley
Implemented missing parent and non-directory parent conflicts
753
                conflicts.append(('missing parent', parent_id))
754
            elif kind != "directory":
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
755
                # Meh, we need a *directory* to put something in it
1534.7.10 by Aaron Bentley
Implemented missing parent and non-directory parent conflicts
756
                conflicts.append(('non-directory parent', parent_id))
1534.7.6 by Aaron Bentley
Added conflict handling
757
        return conflicts
1534.7.37 by Aaron Bentley
Allowed removed dirs to have content-free children.
758
3619.2.8 by Aaron Bentley
Reorganize execute-bit handling
759
    def _set_executability(self, path, trans_id):
1534.7.40 by Aaron Bentley
Updated docs
760
        """Set the executability of versioned files """
6379.7.1 by Jelmer Vernooij
Add and use WorkingTree._supports_executable.
761
        if self._tree._supports_executable():
3619.2.8 by Aaron Bentley
Reorganize execute-bit handling
762
            new_executability = self._new_executability[trans_id]
1534.7.25 by Aaron Bentley
Added set_executability
763
            abspath = self._tree.abspath(path)
764
            current_mode = os.stat(abspath).st_mode
765
            if new_executability:
766
                umask = os.umask(0)
767
                os.umask(umask)
6619.3.14 by Jelmer Vernooij
Convert some octal numbers to new notations.
768
                to_mode = current_mode | (0o100 & ~umask)
1534.7.25 by Aaron Bentley
Added set_executability
769
                # Enable x-bit for others only if they can read it.
6619.3.14 by Jelmer Vernooij
Convert some octal numbers to new notations.
770
                if current_mode & 0o004:
771
                    to_mode |= 0o001 & ~umask
772
                if current_mode & 0o040:
773
                    to_mode |= 0o010 & ~umask
1534.7.25 by Aaron Bentley
Added set_executability
774
            else:
6619.3.14 by Jelmer Vernooij
Convert some octal numbers to new notations.
775
                to_mode = current_mode & ~0o111
6015.50.1 by Martin Pool
Use a chmod wrapper to cope with eperm from chmod
776
            osutils.chmod_if_possible(abspath, to_mode)
1534.7.25 by Aaron Bentley
Added set_executability
777
1534.7.23 by Aaron Bentley
Transform.new_entry -> Transform._new_entry
778
    def _new_entry(self, name, parent_id, file_id):
1534.7.21 by Aaron Bentley
Updated docstrings
779
        """Helper function to create a new filesystem entry."""
1534.7.2 by Aaron Bentley
Added convenience function
780
        trans_id = self.create_path(name, parent_id)
781
        if file_id is not None:
7490.77.8 by Jelmer Vernooij
Change argument order for Transform.version_file.
782
            self.version_file(trans_id, file_id=file_id)
1534.7.2 by Aaron Bentley
Added convenience function
783
        return trans_id
784
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
785
    def new_file(self, name, parent_id, contents, file_id=None,
5752.3.4 by John Arbash Meinel
Add new_file(sha1=XXX) and pass that down to create_file.
786
                 executable=None, sha1=None):
1534.7.156 by Aaron Bentley
PEP8 fixes
787
        """Convenience method to create files.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
788
1534.7.21 by Aaron Bentley
Updated docstrings
789
        name is the name of the file to create.
790
        parent_id is the transaction id of the parent directory of the file.
791
        contents is an iterator of bytestrings, which will be used to produce
792
        the file.
1740.2.4 by Aaron Bentley
Update transform tests and docs
793
        :param file_id: The inventory ID of the file, if it is to be versioned.
794
        :param executable: Only valid when a file_id has been supplied.
1534.7.21 by Aaron Bentley
Updated docstrings
795
        """
1534.7.23 by Aaron Bentley
Transform.new_entry -> Transform._new_entry
796
        trans_id = self._new_entry(name, parent_id, file_id)
1740.2.4 by Aaron Bentley
Update transform tests and docs
797
        # TODO: rather than scheduling a set_executable call,
798
        # have create_file create the file with the right mode.
5752.3.4 by John Arbash Meinel
Add new_file(sha1=XXX) and pass that down to create_file.
799
        self.create_file(contents, trans_id, sha1=sha1)
1534.7.27 by Aaron Bentley
Added execute bit to new_file method
800
        if executable is not None:
801
            self.set_executability(executable, trans_id)
1534.7.20 by Aaron Bentley
Added directory handling
802
        return trans_id
803
804
    def new_directory(self, name, parent_id, file_id=None):
1534.7.156 by Aaron Bentley
PEP8 fixes
805
        """Convenience method to create directories.
1534.7.21 by Aaron Bentley
Updated docstrings
806
807
        name is the name of the directory to create.
808
        parent_id is the transaction id of the parent directory of the
809
        directory.
810
        file_id is the inventory ID of the directory, if it is to be versioned.
811
        """
1534.7.23 by Aaron Bentley
Transform.new_entry -> Transform._new_entry
812
        trans_id = self._new_entry(name, parent_id, file_id)
1534.7.20 by Aaron Bentley
Added directory handling
813
        self.create_directory(trans_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
814
        return trans_id
1534.7.20 by Aaron Bentley
Added directory handling
815
1534.7.22 by Aaron Bentley
Added symlink support
816
    def new_symlink(self, name, parent_id, target, file_id=None):
1534.7.156 by Aaron Bentley
PEP8 fixes
817
        """Convenience method to create symbolic link.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
818
1534.7.22 by Aaron Bentley
Added symlink support
819
        name is the name of the symlink to create.
820
        parent_id is the transaction id of the parent directory of the symlink.
821
        target is a bytestring of the target of the symlink.
822
        file_id is the inventory ID of the file, if it is to be versioned.
823
        """
1534.7.23 by Aaron Bentley
Transform.new_entry -> Transform._new_entry
824
        trans_id = self._new_entry(name, parent_id, file_id)
1534.7.22 by Aaron Bentley
Added symlink support
825
        self.create_symlink(target, trans_id)
826
        return trans_id
827
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
828
    def new_orphan(self, trans_id, parent_id):
829
        """Schedule an item to be orphaned.
830
831
        When a directory is about to be removed, its children, if they are not
832
        versioned are moved out of the way: they don't have a parent anymore.
833
834
        :param trans_id: The trans_id of the existing item.
835
        :param parent_id: The parent trans_id of the item.
836
        """
837
        raise NotImplementedError(self.new_orphan)
838
5409.1.14 by Vincent Ladeuil
Prepare for more ways to handle orphans.
839
    def _get_potential_orphans(self, dir_id):
840
        """Find the potential orphans in a directory.
841
842
        A directory can't be safely deleted if there are versioned files in it.
843
        If all the contained files are unversioned then they can be orphaned.
844
845
        The 'None' return value means that the directory contains at least one
846
        versioned file and should not be deleted.
847
848
        :param dir_id: The directory trans id.
849
850
        :return: A list of the orphan trans ids or None if at least one
851
             versioned file is present.
852
        """
853
        orphans = []
854
        # Find the potential orphans, stop if one item should be kept
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
855
        for child_tid in self.by_parent()[dir_id]:
856
            if child_tid in self._removed_contents:
857
                # The child is removed as part of the transform. Since it was
858
                # versioned before, it's not an orphan
859
                continue
7490.83.1 by Jelmer Vernooij
Add abstract methods.
860
            if self.final_file_id(child_tid) is None:
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
861
                # The child is not versioned
862
                orphans.append(child_tid)
5409.1.14 by Vincent Ladeuil
Prepare for more ways to handle orphans.
863
            else:
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
864
                # We have a versioned file here, searching for orphans is
865
                # meaningless.
866
                orphans = None
5409.1.14 by Vincent Ladeuil
Prepare for more ways to handle orphans.
867
                break
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
868
        return orphans
5409.1.14 by Vincent Ladeuil
Prepare for more ways to handle orphans.
869
1551.11.12 by Aaron Bentley
Changes from review
870
    def _affected_ids(self):
871
        """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
872
        trans_ids = set(self._removed_id)
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
873
        trans_ids.update(self._new_id)
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
874
        trans_ids.update(self._removed_contents)
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
875
        trans_ids.update(self._new_contents)
876
        trans_ids.update(self._new_executability)
877
        trans_ids.update(self._new_name)
878
        trans_ids.update(self._new_parent)
1551.11.12 by Aaron Bentley
Changes from review
879
        return trans_ids
880
881
    def _get_file_id_maps(self):
882
        """Return mapping of file_ids to trans_ids in the to and from states"""
883
        trans_ids = self._affected_ids()
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
884
        from_trans_ids = {}
885
        to_trans_ids = {}
886
        # Build up two dicts: trans_ids associated with file ids in the
887
        # FROM state, vs the TO state.
888
        for trans_id in trans_ids:
889
            from_file_id = self.tree_file_id(trans_id)
890
            if from_file_id is not None:
891
                from_trans_ids[from_file_id] = trans_id
892
            to_file_id = self.final_file_id(trans_id)
893
            if to_file_id is not None:
894
                to_trans_ids[to_file_id] = trans_id
1551.11.12 by Aaron Bentley
Changes from review
895
        return from_trans_ids, to_trans_ids
896
6885.5.5 by Jelmer Vernooij
Use specific_files rather than specific_file_ids in transform.
897
    def _from_file_data(self, from_trans_id, from_versioned, from_path):
1551.11.12 by Aaron Bentley
Changes from review
898
        """Get data about a file in the from (tree) state
899
900
        Return a (name, parent, kind, executable) tuple
901
        """
902
        from_path = self._tree_id_paths.get(from_trans_id)
903
        if from_versioned:
904
            # get data from working tree if versioned
6855.3.4 by Jelmer Vernooij
Merge trunk.
905
            from_entry = next(self._tree.iter_entries_by_dir(
7143.15.2 by Jelmer Vernooij
Run autopep8.
906
                specific_files=[from_path]))[1]
1551.11.12 by Aaron Bentley
Changes from review
907
            from_name = from_entry.name
908
            from_parent = from_entry.parent_id
909
        else:
910
            from_entry = None
911
            if from_path is None:
912
                # File does not exist in FROM state
913
                from_name = None
914
                from_parent = None
915
            else:
916
                # File exists, but is not versioned.  Have to use path-
917
                # splitting stuff
918
                from_name = os.path.basename(from_path)
919
                tree_parent = self.get_tree_parent(from_trans_id)
920
                from_parent = self.tree_file_id(tree_parent)
921
        if from_path is not None:
922
            from_kind, from_executable, from_stats = \
923
                self._tree._comparison_data(from_entry, from_path)
924
        else:
925
            from_kind = None
926
            from_executable = False
927
        return from_name, from_parent, from_kind, from_executable
928
929
    def _to_file_data(self, to_trans_id, from_trans_id, from_executable):
930
        """Get data about a file in the to (target) state
931
932
        Return a (name, parent, kind, executable) tuple
933
        """
934
        to_name = self.final_name(to_trans_id)
4597.9.7 by Vincent Ladeuil
transform.final_kind() now returns None instead of raising NoSuchFile.
935
        to_kind = self.final_kind(to_trans_id)
1551.11.12 by Aaron Bentley
Changes from review
936
        to_parent = self.final_file_id(self.final_parent(to_trans_id))
937
        if to_trans_id in self._new_executability:
938
            to_executable = self._new_executability[to_trans_id]
939
        elif to_trans_id == from_trans_id:
940
            to_executable = from_executable
941
        else:
942
            to_executable = False
943
        return to_name, to_parent, to_kind, to_executable
944
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
945
    def iter_changes(self):
946
        """Produce output in the same format as Tree.iter_changes.
1551.11.12 by Aaron Bentley
Changes from review
947
948
        Will produce nonsensical results if invoked while inventory/filesystem
949
        conflicts (as reported by TreeTransform.find_conflicts()) are present.
950
951
        This reads the Transform, but only reproduces changes involving a
952
        file_id.  Files that are not versioned in either of the FROM or TO
953
        states are not reflected.
954
        """
955
        final_paths = FinalPaths(self)
956
        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
957
        results = []
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
958
        # Now iterate through all active file_ids
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
959
        for file_id in set(from_trans_ids).union(to_trans_ids):
1551.11.7 by Aaron Bentley
Stop modified flag bleeding into later changes
960
            modified = False
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
961
            from_trans_id = from_trans_ids.get(file_id)
962
            # find file ids, and determine versioning state
963
            if from_trans_id is None:
964
                from_versioned = False
965
                from_trans_id = to_trans_ids[file_id]
966
            else:
967
                from_versioned = True
968
            to_trans_id = to_trans_ids.get(file_id)
969
            if to_trans_id is None:
970
                to_versioned = False
971
                to_trans_id = from_trans_id
972
            else:
973
                to_versioned = True
1551.11.12 by Aaron Bentley
Changes from review
974
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
975
            if not from_versioned:
976
                from_path = None
977
            else:
978
                from_path = self._tree_id_paths.get(from_trans_id)
979
            if not to_versioned:
980
                to_path = None
981
            else:
982
                to_path = final_paths.get_path(to_trans_id)
6885.5.5 by Jelmer Vernooij
Use specific_files rather than specific_file_ids in transform.
983
984
            from_name, from_parent, from_kind, from_executable = \
985
                self._from_file_data(from_trans_id, from_versioned, from_path)
986
987
            to_name, to_parent, to_kind, to_executable = \
988
                self._to_file_data(to_trans_id, from_trans_id, from_executable)
989
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
990
            if from_kind != to_kind:
991
                modified = True
1551.10.37 by Aaron Bentley
recommit of TreeTransform._iter_changes fix with missing files
992
            elif to_kind in ('file', 'symlink') and (
7143.15.2 by Jelmer Vernooij
Run autopep8.
993
                    to_trans_id != from_trans_id
994
                    or to_trans_id in self._new_contents):
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
995
                modified = True
7143.15.2 by Jelmer Vernooij
Run autopep8.
996
            if (not modified and from_versioned == to_versioned
997
                and from_parent == to_parent and from_name == to_name
998
                    and from_executable == to_executable):
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
999
                continue
7322.1.6 by Jelmer Vernooij
Use the new attributes on TreeChange.
1000
            results.append(
1001
                TreeChange(
1002
                    file_id, (from_path, to_path), modified,
1003
                    (from_versioned, to_versioned),
1004
                    (from_parent, to_parent),
1005
                    (from_name, to_name),
1006
                    (from_kind, to_kind),
1007
                    (from_executable, to_executable)))
7058.4.9 by Jelmer Vernooij
Fix a transform to.
1008
7322.1.6 by Jelmer Vernooij
Use the new attributes on TreeChange.
1009
        def path_key(c):
1010
            return (c.path[0] or '', c.path[1] or '')
7058.4.9 by Jelmer Vernooij
Fix a transform to.
1011
        return iter(sorted(results, key=path_key))
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1012
4354.4.4 by Aaron Bentley
Simplify by using CommitBuilder directly
1013
    def get_preview_tree(self):
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
1014
        """Return a tree representing the result of the transform.
1015
4634.57.4 by Aaron Bentley
Update docs
1016
        The tree is a snapshot, and altering the TreeTransform will invalidate
1017
        it.
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
1018
        """
7490.77.4 by Jelmer Vernooij
Move some errors around.
1019
        raise NotImplementedError(self.get_preview)
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
1020
5162.4.1 by Aaron Bentley
TreeTransform supports normal commit parameters and includes branch nick.
1021
    def commit(self, branch, message, merge_parents=None, strict=False,
1022
               timestamp=None, timezone=None, committer=None, authors=None,
1023
               revprops=None, revision_id=None):
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
1024
        """Commit the result of this TreeTransform to a branch.
1025
1026
        :param branch: The branch to commit to.
1027
        :param message: The message to attach to the commit.
5162.4.1 by Aaron Bentley
TreeTransform supports normal commit parameters and includes branch nick.
1028
        :param merge_parents: Additional parent revision-ids specified by
1029
            pending merges.
1030
        :param strict: If True, abort the commit if there are unversioned
1031
            files.
1032
        :param timestamp: if not None, seconds-since-epoch for the time and
1033
            date.  (May be a float.)
1034
        :param timezone: Optional timezone for timestamp, as an offset in
1035
            seconds.
1036
        :param committer: Optional committer in email-id format.
1037
            (e.g. "J Random Hacker <jrandom@example.com>")
1038
        :param authors: Optional list of authors in email-id format.
1039
        :param revprops: Optional dictionary of revision properties.
1040
        :param revision_id: Optional revision id.  (Specifying a revision-id
1041
            may reduce performance for some non-native formats.)
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
1042
        :return: The revision_id of the revision committed.
1043
        """
4526.8.6 by Aaron Bentley
Check for malformed transforms before committing.
1044
        self._check_malformed()
4526.8.2 by Aaron Bentley
Proved strict commit handling.
1045
        if strict:
1046
            unversioned = set(self._new_contents).difference(set(self._new_id))
1047
            for trans_id in unversioned:
1048
                if self.final_file_id(trans_id) is None:
1049
                    raise errors.StrictCommitFailed()
4526.8.3 by Aaron Bentley
Clean up merge parent handling.
1050
1051
        revno, last_rev_id = branch.last_revision_info()
1052
        if last_rev_id == _mod_revision.NULL_REVISION:
1053
            if merge_parents is not None:
4526.8.5 by Aaron Bentley
Updates from review.
1054
                raise ValueError('Cannot supply merge parents for first'
1055
                                 ' commit.')
4526.8.3 by Aaron Bentley
Clean up merge parent handling.
1056
            parent_ids = []
1057
        else:
1058
            parent_ids = [last_rev_id]
1059
            if merge_parents is not None:
1060
                parent_ids.extend(merge_parents)
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
1061
        if self._tree.get_revision_id() != last_rev_id:
4526.8.5 by Aaron Bentley
Updates from review.
1062
            raise ValueError('TreeTransform not based on branch basis: %s' %
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
1063
                             self._tree.get_revision_id().decode('utf-8'))
7490.77.11 by Jelmer Vernooij
Merge lp:brz/3.1.
1064
        from . import commit
5162.4.1 by Aaron Bentley
TreeTransform supports normal commit parameters and includes branch nick.
1065
        revprops = commit.Commit.update_revprops(revprops, branch, authors)
1066
        builder = branch.get_commit_builder(parent_ids,
1067
                                            timestamp=timestamp,
5162.4.3 by Aaron Bentley
Fix failing test.
1068
                                            timezone=timezone,
5162.4.1 by Aaron Bentley
TreeTransform supports normal commit parameters and includes branch nick.
1069
                                            committer=committer,
1070
                                            revprops=revprops,
1071
                                            revision_id=revision_id)
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
1072
        preview = self.get_preview_tree()
1073
        list(builder.record_iter_changes(preview, last_rev_id,
1074
                                         self.iter_changes()))
1075
        builder.finish_inventory()
1076
        revision_id = builder.commit(message)
1077
        branch.set_last_revision_info(revno + 1, revision_id)
1078
        return revision_id
1079
0.13.24 by Aaron Bentley
Update to use Tree.readlines, if possible.
1080
    def _text_parent(self, trans_id):
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
1081
        path = self.tree_path(trans_id)
0.13.24 by Aaron Bentley
Update to use Tree.readlines, if possible.
1082
        try:
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
1083
            if path is None or self._tree.kind(path) != 'file':
0.13.24 by Aaron Bentley
Update to use Tree.readlines, if possible.
1084
                return None
1085
        except errors.NoSuchFile:
1086
            return None
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
1087
        return path
0.13.24 by Aaron Bentley
Update to use Tree.readlines, if possible.
1088
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1089
    def _get_parents_texts(self, trans_id):
0.13.9 by Aaron Bentley
Update docs
1090
        """Get texts for compression parents of this file."""
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
1091
        path = self._text_parent(trans_id)
1092
        if path is None:
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1093
            return ()
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
1094
        return (self._tree.get_file_text(path),)
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1095
1096
    def _get_parents_lines(self, trans_id):
0.13.9 by Aaron Bentley
Update docs
1097
        """Get lines for compression parents of this file."""
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
1098
        path = self._text_parent(trans_id)
1099
        if path is None:
0.13.24 by Aaron Bentley
Update to use Tree.readlines, if possible.
1100
            return ()
6883.4.1 by Jelmer Vernooij
Avoid using tree file ids where possible.
1101
        return (self._tree.get_file_lines(path),)
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1102
1103
    def serialize(self, serializer):
0.13.9 by Aaron Bentley
Update docs
1104
        """Serialize this TreeTransform.
1105
1106
        :param serializer: A Serialiser like pack.ContainerSerializer.
1107
        """
7490.83.1 by Jelmer Vernooij
Add abstract methods.
1108
        from . import bencode
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
1109
        new_name = {k.encode('utf-8'): v.encode('utf-8')
1110
                    for k, v in viewitems(self._new_name)}
1111
        new_parent = {k.encode('utf-8'): v.encode('utf-8')
1112
                      for k, v in viewitems(self._new_parent)}
1113
        new_id = {k.encode('utf-8'): v
1114
                  for k, v in viewitems(self._new_id)}
7045.4.7 by Jelmer Vernooij
Fix remaining tests.
1115
        new_executability = {k.encode('utf-8'): int(v)
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
1116
                             for k, v in viewitems(self._new_executability)}
1117
        tree_path_ids = {k.encode('utf-8'): v.encode('utf-8')
1118
                         for k, v in viewitems(self._tree_path_ids)}
1119
        non_present_ids = {k: v.encode('utf-8')
1120
                           for k, v in viewitems(self._non_present_ids)}
1121
        removed_contents = [trans_id.encode('utf-8')
1122
                            for trans_id in self._removed_contents]
1123
        removed_id = [trans_id.encode('utf-8')
1124
                      for trans_id in self._removed_id]
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1125
        attribs = {
6973.7.5 by Jelmer Vernooij
s/file/open.
1126
            b'_id_number': self._id_number,
1127
            b'_new_name': new_name,
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
1128
            b'_new_parent': new_parent,
6973.7.5 by Jelmer Vernooij
s/file/open.
1129
            b'_new_executability': new_executability,
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
1130
            b'_new_id': new_id,
6973.7.5 by Jelmer Vernooij
s/file/open.
1131
            b'_tree_path_ids': tree_path_ids,
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
1132
            b'_removed_id': removed_id,
1133
            b'_removed_contents': removed_contents,
1134
            b'_non_present_ids': non_present_ids,
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1135
            }
1136
        yield serializer.bytes_record(bencode.bencode(attribs),
6973.12.3 by Jelmer Vernooij
Fixes.
1137
                                      ((b'attribs',),))
7058.3.1 by Jelmer Vernooij
Some more sortin'.
1138
        for trans_id, kind in sorted(viewitems(self._new_contents)):
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1139
            if kind == 'file':
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
1140
                with open(self._limbo_name(trans_id), 'rb') as cur_file:
1141
                    lines = cur_file.readlines()
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1142
                parents = self._get_parents_lines(trans_id)
1143
                mpdiff = multiparent.MultiParent.from_lines(lines, parents)
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
1144
                content = b''.join(mpdiff.to_patch())
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1145
            if kind == 'directory':
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
1146
                content = b''
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1147
            if kind == 'symlink':
7045.3.2 by Jelmer Vernooij
Fix tests.
1148
                content = self._read_symlink_target(trans_id)
1149
                if not isinstance(content, bytes):
1150
                    content = content.encode('utf-8')
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
1151
            yield serializer.bytes_record(
7143.15.2 by Jelmer Vernooij
Run autopep8.
1152
                content, ((trans_id.encode('utf-8'), kind.encode('ascii')),))
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1153
1154
    def deserialize(self, records):
0.13.9 by Aaron Bentley
Update docs
1155
        """Deserialize a stored TreeTransform.
1156
1157
        :param records: An iterable of (names, content) tuples, as per
1158
            pack.ContainerPushParser.
1159
        """
7490.83.1 by Jelmer Vernooij
Add abstract methods.
1160
        from . import bencode
6634.2.1 by Martin
Apply 2to3 next fixer and make compatible
1161
        names, content = next(records)
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1162
        attribs = bencode.bdecode(content)
6973.7.5 by Jelmer Vernooij
s/file/open.
1163
        self._id_number = attribs[b'_id_number']
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
1164
        self._new_name = {k.decode('utf-8'): v.decode('utf-8')
1165
                          for k, v in viewitems(attribs[b'_new_name'])}
1166
        self._new_parent = {k.decode('utf-8'): v.decode('utf-8')
1167
                            for k, v in viewitems(attribs[b'_new_parent'])}
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
1168
        self._new_executability = {
1169
            k.decode('utf-8'): bool(v)
1170
            for k, v in viewitems(attribs[b'_new_executability'])}
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
1171
        self._new_id = {k.decode('utf-8'): v
1172
                        for k, v in viewitems(attribs[b'_new_id'])}
1173
        self._r_new_id = {v: k for k, v in viewitems(self._new_id)}
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1174
        self._tree_path_ids = {}
1175
        self._tree_id_paths = {}
6973.7.5 by Jelmer Vernooij
s/file/open.
1176
        for bytepath, trans_id in viewitems(attribs[b'_tree_path_ids']):
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1177
            path = bytepath.decode('utf-8')
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
1178
            trans_id = trans_id.decode('utf-8')
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1179
            self._tree_path_ids[path] = trans_id
1180
            self._tree_id_paths[trans_id] = path
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
1181
        self._removed_id = {trans_id.decode('utf-8')
1182
                            for trans_id in attribs[b'_removed_id']}
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
1183
        self._removed_contents = set(
1184
            trans_id.decode('utf-8')
1185
            for trans_id in attribs[b'_removed_contents'])
1186
        self._non_present_ids = {
1187
            k: v.decode('utf-8')
1188
            for k, v in viewitems(attribs[b'_non_present_ids'])}
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1189
        for ((trans_id, kind),), content in records:
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
1190
            trans_id = trans_id.decode('utf-8')
1191
            kind = kind.decode('ascii')
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1192
            if kind == 'file':
1193
                mpdiff = multiparent.MultiParent.from_patch(content)
1194
                lines = mpdiff.to_lines(self._get_parents_texts(trans_id))
1195
                self.create_file(lines, trans_id)
1196
            if kind == 'directory':
1197
                self.create_directory(trans_id)
1198
            if kind == 'symlink':
0.13.16 by Aaron Bentley
Add unicode symlink targets to tests
1199
                self.create_symlink(content.decode('utf-8'), trans_id)
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
1200
7350.3.3 by Jelmer Vernooij
Add abstract methods.
1201
    def create_file(self, contents, trans_id, mode_id=None, sha1=None):
1202
        """Schedule creation of a new file.
1203
1204
        :seealso: new_file.
1205
1206
        :param contents: an iterator of strings, all of which will be written
1207
            to the target destination.
1208
        :param trans_id: TreeTransform handle
1209
        :param mode_id: If not None, force the mode of the target file to match
1210
            the mode of the object referenced by mode_id.
1211
            Otherwise, we will try to preserve mode bits of an existing file.
1212
        :param sha1: If the sha1 of this content is already known, pass it in.
1213
            We can use it to prevent future sha1 computations.
1214
        """
1215
        raise NotImplementedError(self.create_file)
1216
1217
    def create_directory(self, trans_id):
1218
        """Schedule creation of a new directory.
1219
1220
        See also new_directory.
1221
        """
1222
        raise NotImplementedError(self.create_directory)
1223
1224
    def create_symlink(self, target, trans_id):
1225
        """Schedule creation of a new symbolic link.
1226
1227
        target is a bytestring.
1228
        See also new_symlink.
1229
        """
1230
        raise NotImplementedError(self.create_symlink)
1231
1232
    def create_hardlink(self, path, trans_id):
1233
        """Schedule creation of a hard link"""
1234
        raise NotImplementedError(self.create_hardlink)
1235
1236
    def cancel_creation(self, trans_id):
1237
        """Cancel the creation of new file contents."""
1238
        raise NotImplementedError(self.cancel_creation)
1239
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1240
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1241
class DiskTreeTransform(TreeTransformBase):
1242
    """Tree transform storing its contents on disk."""
1243
7122.6.3 by Jelmer Vernooij
Merge trunk.
1244
    def __init__(self, tree, limbodir, pb=None, case_sensitive=True):
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1245
        """Constructor.
1246
        :param tree: The tree that will be transformed, but not necessarily
1247
            the output tree.
1248
        :param limbodir: A directory where new files can be stored until
1249
            they are installed in their proper places
4961.2.4 by Martin Pool
Delete deprecated ProgressBar constructor
1250
        :param pb: ignored
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1251
        :param case_sensitive: If True, the target of the transform is
1252
            case sensitive, not just case preserving.
1253
        """
1254
        TreeTransformBase.__init__(self, tree, pb, case_sensitive)
1255
        self._limbodir = limbodir
1256
        self._deletiondir = None
1257
        # A mapping of transform ids to their limbo filename
1258
        self._limbo_files = {}
5876.4.4 by Andrew Bennetts
Fix edge cases in handling interrupts during _rename_in_limbo, with messy tests
1259
        self._possibly_stale_limbo_files = set()
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1260
        # A mapping of transform ids to a set of the transform ids of children
1261
        # that their limbo directory has
1262
        self._limbo_children = {}
1263
        # Map transform ids to maps of child filename to child transform id
1264
        self._limbo_children_names = {}
1265
        # List of transform ids that need to be renamed from limbo into place
1266
        self._needs_rename = set()
4934.1.2 by John Arbash Meinel
Move the functionality into osutils / extensions.
1267
        self._creation_mtime = None
7122.6.5 by Jelmer Vernooij
More improvements, add tests.
1268
        self._create_symlinks = osutils.supports_symlinks(self._limbodir)
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1269
1270
    def finalize(self):
1271
        """Release the working tree lock, if held, clean up limbo dir.
1272
1273
        This is required if apply has not been invoked, but can be invoked
1274
        even after apply.
1275
        """
1276
        if self._tree is None:
1277
            return
1278
        try:
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
1279
            limbo_paths = list(viewvalues(self._limbo_files))
1280
            limbo_paths.extend(self._possibly_stale_limbo_files)
1281
            limbo_paths.sort(reverse=True)
5876.4.1 by Andrew Bennetts
Experimental changes to fix 597686.
1282
            for path in limbo_paths:
1283
                try:
1284
                    delete_any(path)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1285
                except OSError as e:
5876.4.1 by Andrew Bennetts
Experimental changes to fix 597686.
1286
                    if e.errno != errno.ENOENT:
1287
                        raise
1288
                    # XXX: warn? perhaps we just got interrupted at an
1289
                    # inconvenient moment, but perhaps files are disappearing
1290
                    # from under us?
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1291
            try:
4440.1.1 by Craig Hewetson
bug fixes for:
1292
                delete_any(self._limbodir)
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1293
            except OSError:
1294
                # We don't especially care *why* the dir is immortal.
1295
                raise ImmortalLimbo(self._limbodir)
1296
            try:
1297
                if self._deletiondir is not None:
4440.1.1 by Craig Hewetson
bug fixes for:
1298
                    delete_any(self._deletiondir)
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1299
            except OSError:
1300
                raise errors.ImmortalPendingDeletion(self._deletiondir)
1301
        finally:
1302
            TreeTransformBase.finalize(self)
1303
6379.7.4 by Jelmer Vernooij
Fix supports_executable for limbo.
1304
    def _limbo_supports_executable(self):
1305
        """Check if the limbo path supports the executable bit."""
7122.7.1 by Jelmer Vernooij
Check for fs type to determine whether executable bit is supported.
1306
        return osutils.supports_executable(self._limbodir)
6379.7.4 by Jelmer Vernooij
Fix supports_executable for limbo.
1307
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1308
    def _limbo_name(self, trans_id):
1309
        """Generate the limbo name of a file"""
1310
        limbo_name = self._limbo_files.get(trans_id)
4634.79.1 by Aaron Bentley
TransformPreview uses ascii-only filenames.
1311
        if limbo_name is None:
1312
            limbo_name = self._generate_limbo_path(trans_id)
1313
            self._limbo_files[trans_id] = limbo_name
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1314
        return limbo_name
1315
4634.79.1 by Aaron Bentley
TransformPreview uses ascii-only filenames.
1316
    def _generate_limbo_path(self, trans_id):
1317
        """Generate a limbo path using the trans_id as the relative path.
1318
1319
        This is suitable as a fallback, and when the transform should not be
1320
        sensitive to the path encoding of the limbo directory.
1321
        """
1322
        self._needs_rename.add(trans_id)
1323
        return pathjoin(self._limbodir, trans_id)
1324
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1325
    def adjust_path(self, name, parent, trans_id):
1326
        previous_parent = self._new_parent.get(trans_id)
1327
        previous_name = self._new_name.get(trans_id)
1328
        TreeTransformBase.adjust_path(self, name, parent, trans_id)
7143.15.2 by Jelmer Vernooij
Run autopep8.
1329
        if (trans_id in self._limbo_files
1330
                and trans_id not in self._needs_rename):
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1331
            self._rename_in_limbo([trans_id])
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
1332
            if previous_parent != parent:
1333
                self._limbo_children[previous_parent].remove(trans_id)
1334
            if previous_parent != parent or previous_name != name:
1335
                del self._limbo_children_names[previous_parent][previous_name]
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1336
4634.78.3 by Aaron Bentley
Remove spurious change.
1337
    def _rename_in_limbo(self, trans_ids):
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1338
        """Fix limbo names so that the right final path is produced.
1339
1340
        This means we outsmarted ourselves-- we tried to avoid renaming
1341
        these files later by creating them with their final names in their
1342
        final parents.  But now the previous name or parent is no longer
1343
        suitable, so we have to rename them.
1344
1345
        Even for trans_ids that have no new contents, we must remove their
1346
        entries from _limbo_files, because they are now stale.
1347
        """
1348
        for trans_id in trans_ids:
5876.4.4 by Andrew Bennetts
Fix edge cases in handling interrupts during _rename_in_limbo, with messy tests
1349
            old_path = self._limbo_files[trans_id]
1350
            self._possibly_stale_limbo_files.add(old_path)
1351
            del self._limbo_files[trans_id]
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1352
            if trans_id not in self._new_contents:
1353
                continue
1354
            new_path = self._limbo_name(trans_id)
5050.15.1 by Martin
Revert change of rename function in transform from r5192 to fix failures on Windows
1355
            os.rename(old_path, new_path)
5876.4.4 by Andrew Bennetts
Fix edge cases in handling interrupts during _rename_in_limbo, with messy tests
1356
            self._possibly_stale_limbo_files.remove(old_path)
4634.78.1 by Aaron Bentley
adjust_path updatest limbo paths.
1357
            for descendant in self._limbo_descendants(trans_id):
1358
                desc_path = self._limbo_files[descendant]
1359
                desc_path = new_path + desc_path[len(old_path):]
1360
                self._limbo_files[descendant] = desc_path
1361
1362
    def _limbo_descendants(self, trans_id):
1363
        """Return the set of trans_ids whose limbo paths descend from this."""
1364
        descendants = set(self._limbo_children.get(trans_id, []))
1365
        for descendant in list(descendants):
1366
            descendants.update(self._limbo_descendants(descendant))
1367
        return descendants
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1368
7490.83.1 by Jelmer Vernooij
Add abstract methods.
1369
    def _set_mode(self, trans_id, mode_id, typefunc):
1370
        raise NotImplementedError(self._set_mode)
1371
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
1372
    def create_file(self, contents, trans_id, mode_id=None, sha1=None):
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1373
        """Schedule creation of a new file.
1374
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
1375
        :seealso: new_file.
1376
1377
        :param contents: an iterator of strings, all of which will be written
1378
            to the target destination.
1379
        :param trans_id: TreeTransform handle
1380
        :param mode_id: If not None, force the mode of the target file to match
1381
            the mode of the object referenced by mode_id.
1382
            Otherwise, we will try to preserve mode bits of an existing file.
1383
        :param sha1: If the sha1 of this content is already known, pass it in.
1384
            We can use it to prevent future sha1 computations.
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1385
        """
1386
        name = self._limbo_name(trans_id)
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
1387
        with open(name, 'wb') as f:
5876.4.3 by Andrew Bennetts
Simplify create_file now that finalize will always take care of cleaning up its limbo file.
1388
            unique_add(self._new_contents, trans_id, 'file')
5752.2.3 by John Arbash Meinel
Change the create_file api to allow it to take a sha1 of the content.
1389
            f.writelines(contents)
4934.1.12 by John Arbash Meinel
Revert all of the extension code.
1390
        self._set_mtime(name)
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1391
        self._set_mode(trans_id, mode_id, S_ISREG)
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
1392
        # It is unfortunate we have to use lstat instead of fstat, but we just
1393
        # used utime and chmod on the file, so we need the accurate final
1394
        # details.
1395
        if sha1 is not None:
1396
            self._observed_sha1s[trans_id] = (sha1, osutils.lstat(name))
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1397
1398
    def _read_symlink_target(self, trans_id):
1399
        return os.readlink(self._limbo_name(trans_id))
1400
4934.1.12 by John Arbash Meinel
Revert all of the extension code.
1401
    def _set_mtime(self, path):
4934.1.2 by John Arbash Meinel
Move the functionality into osutils / extensions.
1402
        """All files that are created get the same mtime.
1403
1404
        This time is set by the first object to be created.
1405
        """
1406
        if self._creation_mtime is None:
1407
            self._creation_mtime = time.time()
4934.1.12 by John Arbash Meinel
Revert all of the extension code.
1408
        os.utime(path, (self._creation_mtime, self._creation_mtime))
4934.1.2 by John Arbash Meinel
Move the functionality into osutils / extensions.
1409
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1410
    def create_hardlink(self, path, trans_id):
1411
        """Schedule creation of a hard link"""
1412
        name = self._limbo_name(trans_id)
1413
        try:
1414
            os.link(path, name)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1415
        except OSError as e:
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1416
            if e.errno != errno.EPERM:
1417
                raise
1418
            raise errors.HardLinkNotSupported(path)
1419
        try:
1420
            unique_add(self._new_contents, trans_id, 'file')
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
1421
        except BaseException:
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1422
            # Clean up the file, it never got registered so
1423
            # TreeTransform.finalize() won't clean it up.
1424
            os.unlink(name)
1425
            raise
1426
1427
    def create_directory(self, trans_id):
1428
        """Schedule creation of a new directory.
1429
1430
        See also new_directory.
1431
        """
1432
        os.mkdir(self._limbo_name(trans_id))
1433
        unique_add(self._new_contents, trans_id, 'directory')
1434
1435
    def create_symlink(self, target, trans_id):
1436
        """Schedule creation of a new symbolic link.
1437
1438
        target is a bytestring.
1439
        See also new_symlink.
1440
        """
7122.6.5 by Jelmer Vernooij
More improvements, add tests.
1441
        if self._create_symlinks:
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1442
            os.symlink(target, self._limbo_name(trans_id))
1443
        else:
1444
            try:
1445
                path = FinalPaths(self).get_path(trans_id)
1446
            except KeyError:
1447
                path = None
7122.6.3 by Jelmer Vernooij
Merge trunk.
1448
            trace.warning(
7122.6.6 by Jelmer Vernooij
Fix more tests.
1449
                'Unable to create symlink "%s" on this filesystem.' % (path,))
6469.1.10 by Parth Malwankar
cosmetic. improved comment.
1450
        # We add symlink to _new_contents even if they are unsupported
1451
        # and not created. These entries are subsequently used to avoid
6469.1.1 by Parth Malwankar
initial support for checking out files with softlinks
1452
        # conflicts on platforms that don't support symlink
1453
        unique_add(self._new_contents, trans_id, 'symlink')
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1454
1455
    def cancel_creation(self, trans_id):
1456
        """Cancel the creation of new file contents."""
1457
        del self._new_contents[trans_id]
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
1458
        if trans_id in self._observed_sha1s:
1459
            del self._observed_sha1s[trans_id]
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1460
        children = self._limbo_children.get(trans_id)
1461
        # if this is a limbo directory with children, move them before removing
1462
        # the directory
1463
        if children is not None:
1464
            self._rename_in_limbo(children)
1465
            del self._limbo_children[trans_id]
1466
            del self._limbo_children_names[trans_id]
1467
        delete_any(self._limbo_name(trans_id))
1468
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
1469
    def new_orphan(self, trans_id, parent_id):
6449.6.5 by Jelmer Vernooij
Merge bzr.transform.orphan_policy move to config stacks.
1470
        conf = self._tree.get_config_stack()
6883.13.1 by Jelmer Vernooij
Rename bzr.transform.orphan_policy -> transform.orphan_policy.
1471
        handle_orphan = conf.get('transform.orphan_policy')
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
1472
        handle_orphan(self, trans_id, parent_id)
1473
1474
1475
class OrphaningError(errors.BzrError):
1476
1477
    # Only bugs could lead to such exception being seen by the user
1478
    internal_error = True
1479
    _fmt = "Error while orphaning %s in %s directory"
1480
1481
    def __init__(self, orphan, parent):
1482
        errors.BzrError.__init__(self)
1483
        self.orphan = orphan
1484
        self.parent = parent
1485
1486
1487
class OrphaningForbidden(OrphaningError):
1488
1489
    _fmt = "Policy: %s doesn't allow creating orphans."
1490
1491
    def __init__(self, policy):
1492
        errors.BzrError.__init__(self)
1493
        self.policy = policy
5409.1.14 by Vincent Ladeuil
Prepare for more ways to handle orphans.
1494
1495
1496
def move_orphan(tt, orphan_id, parent_id):
1497
    """See TreeTransformBase.new_orphan.
1498
6681.2.4 by Jelmer Vernooij
More renames.
1499
    This creates a new orphan in the `brz-orphans` dir at the root of the
5409.1.14 by Vincent Ladeuil
Prepare for more ways to handle orphans.
1500
    `TreeTransform`.
1501
1502
    :param tt: The TreeTransform orphaning `trans_id`.
1503
1504
    :param orphan_id: The trans id that should be orphaned.
1505
1506
    :param parent_id: The orphan parent trans id.
1507
    """
1508
    # Add the orphan dir if it doesn't exist
6681.2.4 by Jelmer Vernooij
More renames.
1509
    orphan_dir_basename = 'brz-orphans'
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
1510
    od_id = tt.trans_id_tree_path(orphan_dir_basename)
5409.1.14 by Vincent Ladeuil
Prepare for more ways to handle orphans.
1511
    if tt.final_kind(od_id) is None:
1512
        tt.create_directory(od_id)
1513
    parent_path = tt._tree_id_paths[parent_id]
1514
    # Find a name that doesn't exist yet in the orphan dir
1515
    actual_name = tt.final_name(orphan_id)
1516
    new_name = tt._available_backup_name(actual_name, od_id)
1517
    tt.adjust_path(new_name, od_id, orphan_id)
5753.2.3 by Jelmer Vernooij
Fix transform tests.
1518
    trace.warning('%s has been orphaned in %s'
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
1519
                  % (joinpath(parent_path, actual_name), orphan_dir_basename))
1520
1521
1522
def refuse_orphan(tt, orphan_id, parent_id):
1523
    """See TreeTransformBase.new_orphan.
1524
5409.1.23 by Vincent Ladeuil
Add more doc and fix rst typos
1525
    This refuses to create orphan, letting the caller handle the conflict.
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
1526
    """
1527
    raise OrphaningForbidden('never')
5409.1.14 by Vincent Ladeuil
Prepare for more ways to handle orphans.
1528
1529
1530
orphaning_registry = registry.Registry()
5409.1.25 by Vincent Ladeuil
Better docs.
1531
orphaning_registry.register(
6973.11.9 by Jelmer Vernooij
Fix tests.
1532
    u'conflict', refuse_orphan,
5409.1.25 by Vincent Ladeuil
Better docs.
1533
    'Leave orphans in place and create a conflict on the directory.')
1534
orphaning_registry.register(
6973.11.9 by Jelmer Vernooij
Fix tests.
1535
    u'move', move_orphan,
6681.2.4 by Jelmer Vernooij
More renames.
1536
    'Move orphans into the brz-orphans directory.')
6973.11.9 by Jelmer Vernooij
Fix tests.
1537
orphaning_registry._set_default_key(u'conflict')
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
1538
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1539
6449.6.5 by Jelmer Vernooij
Merge bzr.transform.orphan_policy move to config stacks.
1540
opt_transform_orphan = _mod_config.RegistryOption(
6883.13.1 by Jelmer Vernooij
Rename bzr.transform.orphan_policy -> transform.orphan_policy.
1541
    'transform.orphan_policy', orphaning_registry,
6449.6.5 by Jelmer Vernooij
Merge bzr.transform.orphan_policy move to config stacks.
1542
    help='Policy for orphaned files during transform operations.',
1543
    invalid='warning')
1544
1545
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1546
class TreeTransform(DiskTreeTransform):
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1547
    """Represent a tree transformation.
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1548
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1549
    This object is designed to support incremental generation of the transform,
1550
    in any order.
1551
1552
    However, it gives optimum performance when parent directories are created
1553
    before their contents.  The transform is then able to put child files
1554
    directly in their parent directory, avoiding later renames.
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1555
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1556
    It is easy to produce malformed transforms, but they are generally
1557
    harmless.  Attempting to apply a malformed transform will cause an
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1558
    exception to be raised before any modifications are made to the tree.
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1559
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1560
    Many kinds of malformed transforms can be corrected with the
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1561
    resolve_conflicts function.  The remaining ones indicate programming error,
1562
    such as trying to create a file with no path.
1563
1564
    Two sets of file creation methods are supplied.  Convenience methods are:
1565
     * new_file
1566
     * new_directory
1567
     * new_symlink
1568
1569
    These are composed of the low-level methods:
1570
     * create_path
1571
     * create_file or create_directory or create_symlink
1572
     * version_file
1573
     * set_executability
3008.1.13 by Michael Hudson
merge bzr.dev
1574
1575
    Transform/Transaction ids
1576
    -------------------------
1577
    trans_ids are temporary ids assigned to all files involved in a transform.
1578
    It's possible, even common, that not all files in the Tree have trans_ids.
1579
1580
    trans_ids are used because filenames and file_ids are not good enough
1581
    identifiers; filenames change, and not all files have file_ids.  File-ids
1582
    are also associated with trans-ids, so that moving a file moves its
1583
    file-id.
1584
1585
    trans_ids are only valid for the TreeTransform that generated them.
1586
1587
    Limbo
1588
    -----
1589
    Limbo is a temporary directory use to hold new versions of files.
1590
    Files are added to limbo by create_file, create_directory, create_symlink,
1591
    and their convenience variants (new_*).  Files may be removed from limbo
1592
    using cancel_creation.  Files are renamed from limbo into their final
1593
    location as part of TreeTransform.apply
1594
1595
    Limbo must be cleaned up, by either calling TreeTransform.apply or
1596
    calling TreeTransform.finalize.
1597
1598
    Files are placed into limbo inside their parent directories, where
1599
    possible.  This reduces subsequent renames, and makes operations involving
1600
    lots of files faster.  This optimization is only possible if the parent
1601
    directory is created *before* creating any of its children, so avoid
1602
    creating children before parents, where possible.
1603
1604
    Pending-deletion
1605
    ----------------
1606
    This temporary directory is used by _FileMover for storing files that are
1607
    about to be deleted.  In case of rollback, the files will be restored.
1608
    FileMover does not delete files until it is sure that a rollback will not
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1609
    happen.
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1610
    """
7143.15.2 by Jelmer Vernooij
Run autopep8.
1611
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
1612
    def __init__(self, tree, pb=None):
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1613
        """Note: a tree_write lock is taken on the tree.
1614
1615
        Use TreeTransform.finalize() to release the lock (can be omitted if
1616
        TreeTransform.apply() called).
1617
        """
1618
        tree.lock_tree_write()
1619
        try:
1620
            limbodir = urlutils.local_path_from_url(
3407.2.8 by Martin Pool
Deprecate LockableFiles.controlfilename
1621
                tree._transport.abspath('limbo'))
6015.51.1 by Martin Pool
Tolerate empty limbo and pending-deletion directories
1622
            osutils.ensure_empty_directory_exists(
1623
                limbodir,
1624
                errors.ExistingLimbo)
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
1625
            deletiondir = urlutils.local_path_from_url(
3407.2.8 by Martin Pool
Deprecate LockableFiles.controlfilename
1626
                tree._transport.abspath('pending-deletion'))
6015.51.1 by Martin Pool
Tolerate empty limbo and pending-deletion directories
1627
            osutils.ensure_empty_directory_exists(
1628
                deletiondir,
1629
                errors.ExistingPendingDeletion)
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
1630
        except BaseException:
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1631
            tree.unlock()
1632
            raise
3008.1.13 by Michael Hudson
merge bzr.dev
1633
4354.5.2 by Aaron Bentley
Move WorkingTree-specific code out of BaseTreeTransform
1634
        # Cache of realpath results, to speed up canonical_path
1635
        self._realpaths = {}
1636
        # Cache of relpath results, to speed up canonical_path
1637
        self._relpaths = {}
4354.5.1 by Aaron Bentley
Split out a DiskTreeTransform class that manages Limbo.
1638
        DiskTreeTransform.__init__(self, tree, limbodir, pb,
3008.1.15 by Aaron Bentley
Make case_sensitive an aspect of the transform, not the source tree
1639
                                   tree.case_sensitive)
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
1640
        self._deletiondir = deletiondir
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1641
4354.5.2 by Aaron Bentley
Move WorkingTree-specific code out of BaseTreeTransform
1642
    def canonical_path(self, path):
1643
        """Get the canonical tree-relative path"""
1644
        # don't follow final symlinks
1645
        abs = self._tree.abspath(path)
1646
        if abs in self._relpaths:
1647
            return self._relpaths[abs]
1648
        dirname, basename = os.path.split(abs)
1649
        if dirname not in self._realpaths:
1650
            self._realpaths[dirname] = os.path.realpath(dirname)
1651
        dirname = self._realpaths[dirname]
1652
        abs = pathjoin(dirname, basename)
1653
        if dirname in self._relpaths:
1654
            relpath = pathjoin(self._relpaths[dirname], basename)
1655
            relpath = relpath.rstrip('/\\')
1656
        else:
1657
            relpath = self._tree.relpath(abs)
1658
        self._relpaths[abs] = relpath
1659
        return relpath
1660
1661
    def tree_kind(self, trans_id):
1662
        """Determine the file kind in the working tree.
1663
4597.9.13 by Vincent Ladeuil
bzrlib.transform.TreeTransform.tree_kind and
1664
        :returns: The file kind or None if the file does not exist
4354.5.2 by Aaron Bentley
Move WorkingTree-specific code out of BaseTreeTransform
1665
        """
1666
        path = self._tree_id_paths.get(trans_id)
1667
        if path is None:
4597.9.13 by Vincent Ladeuil
bzrlib.transform.TreeTransform.tree_kind and
1668
            return None
4354.5.2 by Aaron Bentley
Move WorkingTree-specific code out of BaseTreeTransform
1669
        try:
1670
            return file_kind(self._tree.abspath(path))
4597.9.13 by Vincent Ladeuil
bzrlib.transform.TreeTransform.tree_kind and
1671
        except errors.NoSuchFile:
1672
            return None
4354.5.2 by Aaron Bentley
Move WorkingTree-specific code out of BaseTreeTransform
1673
1674
    def _set_mode(self, trans_id, mode_id, typefunc):
1675
        """Set the mode of new file contents.
1676
        The mode_id is the existing file to get the mode from (often the same
1677
        as trans_id).  The operation is only performed if there's a mode match
1678
        according to typefunc.
1679
        """
1680
        if mode_id is None:
1681
            mode_id = trans_id
1682
        try:
1683
            old_path = self._tree_id_paths[mode_id]
1684
        except KeyError:
1685
            return
1686
        try:
1687
            mode = os.stat(self._tree.abspath(old_path)).st_mode
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1688
        except OSError as e:
4354.5.2 by Aaron Bentley
Move WorkingTree-specific code out of BaseTreeTransform
1689
            if e.errno in (errno.ENOENT, errno.ENOTDIR):
1690
                # Either old_path doesn't exist, or the parent of the
1691
                # target is not a directory (but will be one eventually)
1692
                # Either way, we know it doesn't exist *right now*
1693
                # See also bug #248448
1694
                return
1695
            else:
1696
                raise
1697
        if typefunc(mode):
6015.50.1 by Martin Pool
Use a chmod wrapper to cope with eperm from chmod
1698
            osutils.chmod_if_possible(self._limbo_name(trans_id), mode)
4354.5.2 by Aaron Bentley
Move WorkingTree-specific code out of BaseTreeTransform
1699
1700
    def iter_tree_children(self, parent_id):
1701
        """Iterate through the entry's tree children, if any"""
1702
        try:
1703
            path = self._tree_id_paths[parent_id]
1704
        except KeyError:
1705
            return
1706
        try:
1707
            children = os.listdir(self._tree.abspath(path))
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1708
        except OSError as e:
7143.15.2 by Jelmer Vernooij
Run autopep8.
1709
            if not (osutils._is_error_enotdir(e) or
1710
                    e.errno in (errno.ENOENT, errno.ESRCH)):
4354.5.2 by Aaron Bentley
Move WorkingTree-specific code out of BaseTreeTransform
1711
                raise
1712
            return
1713
1714
        for child in children:
1715
            childpath = joinpath(path, child)
1716
            if self._tree.is_control_filename(childpath):
1717
                continue
1718
            yield self.trans_id_tree_path(childpath)
1719
4634.79.1 by Aaron Bentley
TransformPreview uses ascii-only filenames.
1720
    def _generate_limbo_path(self, trans_id):
1721
        """Generate a limbo path using the final path if possible.
1722
1723
        This optimizes the performance of applying the tree transform by
1724
        avoiding renames.  These renames can be avoided only when the parent
1725
        directory is already scheduled for creation.
1726
1727
        If the final path cannot be used, falls back to using the trans_id as
1728
        the relpath.
1729
        """
1730
        parent = self._new_parent.get(trans_id)
1731
        # if the parent directory is already in limbo (e.g. when building a
1732
        # tree), choose a limbo name inside the parent, to reduce further
1733
        # renames.
1734
        use_direct_path = False
1735
        if self._new_contents.get(parent) == 'directory':
1736
            filename = self._new_name.get(trans_id)
1737
            if filename is not None:
1738
                if parent not in self._limbo_children:
1739
                    self._limbo_children[parent] = set()
1740
                    self._limbo_children_names[parent] = {}
1741
                    use_direct_path = True
1742
                # the direct path can only be used if no other file has
1743
                # already taken this pathname, i.e. if the name is unused, or
1744
                # if it is already associated with this trans_id.
1745
                elif self._case_sensitive_target:
1746
                    if (self._limbo_children_names[parent].get(filename)
7143.15.2 by Jelmer Vernooij
Run autopep8.
1747
                            in (trans_id, None)):
4634.79.1 by Aaron Bentley
TransformPreview uses ascii-only filenames.
1748
                        use_direct_path = True
1749
                else:
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
1750
                    for l_filename, l_trans_id in viewitems(
1751
                            self._limbo_children_names[parent]):
4634.79.1 by Aaron Bentley
TransformPreview uses ascii-only filenames.
1752
                        if l_trans_id == trans_id:
1753
                            continue
1754
                        if l_filename.lower() == filename.lower():
1755
                            break
1756
                    else:
1757
                        use_direct_path = True
1758
1759
        if not use_direct_path:
1760
            return DiskTreeTransform._generate_limbo_path(self, trans_id)
1761
1762
        limbo_name = pathjoin(self._limbo_files[parent], filename)
1763
        self._limbo_children[parent].add(trans_id)
1764
        self._limbo_children_names[parent][filename] = trans_id
1765
        return limbo_name
1766
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
1767
    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
1768
        """Apply all changes to the inventory and filesystem.
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1769
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1770
        If filesystem or inventory conflicts are present, MalformedTransform
1771
        will be thrown.
1772
1773
        If apply succeeds, finalize is not necessary.
1774
1775
        :param no_conflicts: if True, the caller guarantees there are no
1776
            conflicts, so no check is made.
3453.2.11 by Aaron Bentley
Updates from review
1777
        :param precomputed_delta: An inventory delta to use instead of
1778
            calculating one.
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1779
        :param _mover: Supply an alternate FileMover, for testing
1780
        """
7490.77.2 by Jelmer Vernooij
Split out git and bzr-specific transforms.
1781
        raise NotImplementedError(self.apply)
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1782
1783
    def _apply_removals(self, mover):
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1784
        """Perform tree operations that remove directory/inventory names.
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1785
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1786
        That is, delete files that are to be deleted, and put any files that
1787
        need renaming into limbo.  This must be done in strict child-to-parent
1788
        order.
3453.2.11 by Aaron Bentley
Updates from review
1789
1790
        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
1791
        """
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
1792
        tree_paths = sorted(viewitems(self._tree_path_ids), reverse=True)
6861.4.1 by Jelmer Vernooij
Make progress bars context managers.
1793
        with ui.ui_factory.nested_progress_bar() as child_pb:
5954.4.1 by Aaron Bentley
Never attempt to delete the tree root.
1794
            for num, (path, trans_id) in enumerate(tree_paths):
1795
                # do not attempt to move root into a subdirectory of itself.
1796
                if path == '':
1797
                    continue
6138.4.1 by Jonathan Riddell
add gettext to progress bar strings
1798
                child_pb.update(gettext('removing file'), num, len(tree_paths))
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1799
                full_path = self._tree.abspath(path)
1800
                if trans_id in self._removed_contents:
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
1801
                    delete_path = os.path.join(self._deletiondir, trans_id)
1802
                    mover.pre_delete(full_path, delete_path)
7143.15.2 by Jelmer Vernooij
Run autopep8.
1803
                elif (trans_id in self._new_name or
1804
                      trans_id in self._new_parent):
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1805
                    try:
1806
                        mover.rename(full_path, self._limbo_name(trans_id))
7490.77.4 by Jelmer Vernooij
Move some errors around.
1807
                    except TransformRenameFailed as e:
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1808
                        if e.errno != errno.ENOENT:
1809
                            raise
1810
                    else:
1811
                        self.rename_count += 1
1812
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1813
    def _apply_insertions(self, mover):
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1814
        """Perform tree operations that insert directory/inventory names.
3008.1.19 by Aaron Bentley
Remove trailing whitespace
1815
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1816
        That is, create any files that need to be created, and restore from
1817
        limbo any files that needed renaming.  This must be done in strict
1818
        parent-to-child order.
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
1819
1820
        If inventory_delta is None, no inventory delta is calculated, and
1821
        no list of modified paths is returned.
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1822
        """
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1823
        new_paths = self.new_paths(filesystem_only=True)
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1824
        modified_paths = []
6861.4.1 by Jelmer Vernooij
Make progress bars context managers.
1825
        with ui.ui_factory.nested_progress_bar() as child_pb:
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1826
            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
1827
                if (num % 10) == 0:
7143.15.2 by Jelmer Vernooij
Run autopep8.
1828
                    child_pb.update(gettext('adding file'),
1829
                                    num, len(new_paths))
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
1830
                full_path = self._tree.abspath(path)
1831
                if trans_id in self._needs_rename:
1832
                    try:
1833
                        mover.rename(self._limbo_name(trans_id), full_path)
7490.77.4 by Jelmer Vernooij
Move some errors around.
1834
                    except TransformRenameFailed as e:
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
1835
                        # We may be renaming a dangling inventory id
1836
                        if e.errno != errno.ENOENT:
1837
                            raise
1838
                    else:
1839
                        self.rename_count += 1
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
1840
                    # TODO: if trans_id in self._observed_sha1s, we should
1841
                    #       re-stat the final target, since ctime will be
1842
                    #       updated by the change.
7143.15.2 by Jelmer Vernooij
Run autopep8.
1843
                if (trans_id in self._new_contents
1844
                        or self.path_changed(trans_id)):
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1845
                    if trans_id in self._new_contents:
1846
                        modified_paths.append(full_path)
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1847
                if trans_id in self._new_executability:
3619.2.8 by Aaron Bentley
Reorganize execute-bit handling
1848
                    self._set_executability(path, trans_id)
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
1849
                if trans_id in self._observed_sha1s:
1850
                    o_sha1, o_st_val = self._observed_sha1s[trans_id]
1851
                    st = osutils.lstat(full_path)
1852
                    self._observed_sha1s[trans_id] = (o_sha1, st)
5946.1.2 by John Arbash Meinel
Can't just delete trans_id in new_paths because some don't come from limbo.
1853
        for path, trans_id in new_paths:
1854
            # new_paths includes stuff like workingtree conflicts. Only the
1855
            # stuff in new_contents actually comes from limbo.
1856
            if trans_id in self._limbo_files:
1857
                del self._limbo_files[trans_id]
3619.2.1 by Aaron Bentley
Refactor inventory delta generation out of apply_insersions/removals
1858
        self._new_contents.clear()
3008.1.7 by Michael Hudson
move apply and helpers to TreeTransform from TreeTransformBase
1859
        return modified_paths
1860
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
1861
    def _apply_observed_sha1s(self):
1862
        """After we have finished renaming everything, update observed sha1s
1863
1864
        This has to be done after self._tree.apply_inventory_delta, otherwise
1865
        it doesn't know anything about the files we are updating. Also, we want
1866
        to do this as late as possible, so that most entries end up cached.
1867
        """
1868
        # TODO: this doesn't update the stat information for directories. So
1869
        #       the first 'bzr status' will still need to rewrite
1870
        #       .bzr/checkout/dirstate. However, we at least don't need to
1871
        #       re-read all of the files.
1872
        # TODO: If the operation took a while, we could do a time.sleep(3) here
1873
        #       to allow the clock to tick over and ensure we won't have any
1874
        #       problems. (we could observe start time, and finish time, and if
1875
        #       it is less than eg 10% overhead, add a sleep call.)
1876
        paths = FinalPaths(self)
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
1877
        for trans_id, observed in viewitems(self._observed_sha1s):
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
1878
            path = paths.get_path(trans_id)
7141.7.1 by Jelmer Vernooij
Get rid of file_ids in most of Tree.
1879
            self._tree._observed_sha1(path, observed)
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
1880
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
1881
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
1882
def joinpath(parent, child):
1534.7.40 by Aaron Bentley
Updated docs
1883
    """Join tree-relative paths, handling the tree root specially"""
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
1884
    if parent is None or parent == "":
1885
        return child
1886
    else:
1534.7.166 by Aaron Bentley
Swapped os.path.join for pathjoin everywhere
1887
        return pathjoin(parent, child)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1888
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
1889
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1890
class FinalPaths(object):
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
1891
    """Make path calculation cheap by memoizing paths.
1534.7.21 by Aaron Bentley
Updated docstrings
1892
1893
    The underlying tree must not be manipulated between calls, or else
1894
    the results will likely be incorrect.
1895
    """
7143.15.2 by Jelmer Vernooij
Run autopep8.
1896
1534.7.132 by Aaron Bentley
Got cooked conflicts working
1897
    def __init__(self, transform):
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1898
        object.__init__(self)
1899
        self._known_paths = {}
1534.7.33 by Aaron Bentley
Fixed naming
1900
        self.transform = transform
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1901
1902
    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.
1903
        if (trans_id == self.transform.root or trans_id == ROOT_PARENT):
6996 by Jelmer Vernooij
Merge lp:~jelmer/brz/python3-e
1904
            return u""
1534.7.33 by Aaron Bentley
Fixed naming
1905
        name = self.transform.final_name(trans_id)
1906
        parent_id = self.transform.final_parent(trans_id)
1534.7.132 by Aaron Bentley
Got cooked conflicts working
1907
        if parent_id == self.transform.root:
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1908
            return name
1909
        else:
1534.7.166 by Aaron Bentley
Swapped os.path.join for pathjoin everywhere
1910
            return pathjoin(self.get_path(parent_id), name)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1911
1912
    def get_path(self, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
1913
        """Find the final path associated with a trans_id"""
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1914
        if trans_id not in self._known_paths:
1915
            self._known_paths[trans_id] = self._determine_path(trans_id)
1916
        return self._known_paths[trans_id]
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
1917
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
1918
    def get_paths(self, trans_ids):
1919
        return [(self.get_path(t), t) for t in trans_ids]
1920
1921
1922
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
1923
               delta_from_tree=False):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1924
    """Create working tree for a branch, using a TreeTransform.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1925
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1926
    This function should be used on empty trees, having a tree root at most.
1927
    (see merge and revert functionality for working with existing trees)
1928
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1929
    Existing files are handled like so:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1930
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1931
    - Existing bzrdirs take precedence over creating new items.  They are
1932
      created as '%s.diverted' % name.
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1933
    - Otherwise, if the content on disk matches the content we are building,
1934
      it is silently replaced.
1935
    - Otherwise, conflict resolution will move the old file to 'oldname.moved'.
3123.5.17 by Aaron Bentley
Update docs
1936
1937
    :param tree: The tree to convert wt into a copy of
1938
    :param wt: The working tree that files will be placed into
1939
    :param accelerator_tree: A tree which can be used for retrieving file
1940
        contents more quickly than tree itself, i.e. a workingtree.  tree
1941
        will be used for cases where accelerator_tree's content is different.
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
1942
    :param hardlink: If true, hard-link files to accelerator_tree, where
3136.1.4 by Aaron Bentley
Avoid id2abspath calls
1943
        possible.  accelerator_tree must implement abspath, i.e. be a
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
1944
        working tree.
3453.2.6 by Aaron Bentley
Rename mutate_tree to delta_from_tree, add comment
1945
    :param delta_from_tree: If true, build_tree may use the input Tree to
1946
        generate the inventory delta.
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1947
    """
7356.1.2 by Jelmer Vernooij
Use ExitStack in more places.
1948
    with cleanup.ExitStack() as exit_stack:
1949
        exit_stack.enter_context(wt.lock_tree_write())
1950
        exit_stack.enter_context(tree.lock_read())
6754.8.4 by Jelmer Vernooij
Use new context stuff.
1951
        if accelerator_tree is not None:
7356.1.2 by Jelmer Vernooij
Use ExitStack in more places.
1952
            exit_stack.enter_context(accelerator_tree.lock_read())
1953
        return _build_tree(tree, wt, accelerator_tree, hardlink,
1954
                           delta_from_tree)
2255.7.49 by Robert Collins
Lock trees passed in to build_tree.
1955
3006.2.2 by Alexander Belchenko
tests added.
1956
3453.2.6 by Aaron Bentley
Rename mutate_tree to delta_from_tree, add comment
1957
def _build_tree(tree, wt, accelerator_tree, hardlink, delta_from_tree):
2255.7.49 by Robert Collins
Lock trees passed in to build_tree.
1958
    """See build_tree."""
6825.5.1 by Jelmer Vernooij
Implement Tree.all_versioned_paths.
1959
    for num, _unused in enumerate(wt.all_versioned_paths()):
3146.8.16 by Aaron Bentley
Updates from review
1960
        if num > 0:  # more than just a root
1961
            raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
1962
    file_trans_id = {}
5582.10.4 by Jelmer Vernooij
Fix a bunch of tests.
1963
    top_pb = ui.ui_factory.nested_progress_bar()
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
1964
    pp = ProgressPhase("Build phase", 2, top_pb)
7358.14.1 by Jelmer Vernooij
Remove Tree.get_root_id() in favour of Tree.path2id('').
1965
    if tree.path2id('') is not None:
2502.1.6 by Aaron Bentley
Update from review comments
1966
        # This is kind of a hack: we should be altering the root
1967
        # as part of the regular tree shape diff logic.
1968
        # 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.
1969
        # expensive operation (flush) every time the root id
1970
        # is set within the tree, nor setting the root and thus
1971
        # marking the tree as dirty, because we use two different
1972
        # idioms here: tree interfaces and inventory interfaces.
7358.14.1 by Jelmer Vernooij
Remove Tree.get_root_id() in favour of Tree.path2id('').
1973
        if wt.path2id('') != tree.path2id(''):
1974
            wt.set_root_id(tree.path2id(''))
2255.2.194 by Robert Collins
[BROKEN] Many updates to stop using experimental formats in tests.
1975
            wt.flush()
7490.77.2 by Jelmer Vernooij
Split out git and bzr-specific transforms.
1976
    tt = wt.transform()
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1977
    divert = set()
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
1978
    try:
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
1979
        pp.next_phase()
7358.14.1 by Jelmer Vernooij
Remove Tree.get_root_id() in favour of Tree.path2id('').
1980
        file_trans_id[wt.path2id('')] = tt.trans_id_tree_path('')
6861.4.1 by Jelmer Vernooij
Make progress bars context managers.
1981
        with ui.ui_factory.nested_progress_bar() as pb:
2708.1.2 by Aaron Bentley
Use extract_files_bytes for build_tree
1982
            deferred_contents = []
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
1983
            num = 0
6825.5.1 by Jelmer Vernooij
Implement Tree.all_versioned_paths.
1984
            total = len(tree.all_versioned_paths())
3453.2.6 by Aaron Bentley
Rename mutate_tree to delta_from_tree, add comment
1985
            if delta_from_tree:
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
1986
                precomputed_delta = []
1987
            else:
1988
                precomputed_delta = None
5268.2.7 by Parth Malwankar
fixed comment
1989
            # Check if tree inventory has content. If so, we populate
5268.2.3 by Parth Malwankar
keep the tree_entries list lazy to ensure progress bar works
1990
            # existing_files with the directory content. If there are no
1991
            # entries we skip populating existing_files as its not used.
1992
            # This improves performance and unncessary work on large
1993
            # directory trees. (#501307)
5268.2.5 by Parth Malwankar
simplified conditional file list creating using existing count.
1994
            if total > 0:
5268.2.1 by Parth Malwankar
init no longer iterates files in dir.
1995
                existing_files = set()
1996
                for dir, files in wt.walkdirs():
1997
                    existing_files.update(f[0] for f in files)
5268.2.5 by Parth Malwankar
simplified conditional file list creating using existing count.
1998
            for num, (tree_path, entry) in \
7143.15.2 by Jelmer Vernooij
Run autopep8.
1999
                    enumerate(tree.iter_entries_by_dir()):
2000
                pb.update(gettext("Building tree"), num
2001
                          - len(deferred_contents), total)
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
2002
                if entry.parent_id is None:
2003
                    continue
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2004
                reparent = False
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2005
                file_id = entry.file_id
3453.2.6 by Aaron Bentley
Rename mutate_tree to delta_from_tree, add comment
2006
                if delta_from_tree:
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
2007
                    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
2008
                if tree_path in existing_files:
2009
                    target_path = wt.abspath(tree_path)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2010
                    kind = file_kind(target_path)
2011
                    if kind == "directory":
2012
                        try:
6207.3.3 by jelmer at samba
Fix tests and the like.
2013
                            controldir.ControlDir.open(target_path)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2014
                        except errors.NotBranchError:
2015
                            pass
2016
                        else:
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2017
                            divert.add(file_id)
7143.15.2 by Jelmer Vernooij
Run autopep8.
2018
                    if (file_id not in divert
7143.16.10 by Jelmer Vernooij
Fix E128.
2019
                        and _content_match(
7350.6.6 by Jelmer Vernooij
Drop unused file_id argument.
2020
                            tree, entry, tree_path, kind, target_path)):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2021
                        tt.delete_contents(tt.trans_id_tree_path(tree_path))
2022
                        if kind == 'directory':
2023
                            reparent = True
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
2024
                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
2025
                if entry.kind == 'file':
2708.1.2 by Aaron Bentley
Use extract_files_bytes for build_tree
2026
                    # We *almost* replicate new_by_entry, so that we can defer
2027
                    # getting the file text, and get them all at once.
2028
                    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
2029
                    file_trans_id[file_id] = trans_id
7490.77.8 by Jelmer Vernooij
Change argument order for Transform.version_file.
2030
                    tt.version_file(trans_id, file_id=file_id)
7141.7.1 by Jelmer Vernooij
Get rid of file_ids in most of Tree.
2031
                    executable = tree.is_executable(tree_path)
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
2032
                    if executable:
2708.1.8 by Aaron Bentley
rename extract_files_bytest to iter_files_bytes, fix build_tree / progress
2033
                        tt.set_executability(executable, trans_id)
7490.77.1 by Jelmer Vernooij
Remove use of file_id when we don't need it.
2034
                    trans_data = (trans_id, tree_path, entry.text_sha1)
6874.2.1 by Jelmer Vernooij
Make Tree.iter_files_bytes() take paths rather than file_ids.
2035
                    deferred_contents.append((tree_path, trans_data))
2708.1.2 by Aaron Bentley
Use extract_files_bytes for build_tree
2036
                else:
6809.4.4 by Jelmer Vernooij
Swap arguments for Tree.is_executable.
2037
                    file_trans_id[file_id] = new_by_entry(
7143.15.2 by Jelmer Vernooij
Run autopep8.
2038
                        tree_path, tt, entry, parent_id, tree)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2039
                if reparent:
2040
                    new_trans_id = file_trans_id[file_id]
2041
                    old_parent = tt.trans_id_tree_path(tree_path)
2042
                    _reparent_children(tt, old_parent, new_trans_id)
3136.1.11 by Aaron Bentley
Updates from review
2043
            offset = num + 1 - len(deferred_contents)
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2044
            _create_files(tt, tree, deferred_contents, pb, offset,
2045
                          accelerator_tree, hardlink)
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
2046
        pp.next_phase()
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2047
        divert_trans = set(file_trans_id[f] for f in divert)
7143.15.2 by Jelmer Vernooij
Run autopep8.
2048
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2049
        def resolver(t, c):
2050
            return resolve_checkout(t, c, divert_trans)
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2051
        raw_conflicts = resolve_conflicts(tt, pass_func=resolver)
3453.2.4 by Aaron Bentley
Disable fast-path when conflicts are encountered
2052
        if len(raw_conflicts) > 0:
2053
            precomputed_delta = None
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2054
        conflicts = cook_conflicts(raw_conflicts, tt)
2055
        for conflict in conflicts:
6973.6.2 by Jelmer Vernooij
Fix more tests.
2056
            trace.warning(text_type(conflict))
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2057
        try:
2058
            wt.add_conflicts(conflicts)
2059
        except errors.UnsupportedOperation:
2060
            pass
3453.2.3 by Aaron Bentley
Enable using a precomputed inventory delta for build_tree.
2061
        result = tt.apply(no_conflicts=True,
2062
                          precomputed_delta=precomputed_delta)
1534.7.47 by Aaron Bentley
Started work on 'revert'
2063
    finally:
2064
        tt.finalize()
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
2065
        top_pb.finished()
2502.1.5 by Aaron Bentley
Cleanup
2066
    return result
1534.7.47 by Aaron Bentley
Started work on 'revert'
2067
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2068
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2069
def _create_files(tt, tree, desired_files, pb, offset, accelerator_tree,
2070
                  hardlink):
2071
    total = len(desired_files) + offset
4208.4.1 by Ian Clatworthy
eol conversion support
2072
    wt = tt._tree
3123.5.5 by Aaron Bentley
Split out _iter_files_bytes_accelerated
2073
    if accelerator_tree is None:
2074
        new_desired_files = desired_files
2075
    else:
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2076
        iter = accelerator_tree.iter_changes(tree, include_unchanged=True)
7322.1.6 by Jelmer Vernooij
Use the new attributes on TreeChange.
2077
        unchanged = [
2078
            change.path for change in iter
2079
            if not (change.changed_content or change.executable[0] != change.executable[1])]
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.
2080
        if accelerator_tree.supports_content_filtering():
6874.2.1 by Jelmer Vernooij
Make Tree.iter_files_bytes() take paths rather than file_ids.
2081
            unchanged = [(tp, ap) for (tp, ap) in unchanged
2082
                         if not next(accelerator_tree.iter_search_rules([ap]))]
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.
2083
        unchanged = dict(unchanged)
3123.5.5 by Aaron Bentley
Split out _iter_files_bytes_accelerated
2084
        new_desired_files = []
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2085
        count = 0
7490.77.1 by Jelmer Vernooij
Remove use of file_id when we don't need it.
2086
        for unused_tree_path, (trans_id, tree_path, text_sha1) in desired_files:
6874.2.1 by Jelmer Vernooij
Make Tree.iter_files_bytes() take paths rather than file_ids.
2087
            accelerator_path = unchanged.get(tree_path)
3123.5.12 by Aaron Bentley
Try to optimize iter_changes_accelerated
2088
            if accelerator_path is None:
6874.2.1 by Jelmer Vernooij
Make Tree.iter_files_bytes() take paths rather than file_ids.
2089
                new_desired_files.append((tree_path,
7490.77.1 by Jelmer Vernooij
Remove use of file_id when we don't need it.
2090
                                          (trans_id, tree_path, text_sha1)))
3123.5.12 by Aaron Bentley
Try to optimize iter_changes_accelerated
2091
                continue
6138.4.1 by Jonathan Riddell
add gettext to progress bar strings
2092
            pb.update(gettext('Adding file contents'), count + offset, total)
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2093
            if hardlink:
3136.1.4 by Aaron Bentley
Avoid id2abspath calls
2094
                tt.create_hardlink(accelerator_tree.abspath(accelerator_path),
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2095
                                   trans_id)
2096
            else:
7192.5.2 by Jelmer Vernooij
Fixes.
2097
                with accelerator_tree.get_file(accelerator_path) as f:
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
2098
                    chunks = osutils.file_iterator(f)
2099
                    if wt.supports_content_filtering():
2100
                        filters = wt._content_filter_stack(tree_path)
2101
                        chunks = filtered_output_bytes(chunks, filters,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2102
                                                       ContentFilterContext(tree_path, tree))
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
2103
                    tt.create_file(chunks, trans_id, sha1=text_sha1)
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2104
            count += 1
2105
        offset += count
7490.77.1 by Jelmer Vernooij
Remove use of file_id when we don't need it.
2106
    for count, ((trans_id, tree_path, text_sha1), contents) in enumerate(
3368.2.20 by Ian Clatworthy
move filtering up the layers in TreeTransform
2107
            tree.iter_files_bytes(new_desired_files)):
4208.4.1 by Ian Clatworthy
eol conversion support
2108
        if wt.supports_content_filtering():
2109
            filters = wt._content_filter_stack(tree_path)
3368.2.45 by Ian Clatworthy
add and use supports_content_filtering API
2110
            contents = filtered_output_bytes(contents, filters,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2111
                                             ContentFilterContext(tree_path, tree))
5752.5.1 by John Arbash Meinel
Merge up transform-create-file
2112
        tt.create_file(contents, trans_id, sha1=text_sha1)
6138.4.1 by Jonathan Riddell
add gettext to progress bar strings
2113
        pb.update(gettext('Adding file contents'), count + offset, total)
3123.5.5 by Aaron Bentley
Split out _iter_files_bytes_accelerated
2114
2115
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2116
def _reparent_children(tt, old_parent, new_parent):
2117
    for child in tt.iter_tree_children(old_parent):
2118
        tt.adjust_path(tt.final_name(child), new_parent, child)
2119
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
2120
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
2121
def _reparent_transform_children(tt, old_parent, new_parent):
2122
    by_parent = tt.by_parent()
2123
    for child in by_parent[old_parent]:
2124
        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)
2125
    return by_parent[old_parent]
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2126
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
2127
7350.6.6 by Jelmer Vernooij
Drop unused file_id argument.
2128
def _content_match(tree, entry, tree_path, kind, target_path):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2129
    if entry.kind != kind:
2130
        return False
2131
    if entry.kind == "directory":
2132
        return True
2133
    if entry.kind == "file":
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
2134
        with open(target_path, 'rb') as f1, \
7143.16.21 by Jelmer Vernooij
Fix regressions.
2135
                tree.get_file(tree_path) as f2:
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
2136
            if osutils.compare_files(f1, f2):
4708.2.2 by Martin
Workingtree changes sitting around since November, more explict closing of files in bzrlib
2137
                return True
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2138
    elif entry.kind == "symlink":
7141.7.1 by Jelmer Vernooij
Get rid of file_ids in most of Tree.
2139
        if tree.get_symlink_target(tree_path) == os.readlink(target_path):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2140
            return True
2141
    return False
2142
2143
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2144
def resolve_checkout(tt, conflicts, divert):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2145
    new_conflicts = set()
2146
    for c_type, conflict in ((c[0], c) for c in conflicts):
2147
        # Anything but a 'duplicate' would indicate programmer error
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2148
        if c_type != 'duplicate':
2149
            raise AssertionError(c_type)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2150
        # 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
2151
        if tt.new_contents(conflict[1]):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2152
            new_file = conflict[1]
2153
            old_file = conflict[2]
2154
        else:
2155
            new_file = conflict[2]
2156
            old_file = conflict[1]
2157
2158
        # We should only get here if the conflict wasn't completely
2159
        # resolved
2160
        final_parent = tt.final_parent(old_file)
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2161
        if new_file in divert:
7143.15.2 by Jelmer Vernooij
Run autopep8.
2162
            new_name = tt.final_name(old_file) + '.diverted'
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2163
            tt.adjust_path(new_name, final_parent, new_file)
2164
            new_conflicts.add((c_type, 'Diverted to',
2165
                               new_file, old_file))
2166
        else:
7143.15.2 by Jelmer Vernooij
Run autopep8.
2167
            new_name = tt.final_name(old_file) + '.moved'
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2168
            tt.adjust_path(new_name, final_parent, old_file)
2169
            new_conflicts.add((c_type, 'Moved existing file to',
2170
                               old_file, new_file))
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2171
    return new_conflicts
2172
2173
6809.4.4 by Jelmer Vernooij
Swap arguments for Tree.is_executable.
2174
def new_by_entry(path, tt, entry, parent_id, tree):
1534.7.157 by Aaron Bentley
Added more docs
2175
    """Create a new file according to its inventory entry"""
1534.7.47 by Aaron Bentley
Started work on 'revert'
2176
    name = entry.name
2177
    kind = entry.kind
2178
    if kind == 'file':
7141.7.1 by Jelmer Vernooij
Get rid of file_ids in most of Tree.
2179
        with tree.get_file(path) as f:
2180
            executable = tree.is_executable(path)
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
2181
            return tt.new_file(
7143.15.2 by Jelmer Vernooij
Run autopep8.
2182
                name, parent_id, osutils.file_iterator(f), entry.file_id,
2183
                executable)
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
2184
    elif kind in ('directory', 'tree-reference'):
2185
        trans_id = tt.new_directory(name, parent_id, entry.file_id)
2186
        if kind == 'tree-reference':
2187
            tt.set_tree_reference(entry.reference_revision, trans_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2188
        return trans_id
1534.7.47 by Aaron Bentley
Started work on 'revert'
2189
    elif kind == 'symlink':
7141.7.1 by Jelmer Vernooij
Get rid of file_ids in most of Tree.
2190
        target = tree.get_symlink_target(path)
1534.7.183 by Aaron Bentley
Fixed build_tree with symlinks
2191
        return tt.new_symlink(name, parent_id, target, entry.file_id)
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
2192
    else:
2193
        raise errors.BadFileKindError(name, kind)
1534.7.47 by Aaron Bentley
Started work on 'revert'
2194
3006.2.2 by Alexander Belchenko
tests added.
2195
7350.5.1 by Jelmer Vernooij
Remove file_id from transform's create_from_tree, get filter tree paths by path.
2196
def create_from_tree(tt, trans_id, tree, path, chunks=None,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2197
                     filter_tree_path=None):
4443.2.1 by Ian Clatworthy
apply content filters when merging new files
2198
    """Create new file contents according to tree contents.
6809.4.7 by Jelmer Vernooij
Swap arguments for get_symlink_target and kind/stored_kind.
2199
4443.2.1 by Ian Clatworthy
apply content filters when merging new files
2200
    :param filter_tree_path: the tree path to use to lookup
2201
      content filters to apply to the bytes output in the working tree.
2202
      This only applies if the working tree supports content filtering.
2203
    """
7141.7.1 by Jelmer Vernooij
Get rid of file_ids in most of Tree.
2204
    kind = tree.kind(path)
3363.17.24 by Aaron Bentley
Implement create_by_tree
2205
    if kind == 'directory':
2206
        tt.create_directory(trans_id)
2207
    elif kind == "file":
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
2208
        if chunks is None:
7141.7.1 by Jelmer Vernooij
Get rid of file_ids in most of Tree.
2209
            f = tree.get_file(path)
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
2210
            chunks = osutils.file_iterator(f)
2211
        else:
2212
            f = None
2213
        try:
2214
            wt = tt._tree
2215
            if wt.supports_content_filtering() and filter_tree_path is not None:
2216
                filters = wt._content_filter_stack(filter_tree_path)
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2217
                chunks = filtered_output_bytes(
2218
                    chunks, filters,
2219
                    ContentFilterContext(filter_tree_path, tree))
6977.2.1 by Jelmer Vernooij
Require that get_file implementations are contect managers, simplify file handling in transform.
2220
            tt.create_file(chunks, trans_id)
2221
        finally:
2222
            if f is not None:
2223
                f.close()
3363.17.24 by Aaron Bentley
Implement create_by_tree
2224
    elif kind == "symlink":
7141.7.1 by Jelmer Vernooij
Get rid of file_ids in most of Tree.
2225
        tt.create_symlink(tree.get_symlink_target(path), trans_id)
3363.17.27 by Aaron Bentley
Add default case for create_from_tree
2226
    else:
2227
        raise AssertionError('Unknown kind %r' % kind)
3363.17.24 by Aaron Bentley
Implement create_by_tree
2228
2229
1534.7.89 by Aaron Bentley
Handle all content types in three-way
2230
def create_entry_executability(tt, entry, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
2231
    """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
2232
    if entry.kind == "file":
2233
        tt.set_executability(entry.executable, trans_id)
1534.7.47 by Aaron Bentley
Started work on 'revert'
2234
1534.7.157 by Aaron Bentley
Added more docs
2235
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2236
def revert(working_tree, target_tree, filenames, backups=False,
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
2237
           pb=None, change_reporter=None):
1534.7.157 by Aaron Bentley
Added more docs
2238
    """Revert a working tree's contents to those of a target tree."""
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
2239
    pb = ui.ui_factory.nested_progress_bar()
1534.7.47 by Aaron Bentley
Started work on 'revert'
2240
    try:
7490.77.2 by Jelmer Vernooij
Split out git and bzr-specific transforms.
2241
        with target_tree.lock_read(), working_tree.transform(pb) as tt:
6969.3.2 by Jelmer Vernooij
Use context managers for locking.
2242
            pp = ProgressPhase("Revert phase", 3, pb)
2243
            conflicts, merge_modified = _prepare_revert_transform(
2244
                working_tree, target_tree, tt, filenames, backups, pp)
2245
            if change_reporter:
7490.83.1 by Jelmer Vernooij
Add abstract methods.
2246
                from . import delta
6969.3.2 by Jelmer Vernooij
Use context managers for locking.
2247
                change_reporter = delta._ChangeReporter(
2248
                    unversioned_filter=working_tree.is_ignored)
2249
                delta.report_changes(tt.iter_changes(), change_reporter)
2250
            for conflict in conflicts:
6973.6.2 by Jelmer Vernooij
Fix more tests.
2251
                trace.warning(text_type(conflict))
6969.3.2 by Jelmer Vernooij
Use context managers for locking.
2252
            pp.next_phase()
2253
            tt.apply()
2254
            if working_tree.supports_merge_modified():
2255
                working_tree.set_merge_modified(merge_modified)
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
2256
    finally:
1534.9.4 by Aaron Bentley
Added progress bars to revert.
2257
        pb.clear()
1558.7.13 by Aaron Bentley
WorkingTree.revert returns conflicts
2258
    return conflicts
1534.7.51 by Aaron Bentley
New approach to revert
2259
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
2260
3363.2.10 by Aaron Bentley
Refactor _prepare_revert_transform out of revert
2261
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
3363.2.17 by Aaron Bentley
Start implementing post-change PreviewTree functionality
2262
                              backups, pp, basis_tree=None,
2263
                              merge_modified=None):
6861.4.1 by Jelmer Vernooij
Make progress bars context managers.
2264
    with ui.ui_factory.nested_progress_bar() as child_pb:
3363.2.17 by Aaron Bentley
Start implementing post-change PreviewTree functionality
2265
        if merge_modified is None:
2266
            merge_modified = working_tree.merge_modified()
3363.2.10 by Aaron Bentley
Refactor _prepare_revert_transform out of revert
2267
        merge_modified = _alter_files(working_tree, target_tree, tt,
3363.2.17 by Aaron Bentley
Start implementing post-change PreviewTree functionality
2268
                                      child_pb, filenames, backups,
2269
                                      merge_modified, basis_tree)
6861.4.1 by Jelmer Vernooij
Make progress bars context managers.
2270
    with ui.ui_factory.nested_progress_bar() as child_pb:
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2271
        raw_conflicts = resolve_conflicts(
2272
            tt, child_pb, lambda t, c: conflict_pass(t, c, target_tree))
3363.2.10 by Aaron Bentley
Refactor _prepare_revert_transform out of revert
2273
    conflicts = cook_conflicts(raw_conflicts, tt)
2274
    return conflicts, merge_modified
2275
2276
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
2277
def _alter_files(working_tree, target_tree, tt, pb, specific_files,
3363.2.17 by Aaron Bentley
Start implementing post-change PreviewTree functionality
2278
                 backups, merge_modified, basis_tree=None):
3363.10.25 by Aaron Bentley
_alter_files locks supplied basis_tree
2279
    if basis_tree is not None:
2280
        basis_tree.lock_read()
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2281
    # We ask the working_tree for its changes relative to the target, rather
2282
    # than the target changes relative to the working tree. Because WT4 has an
2283
    # optimizer to compare itself to a target, but no optimizer for the
2284
    # reverse.
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2285
    change_list = working_tree.iter_changes(
2286
        target_tree, specific_files=specific_files, pb=pb)
6973.3.1 by Jelmer Vernooij
Avoid using file ids where possible.
2287
    if not target_tree.is_versioned(u''):
2012.1.12 by Aaron Bentley
Use iter_changes for revert
2288
        skip_root = True
2289
    else:
2290
        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.
2291
    try:
2708.1.5 by Aaron Bentley
Use Tree.extract_files_bytes in revert
2292
        deferred_files = []
7322.1.7 by Jelmer Vernooij
Fix remaining tests.
2293
        for id_num, change in enumerate(change_list):
2294
            file_id = change.file_id
2295
            target_path, wt_path = change.path
2296
            target_versioned, wt_versioned = change.versioned
2297
            target_parent, wt_parent = change.parent_id
2298
            target_name, wt_name = change.name
2299
            target_kind, wt_kind = change.kind
2300
            target_executable, wt_executable = change.executable
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2301
            if skip_root and wt_parent is None:
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2302
                continue
2303
            trans_id = tt.trans_id_file_id(file_id)
2304
            mode_id = None
7322.1.7 by Jelmer Vernooij
Fix remaining tests.
2305
            if change.changed_content:
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2306
                keep_content = False
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2307
                if wt_kind == 'file' and (backups or target_kind is None):
7141.7.1 by Jelmer Vernooij
Get rid of file_ids in most of Tree.
2308
                    wt_sha1 = working_tree.get_file_sha1(wt_path)
7350.4.1 by Jelmer Vernooij
Use paths as keys in merge modified dictionaries.
2309
                    if merge_modified.get(wt_path) != wt_sha1:
2502.1.6 by Aaron Bentley
Update from review comments
2310
                        # acquire the basis tree lazily to prevent the
2311
                        # expense of accessing it when it's not needed ?
2312
                        # (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.
2313
                        if basis_tree is None:
2314
                            basis_tree = working_tree.basis_tree()
2315
                            basis_tree.lock_read()
7357.1.8 by Jelmer Vernooij
Remove the InterTree object.
2316
                        basis_inter = InterTree.get(basis_tree, working_tree)
2317
                        basis_path = basis_inter.find_source_path(wt_path)
6883.5.3 by Jelmer Vernooij
Add find_previous_path.
2318
                        if basis_path is None:
6809.4.13 by Jelmer Vernooij
Fix tests.
2319
                            if target_kind is None and not target_versioned:
2320
                                keep_content = True
2321
                        else:
7141.7.1 by Jelmer Vernooij
Get rid of file_ids in most of Tree.
2322
                            if wt_sha1 != basis_tree.get_file_sha1(basis_path):
6809.4.13 by Jelmer Vernooij
Fix tests.
2323
                                keep_content = True
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2324
                if wt_kind is not None:
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2325
                    if not keep_content:
2326
                        tt.delete_contents(trans_id)
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2327
                    elif target_kind is not None:
2328
                        parent_trans_id = tt.trans_id_file_id(wt_parent)
5409.8.4 by Vincent Ladeuil
Fix indentations.
2329
                        backup_name = tt._available_backup_name(
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2330
                            wt_name, parent_trans_id)
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2331
                        tt.adjust_path(backup_name, parent_trans_id, trans_id)
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2332
                        new_trans_id = tt.create_path(wt_name, parent_trans_id)
5783.3.2 by John Arbash Meinel
catch a couple more cases
2333
                        if wt_versioned and target_versioned:
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2334
                            tt.unversion_file(trans_id)
7490.77.8 by Jelmer Vernooij
Change argument order for Transform.version_file.
2335
                            tt.version_file(new_trans_id, file_id=file_id)
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2336
                        # New contents should have the same unix perms as old
2337
                        # contents
2338
                        mode_id = trans_id
2339
                        trans_id = new_trans_id
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2340
                if target_kind in ('directory', 'tree-reference'):
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2341
                    tt.create_directory(trans_id)
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2342
                    if target_kind == 'tree-reference':
6809.4.1 by Jelmer Vernooij
Swap file_id and path arguments for get_reference_revision and get_nested_tree.
2343
                        revision = target_tree.get_reference_revision(
7143.15.15 by Jelmer Vernooij
Merge trunk.
2344
                            target_path)
3363.11.3 by Aaron Bentley
Handle adding tree references in revert
2345
                        tt.set_tree_reference(revision, trans_id)
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2346
                elif target_kind == 'symlink':
6809.4.13 by Jelmer Vernooij
Fix tests.
2347
                    tt.create_symlink(target_tree.get_symlink_target(
7143.15.15 by Jelmer Vernooij
Merge trunk.
2348
                        target_path), trans_id)
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2349
                elif target_kind == 'file':
7143.15.2 by Jelmer Vernooij
Run autopep8.
2350
                    deferred_files.append(
2351
                        (target_path, (trans_id, mode_id, file_id)))
2499.1.1 by Aaron Bentley
Revert does not try to preserve file contents produced by revert
2352
                    if basis_tree is None:
2353
                        basis_tree = working_tree.basis_tree()
2354
                        basis_tree.lock_read()
7141.7.1 by Jelmer Vernooij
Get rid of file_ids in most of Tree.
2355
                    new_sha1 = target_tree.get_file_sha1(target_path)
7357.1.8 by Jelmer Vernooij
Remove the InterTree object.
2356
                    basis_inter = InterTree.get(basis_tree, target_tree)
2357
                    basis_path = basis_inter.find_source_path(target_path)
6809.4.5 by Jelmer Vernooij
Swap arguments for get_file_*.
2358
                    if (basis_path is not None and
7143.15.15 by Jelmer Vernooij
Merge trunk.
2359
                            new_sha1 == basis_tree.get_file_sha1(basis_path)):
7350.4.3 by Jelmer Vernooij
Fix tests.
2360
                        # If the new contents of the file match what is in basis,
2361
                        # then there is no need to store in merge_modified.
2362
                        if basis_path in merge_modified:
2363
                            del merge_modified[basis_path]
2499.1.1 by Aaron Bentley
Revert does not try to preserve file contents produced by revert
2364
                    else:
7350.4.3 by Jelmer Vernooij
Fix tests.
2365
                        merge_modified[target_path] = new_sha1
2499.1.1 by Aaron Bentley
Revert does not try to preserve file contents produced by revert
2366
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2367
                    # preserve the execute bit when backing up
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2368
                    if keep_content and wt_executable == target_executable:
2369
                        tt.set_executability(target_executable, trans_id)
2370
                elif target_kind is not None:
2371
                    raise AssertionError(target_kind)
5783.3.2 by John Arbash Meinel
catch a couple more cases
2372
            if not wt_versioned and target_versioned:
7490.77.8 by Jelmer Vernooij
Change argument order for Transform.version_file.
2373
                tt.version_file(trans_id, file_id=file_id)
5783.3.2 by John Arbash Meinel
catch a couple more cases
2374
            if wt_versioned and not target_versioned:
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2375
                tt.unversion_file(trans_id)
7143.15.2 by Jelmer Vernooij
Run autopep8.
2376
            if (target_name is not None
2377
                    and (wt_name != target_name or wt_parent != target_parent)):
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2378
                if target_name == '' and target_parent is None:
3363.2.16 by Aaron Bentley
Fix root directory creation
2379
                    parent_trans = ROOT_PARENT
2380
                else:
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2381
                    parent_trans = tt.trans_id_file_id(target_parent)
2382
                if wt_parent is None and wt_versioned:
2383
                    tt.adjust_root_path(target_name, parent_trans)
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
2384
                else:
5783.3.1 by John Arbash Meinel
Do an 'obvious' transformation for clarity.
2385
                    tt.adjust_path(target_name, parent_trans, trans_id)
2386
            if wt_executable != target_executable and target_kind == "file":
2387
                tt.set_executability(target_executable, trans_id)
4443.2.7 by Ian Clatworthy
test and fix for revert with content filtering
2388
        if working_tree.supports_content_filtering():
6874.2.1 by Jelmer Vernooij
Make Tree.iter_files_bytes() take paths rather than file_ids.
2389
            for (trans_id, mode_id, file_id), bytes in (
7143.15.2 by Jelmer Vernooij
Run autopep8.
2390
                    target_tree.iter_files_bytes(deferred_files)):
4634.102.4 by Ian Clatworthy
Explain why we're using the target tree to look up the path when reverting
2391
                # We're reverting a tree to the target tree so using the
2392
                # target tree to find the file path seems the best choice
2393
                # here IMO - Ian C 27/Oct/2009
4443.2.7 by Ian Clatworthy
test and fix for revert with content filtering
2394
                filter_tree_path = target_tree.id2path(file_id)
2395
                filters = working_tree._content_filter_stack(filter_tree_path)
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2396
                bytes = filtered_output_bytes(
2397
                    bytes, filters,
2398
                    ContentFilterContext(filter_tree_path, working_tree))
4443.2.7 by Ian Clatworthy
test and fix for revert with content filtering
2399
                tt.create_file(bytes, trans_id, mode_id)
2400
        else:
6874.2.1 by Jelmer Vernooij
Make Tree.iter_files_bytes() take paths rather than file_ids.
2401
            for (trans_id, mode_id, file_id), bytes in target_tree.iter_files_bytes(
7143.15.2 by Jelmer Vernooij
Run autopep8.
2402
                    deferred_files):
4443.2.7 by Ian Clatworthy
test and fix for revert with content filtering
2403
                tt.create_file(bytes, trans_id, mode_id)
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
2404
        tt.fixup_new_roots()
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
2405
    finally:
2406
        if basis_tree is not None:
2407
            basis_tree.unlock()
2499.1.1 by Aaron Bentley
Revert does not try to preserve file contents produced by revert
2408
    return merge_modified
2012.1.12 by Aaron Bentley
Use iter_changes for revert
2409
2410
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
2411
def resolve_conflicts(tt, pb=None, pass_func=None):
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
2412
    """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
2413
    if pass_func is None:
2414
        pass_func = conflict_pass
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
2415
    new_conflicts = set()
6861.4.1 by Jelmer Vernooij
Make progress bars context managers.
2416
    with ui.ui_factory.nested_progress_bar() as pb:
1534.9.1 by Aaron Bentley
Added progress bars to merge
2417
        for n in range(10):
7143.15.2 by Jelmer Vernooij
Run autopep8.
2418
            pb.update(gettext('Resolution pass'), n + 1, 10)
1534.9.1 by Aaron Bentley
Added progress bars to merge
2419
            conflicts = tt.find_conflicts()
2420
            if len(conflicts) == 0:
2421
                return new_conflicts
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2422
            new_conflicts.update(pass_func(tt, conflicts))
1534.9.1 by Aaron Bentley
Added progress bars to merge
2423
        raise MalformedTransform(conflicts=conflicts)
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
2424
2425
2590.2.8 by Aaron Bentley
Restore conflict handling changes
2426
def conflict_pass(tt, conflicts, path_tree=None):
2427
    """Resolve some classes of conflicts.
2428
2429
    :param tt: The transform to resolve conflicts in
2430
    :param conflicts: The conflicts to resolve
2431
    :param path_tree: A Tree to get supplemental paths from
2432
    """
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
2433
    new_conflicts = set()
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
2434
    for c_type, conflict in ((c[0], c) for c in conflicts):
2435
        if c_type == 'duplicate id':
1534.7.51 by Aaron Bentley
New approach to revert
2436
            tt.unversion_file(conflict[1])
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2437
            new_conflicts.add((c_type, 'Unversioned existing file',
2438
                               conflict[1], conflict[2], ))
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
2439
        elif c_type == 'duplicate':
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
2440
            # files that were renamed take precedence
2441
            final_parent = tt.final_parent(conflict[1])
2442
            if tt.path_changed(conflict[1]):
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
2443
                existing_file, new_file = conflict[2], conflict[1]
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
2444
            else:
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
2445
                existing_file, new_file = conflict[1], conflict[2]
6015.47.2 by Vincent Ladeuil
Cosmetic change.
2446
            new_name = tt.final_name(existing_file) + '.moved'
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
2447
            tt.adjust_path(new_name, final_parent, existing_file)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2448
            new_conflicts.add((c_type, 'Moved existing file to',
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
2449
                               existing_file, new_file))
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
2450
        elif c_type == 'parent loop':
2451
            # break the loop by undoing one of the ops that caused the loop
2452
            cur = conflict[1]
2453
            while not tt.path_changed(cur):
2454
                cur = tt.final_parent(cur)
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2455
            new_conflicts.add((c_type, 'Cancelled move', cur,
2456
                               tt.final_parent(cur),))
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
2457
            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
2458
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
2459
        elif c_type == 'missing parent':
1534.7.128 by Aaron Bentley
Got missing contents test working
2460
            trans_id = conflict[1]
5409.1.3 by Vincent Ladeuil
Clarify b.transform.conflict_pass.
2461
            if trans_id in tt._removed_contents:
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
2462
                cancel_deletion = True
5409.1.14 by Vincent Ladeuil
Prepare for more ways to handle orphans.
2463
                orphans = tt._get_potential_orphans(trans_id)
2464
                if orphans:
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
2465
                    cancel_deletion = False
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
2466
                    # All children are orphans
2467
                    for o in orphans:
5409.1.14 by Vincent Ladeuil
Prepare for more ways to handle orphans.
2468
                        try:
2469
                            tt.new_orphan(o, trans_id)
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
2470
                        except OrphaningError:
2471
                            # Something bad happened so we cancel the directory
2472
                            # deletion which will leave it in place with a
2473
                            # conflict. The user can deal with it from there.
2474
                            # Note that this also catch the case where we don't
2475
                            # want to create orphans and leave the directory in
2476
                            # place.
2477
                            cancel_deletion = True
5409.1.14 by Vincent Ladeuil
Prepare for more ways to handle orphans.
2478
                            break
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
2479
                if cancel_deletion:
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
2480
                    # Cancel the directory deletion
2481
                    tt.cancel_deletion(trans_id)
2482
                    new_conflicts.add(('deleting parent', 'Not deleting',
2483
                                       trans_id))
5409.1.3 by Vincent Ladeuil
Clarify b.transform.conflict_pass.
2484
            else:
1551.19.32 by Aaron Bentley
Don't traceback when adding files to a deleted root (abentley, #210092)
2485
                create = True
2590.2.8 by Aaron Bentley
Restore conflict handling changes
2486
                try:
2487
                    tt.final_name(trans_id)
2488
                except NoFinalPath:
1551.19.6 by Aaron Bentley
Revert doesn't crash restoring a file from a deleted directory
2489
                    if path_tree is not None:
2490
                        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)
2491
                        if file_id is None:
2492
                            file_id = tt.inactive_file_id(trans_id)
6634.2.1 by Martin
Apply 2to3 next fixer and make compatible
2493
                        _, entry = next(path_tree.iter_entries_by_dir(
6885.5.7 by Jelmer Vernooij
Use specific_files rather than specific_file_ids in transform.
2494
                            specific_files=[path_tree.id2path(file_id)]))
1551.19.32 by Aaron Bentley
Don't traceback when adding files to a deleted root (abentley, #210092)
2495
                        # special-case the other tree root (move its
2496
                        # children to current root)
2497
                        if entry.parent_id is None:
5128.1.1 by Vincent Ladeuil
Uncontroversial cleanups, mostly comments
2498
                            create = False
1551.19.32 by Aaron Bentley
Don't traceback when adding files to a deleted root (abentley, #210092)
2499
                            moved = _reparent_transform_children(
2500
                                tt, trans_id, tt.root)
2501
                            for child in moved:
2502
                                new_conflicts.add((c_type, 'Moved to root',
2503
                                                   child))
2504
                        else:
2505
                            parent_trans_id = tt.trans_id_file_id(
2506
                                entry.parent_id)
2507
                            tt.adjust_path(entry.name, parent_trans_id,
2508
                                           trans_id)
2509
                if create:
2510
                    tt.create_directory(trans_id)
2511
                    new_conflicts.add((c_type, 'Created directory', trans_id))
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
2512
        elif c_type == 'unversioned parent':
1551.19.32 by Aaron Bentley
Don't traceback when adding files to a deleted root (abentley, #210092)
2513
            file_id = tt.inactive_file_id(conflict[1])
2514
            # special-case the other tree root (move its children instead)
6883.7.10 by Jelmer Vernooij
Avoid has_id.
2515
            if path_tree and path_tree.path2id('') == file_id:
7260.1.2 by Jelmer Vernooij
Fix flake8 issues.
2516
                # This is the root entry, skip it
7143.15.2 by Jelmer Vernooij
Run autopep8.
2517
                continue
7490.77.8 by Jelmer Vernooij
Change argument order for Transform.version_file.
2518
            tt.version_file(conflict[1], file_id=file_id)
1534.7.171 by Aaron Bentley
Implemented stringifying filesystem conflicts
2519
            new_conflicts.add((c_type, 'Versioned directory', conflict[1]))
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
2520
        elif c_type == 'non-directory parent':
2521
            parent_id = conflict[1]
2522
            parent_parent = tt.final_parent(parent_id)
2523
            parent_name = tt.final_name(parent_id)
2524
            parent_file_id = tt.final_file_id(parent_id)
2525
            new_parent_id = tt.new_directory(parent_name + '.new',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2526
                                             parent_parent, parent_file_id)
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
2527
            _reparent_transform_children(tt, parent_id, new_parent_id)
3146.8.19 by Aaron Bentley
Merge with bzr.dev
2528
            if parent_file_id is not None:
2529
                tt.unversion_file(parent_id)
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
2530
            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
2531
        elif c_type == 'versioning no contents':
2532
            tt.cancel_versioning(conflict[1])
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
2533
    return new_conflicts
2534
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
2535
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
2536
def cook_conflicts(raw_conflicts, tt):
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2537
    """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
2538
    conflict_iter = iter_cook_conflicts(raw_conflicts, tt)
5988.2.1 by Vincent Ladeuil
Do not generate path conflicts if a corresponding content conflict exists
2539
    return sorted(conflict_iter, key=conflicts.Conflict.sort_key)
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2540
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
2541
2542
def iter_cook_conflicts(raw_conflicts, tt):
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2543
    fp = FinalPaths(tt)
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
2544
    for conflict in raw_conflicts:
2545
        c_type = conflict[0]
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2546
        action = conflict[1]
2547
        modified_path = fp.get_path(conflict[2])
2548
        modified_id = tt.final_file_id(conflict[2])
2549
        if len(conflict) == 3:
5988.2.1 by Vincent Ladeuil
Do not generate path conflicts if a corresponding content conflict exists
2550
            yield conflicts.Conflict.factory(
2551
                c_type, action=action, path=modified_path, file_id=modified_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2552
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
2553
        else:
2554
            conflicting_path = fp.get_path(conflict[3])
2555
            conflicting_id = tt.final_file_id(conflict[3])
5988.2.1 by Vincent Ladeuil
Do not generate path conflicts if a corresponding content conflict exists
2556
            yield conflicts.Conflict.factory(
2557
                c_type, action=action, path=modified_path,
2558
                file_id=modified_id,
2559
                conflict_path=conflicting_path,
2560
                conflict_file_id=conflicting_id)
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2561
2562
2563
class _FileMover(object):
2733.2.9 by Aaron Bentley
Update docstrings
2564
    """Moves and deletes files for TreeTransform, tracking operations"""
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2565
2566
    def __init__(self):
2567
        self.past_renames = []
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2568
        self.pending_deletions = []
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2569
2570
    def rename(self, from_, to):
5186.2.2 by Martin Pool
wrap os.rename to insert the source and destination filenames in any exception that may be raised
2571
        """Rename a file from one path to another."""
3063.1.1 by Alexander Belchenko
Catch OSError 17 (file exists) in final phase of tree transform and show filename to user (#111758).
2572
        try:
5050.15.1 by Martin
Revert change of rename function in transform from r5192 to fix failures on Windows
2573
            os.rename(from_, to)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2574
        except OSError as e:
3063.1.3 by Aaron Bentley
Update for Linux
2575
            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).
2576
                raise errors.FileExists(to, str(e))
5186.2.5 by Martin Pool
Raise a specific clearer error when a rename fails inside transform
2577
            # normal OSError doesn't include filenames so it's hard to see where
2578
            # the problem is, see https://bugs.launchpad.net/bzr/+bug/491763
7490.77.4 by Jelmer Vernooij
Move some errors around.
2579
            raise TransformRenameFailed(from_, to, str(e), e.errno)
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2580
        self.past_renames.append((from_, to))
2581
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2582
    def pre_delete(self, from_, to):
2733.2.9 by Aaron Bentley
Update docstrings
2583
        """Rename a file out of the way and mark it for deletion.
2584
2585
        Unlike os.unlink, this works equally well for files and directories.
2586
        :param from_: The current file path
2587
        :param to: A temporary path for the file
2588
        """
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2589
        self.rename(from_, to)
2590
        self.pending_deletions.append(to)
2591
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2592
    def rollback(self):
2733.2.9 by Aaron Bentley
Update docstrings
2593
        """Reverse all renames that have been performed"""
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2594
        for from_, to in reversed(self.past_renames):
5186.2.7 by Martin Pool
Update other cases where transform detects failure to rename
2595
            try:
5050.15.1 by Martin
Revert change of rename function in transform from r5192 to fix failures on Windows
2596
                os.rename(to, from_)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2597
            except OSError as e:
7490.77.4 by Jelmer Vernooij
Move some errors around.
2598
                raise TransformRenameFailed(to, from_, str(e), e.errno)
2733.2.12 by Aaron Bentley
Updates from review
2599
        # after rollback, don't reuse _FileMover
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2600
        self.past_renames = None
2601
        self.pending_deletions = None
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2602
2603
    def apply_deletions(self):
2733.2.9 by Aaron Bentley
Update docstrings
2604
        """Apply all marked deletions"""
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2605
        for path in self.pending_deletions:
2606
            delete_any(path)
2733.2.12 by Aaron Bentley
Updates from review
2607
        # after apply_deletions, don't reuse _FileMover
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2608
        self.past_renames = None
2609
        self.pending_deletions = None
6652.1.1 by Jelmer Vernooij
Bundle the link-tree command.
2610
2611
2612
def link_tree(target_tree, source_tree):
2613
    """Where possible, hard-link files in a tree to those in another tree.
2614
2615
    :param target_tree: Tree to change
2616
    :param source_tree: Tree to hard-link from
2617
    """
7490.77.2 by Jelmer Vernooij
Split out git and bzr-specific transforms.
2618
    with target_tree.transform() as tt:
7322.1.6 by Jelmer Vernooij
Use the new attributes on TreeChange.
2619
        for change in target_tree.iter_changes(source_tree, include_unchanged=True):
2620
            if change.changed_content:
2621
                continue
2622
            if change.kind != ('file', 'file'):
2623
                continue
2624
            if change.executable[0] != change.executable[1]:
2625
                continue
2626
            trans_id = tt.trans_id_tree_path(change.path[1])
6652.1.1 by Jelmer Vernooij
Bundle the link-tree command.
2627
            tt.delete_contents(trans_id)
7322.1.6 by Jelmer Vernooij
Use the new attributes on TreeChange.
2628
            tt.create_hardlink(source_tree.abspath(change.path[0]), trans_id)
6652.1.1 by Jelmer Vernooij
Bundle the link-tree command.
2629
        tt.apply()