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