/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
1
# Copyright (C) 2006 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
17
import os
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
18
import errno
1534.7.117 by Aaron Bentley
Simplified permission handling of existing files in transform.
19
from stat import S_ISREG
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
20
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
21
from bzrlib import bzrdir, errors
1551.11.12 by Aaron Bentley
Changes from review
22
from bzrlib.lazy_import import lazy_import
23
lazy_import(globals(), """
24
from bzrlib import delta
25
""")
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
26
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
1534.7.162 by Aaron Bentley
Handle failures creating/deleting the Limbo directory
27
                           ReusingTransform, NotVersionedError, CantMoveRoot,
1731.1.33 by Aaron Bentley
Revert no-special-root changes
28
                           ExistingLimbo, ImmortalLimbo, NoFinalPath)
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
29
from bzrlib.inventory import InventoryEntry
1558.12.9 by Aaron Bentley
Handle resolving conflicts with directories properly
30
from bzrlib.osutils import (file_kind, supports_executable, pathjoin, lexists,
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
31
                            delete_any)
1551.2.34 by Aaron Bentley
Refactored the revert phases
32
from bzrlib.progress import DummyProgress, ProgressPhase
2255.7.48 by Robert Collins
Deprecated and make work with DirState trees 'transform.find_interesting'.
33
from bzrlib.symbol_versioning import deprecated_function, zero_fifteen
1534.7.173 by Aaron Bentley
Added conflict warnings to revert
34
from bzrlib.trace import mutter, warning
1551.7.14 by Aaron Bentley
Use specified_file_ids instead of is_inside_any in compare_trees
35
from bzrlib import tree
1551.2.31 by Aaron Bentley
Got merge and revert using nested pbs
36
import bzrlib.ui 
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
37
import bzrlib.urlutils as urlutils
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
38
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
39
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
40
ROOT_PARENT = "root-parent"
41
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
42
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
43
def unique_add(map, key, value):
44
    if key in map:
1534.7.5 by Aaron Bentley
Got unique_add under test
45
        raise DuplicateKey(key=key)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
46
    map[key] = value
47
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
48
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
49
class _TransformResults(object):
50
    def __init__(self, modified_paths):
51
        object.__init__(self)
52
        self.modified_paths = modified_paths
53
54
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
55
class TreeTransform(object):
1534.7.179 by Aaron Bentley
Added Transform docs
56
    """Represent a tree transformation.
57
    
58
    This object is designed to support incremental generation of the transform,
59
    in any order.  
60
    
61
    It is easy to produce malformed transforms, but they are generally
62
    harmless.  Attempting to apply a malformed transform will cause an
63
    exception to be raised before any modifications are made to the tree.  
64
65
    Many kinds of malformed transforms can be corrected with the 
66
    resolve_conflicts function.  The remaining ones indicate programming error,
67
    such as trying to create a file with no path.
68
69
    Two sets of file creation methods are supplied.  Convenience methods are:
70
     * new_file
71
     * new_directory
72
     * new_symlink
73
74
    These are composed of the low-level methods:
75
     * create_path
76
     * create_file or create_directory or create_symlink
77
     * version_file
78
     * set_executability
79
    """
1534.9.1 by Aaron Bentley
Added progress bars to merge
80
    def __init__(self, tree, pb=DummyProgress()):
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
81
        """Note: a tree_write lock is taken on the tree.
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
82
        
83
        Use TreeTransform.finalize() to release the lock
84
        """
85
        object.__init__(self)
86
        self._tree = tree
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
87
        self._tree.lock_tree_write()
1534.7.162 by Aaron Bentley
Handle failures creating/deleting the Limbo directory
88
        try:
89
            control_files = self._tree._control_files
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
90
            self._limbodir = urlutils.local_path_from_url(
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
91
                control_files.controlfilename('limbo'))
1534.7.162 by Aaron Bentley
Handle failures creating/deleting the Limbo directory
92
            try:
93
                os.mkdir(self._limbodir)
94
            except OSError, e:
95
                if e.errno == errno.EEXIST:
96
                    raise ExistingLimbo(self._limbodir)
97
        except: 
98
            self._tree.unlock()
99
            raise
100
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
101
        self._id_number = 0
102
        self._new_name = {}
103
        self._new_parent = {}
1534.7.4 by Aaron Bentley
Unified all file types as 'contents'
104
        self._new_contents = {}
1534.7.34 by Aaron Bentley
Proper conflicts for removals
105
        self._removed_contents = set()
1534.7.25 by Aaron Bentley
Added set_executability
106
        self._new_executability = {}
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
107
        self._new_id = {}
1534.7.143 by Aaron Bentley
Prevented get_trans_id from automatically versioning file ids
108
        self._non_present_ids = {}
1534.7.75 by Aaron Bentley
Added reverse-lookup for versioned files and get_trans_id
109
        self._r_new_id = {}
1534.7.39 by Aaron Bentley
Ensured that files can be unversioned (de-versioned?)
110
        self._removed_id = set()
1534.7.7 by Aaron Bentley
Added support for all-file path ids
111
        self._tree_path_ids = {}
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
112
        self._tree_id_paths = {}
1534.10.31 by Aaron Bentley
Add caching to speed canonical_path
113
        self._realpaths = {}
114
        # Cache of realpath results, to speed up canonical_path
115
        self._relpaths = {}
116
        # Cache of relpath results, to speed up canonical_path
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
117
        self._new_root = self.trans_id_tree_file_id(tree.get_root_id())
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
118
        self.__done = False
1534.9.1 by Aaron Bentley
Added progress bars to merge
119
        self._pb = pb
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
120
1534.7.132 by Aaron Bentley
Got cooked conflicts working
121
    def __get_root(self):
122
        return self._new_root
123
124
    root = property(__get_root)
125
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
126
    def finalize(self):
1534.7.157 by Aaron Bentley
Added more docs
127
        """Release the working tree lock, if held, clean up limbo dir."""
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
128
        if self._tree is None:
129
            return
1534.7.162 by Aaron Bentley
Handle failures creating/deleting the Limbo directory
130
        try:
131
            for trans_id, kind in self._new_contents.iteritems():
132
                path = self._limbo_name(trans_id)
133
                if kind == "directory":
134
                    os.rmdir(path)
135
                else:
136
                    os.unlink(path)
137
            try:
138
                os.rmdir(self._limbodir)
139
            except OSError:
140
                # We don't especially care *why* the dir is immortal.
141
                raise ImmortalLimbo(self._limbodir)
142
        finally:
143
            self._tree.unlock()
144
            self._tree = None
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
145
146
    def _assign_id(self):
147
        """Produce a new tranform id"""
148
        new_id = "new-%s" % self._id_number
149
        self._id_number +=1
150
        return new_id
151
152
    def create_path(self, name, parent):
153
        """Assign a transaction id to a new path"""
154
        trans_id = self._assign_id()
155
        unique_add(self._new_name, trans_id, name)
156
        unique_add(self._new_parent, trans_id, parent)
157
        return trans_id
158
1534.7.6 by Aaron Bentley
Added conflict handling
159
    def adjust_path(self, name, parent, trans_id):
1534.7.21 by Aaron Bentley
Updated docstrings
160
        """Change the path that is assigned to a transaction id."""
1534.7.66 by Aaron Bentley
Ensured we don't accidentally move the root directory
161
        if trans_id == self._new_root:
162
            raise CantMoveRoot
1534.7.6 by Aaron Bentley
Added conflict handling
163
        self._new_name[trans_id] = name
164
        self._new_parent[trans_id] = parent
165
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
166
    def adjust_root_path(self, name, parent):
167
        """Emulate moving the root by moving all children, instead.
168
        
169
        We do this by undoing the association of root's transaction id with the
170
        current tree.  This allows us to create a new directory with that
1534.7.69 by Aaron Bentley
Got real root moves working
171
        transaction id.  We unversion the root directory and version the 
172
        physically new directory, and hope someone versions the tree root
173
        later.
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
174
        """
175
        old_root = self._new_root
176
        old_root_file_id = self.final_file_id(old_root)
177
        # force moving all children of root
178
        for child_id in self.iter_tree_children(old_root):
179
            if child_id != parent:
180
                self.adjust_path(self.final_name(child_id), 
181
                                 self.final_parent(child_id), child_id)
1534.7.69 by Aaron Bentley
Got real root moves working
182
            file_id = self.final_file_id(child_id)
183
            if file_id is not None:
184
                self.unversion_file(child_id)
185
            self.version_file(file_id, child_id)
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
186
        
187
        # the physical root needs a new transaction id
188
        self._tree_path_ids.pop("")
189
        self._tree_id_paths.pop(old_root)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
190
        self._new_root = self.trans_id_tree_file_id(self._tree.get_root_id())
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
191
        if parent == old_root:
192
            parent = self._new_root
193
        self.adjust_path(name, parent, old_root)
194
        self.create_directory(old_root)
1534.7.69 by Aaron Bentley
Got real root moves working
195
        self.version_file(old_root_file_id, old_root)
196
        self.unversion_file(self._new_root)
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
197
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
198
    def trans_id_tree_file_id(self, inventory_id):
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
199
        """Determine the transaction id of a working tree file.
200
        
201
        This reflects only files that already exist, not ones that will be
202
        added by transactions.
203
        """
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
204
        path = self._tree.inventory.id2path(inventory_id)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
205
        return self.trans_id_tree_path(path)
1534.7.7 by Aaron Bentley
Added support for all-file path ids
206
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
207
    def trans_id_file_id(self, file_id):
1534.7.156 by Aaron Bentley
PEP8 fixes
208
        """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
209
        A new id is only created for file_ids that were never present.  If
210
        a transaction has been unversioned, it is deliberately still returned.
211
        (this will likely lead to an unversioned parent conflict.)
212
        """
213
        if file_id in self._r_new_id and self._r_new_id[file_id] is not None:
214
            return self._r_new_id[file_id]
215
        elif file_id in self._tree.inventory:
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
216
            return self.trans_id_tree_file_id(file_id)
1534.7.143 by Aaron Bentley
Prevented get_trans_id from automatically versioning file ids
217
        elif file_id in self._non_present_ids:
218
            return self._non_present_ids[file_id]
1534.7.75 by Aaron Bentley
Added reverse-lookup for versioned files and get_trans_id
219
        else:
220
            trans_id = self._assign_id()
1534.7.143 by Aaron Bentley
Prevented get_trans_id from automatically versioning file ids
221
            self._non_present_ids[file_id] = trans_id
1534.7.75 by Aaron Bentley
Added reverse-lookup for versioned files and get_trans_id
222
            return trans_id
223
1534.7.12 by Aaron Bentley
Added canonical_path function
224
    def canonical_path(self, path):
225
        """Get the canonical tree-relative path"""
226
        # don't follow final symlinks
1534.10.31 by Aaron Bentley
Add caching to speed canonical_path
227
        abs = self._tree.abspath(path)
228
        if abs in self._relpaths:
229
            return self._relpaths[abs]
230
        dirname, basename = os.path.split(abs)
231
        if dirname not in self._realpaths:
232
            self._realpaths[dirname] = os.path.realpath(dirname)
233
        dirname = self._realpaths[dirname]
234
        abs = pathjoin(dirname, basename)
235
        if dirname in self._relpaths:
236
            relpath = pathjoin(self._relpaths[dirname], basename)
1534.10.32 by Aaron Bentley
Test and fix case where name has trailing slash
237
            relpath = relpath.rstrip('/\\')
1534.10.31 by Aaron Bentley
Add caching to speed canonical_path
238
        else:
239
            relpath = self._tree.relpath(abs)
240
        self._relpaths[abs] = relpath
241
        return relpath
1534.7.12 by Aaron Bentley
Added canonical_path function
242
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
243
    def trans_id_tree_path(self, path):
1534.7.7 by Aaron Bentley
Added support for all-file path ids
244
        """Determine (and maybe set) the transaction ID for a tree path."""
1534.7.12 by Aaron Bentley
Added canonical_path function
245
        path = self.canonical_path(path)
1534.7.7 by Aaron Bentley
Added support for all-file path ids
246
        if path not in self._tree_path_ids:
247
            self._tree_path_ids[path] = self._assign_id()
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
248
            self._tree_id_paths[self._tree_path_ids[path]] = path
1534.7.7 by Aaron Bentley
Added support for all-file path ids
249
        return self._tree_path_ids[path]
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
250
1534.7.16 by Aaron Bentley
Added get_tree_parent
251
    def get_tree_parent(self, trans_id):
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
252
        """Determine id of the parent in the tree."""
1534.7.16 by Aaron Bentley
Added get_tree_parent
253
        path = self._tree_id_paths[trans_id]
254
        if path == "":
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
255
            return ROOT_PARENT
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
256
        return self.trans_id_tree_path(os.path.dirname(path))
1534.7.16 by Aaron Bentley
Added get_tree_parent
257
1534.7.117 by Aaron Bentley
Simplified permission handling of existing files in transform.
258
    def create_file(self, contents, trans_id, mode_id=None):
1534.7.21 by Aaron Bentley
Updated docstrings
259
        """Schedule creation of a new file.
260
261
        See also new_file.
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
262
        
263
        Contents is an iterator of strings, all of which will be written
1534.7.21 by Aaron Bentley
Updated docstrings
264
        to the target destination.
1534.7.117 by Aaron Bentley
Simplified permission handling of existing files in transform.
265
266
        New file takes the permissions of any existing file with that id,
267
        unless mode_id is specified.
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
268
        """
1711.7.22 by John Arbash Meinel
transform: cleanup the temporary file even if unique_add fails.
269
        name = self._limbo_name(trans_id)
270
        f = open(name, 'wb')
1711.7.8 by John Arbash Meinel
Use try/finally inside create_file for TreeTransform to ensure the file handle gets closed
271
        try:
1711.7.22 by John Arbash Meinel
transform: cleanup the temporary file even if unique_add fails.
272
            try:
273
                unique_add(self._new_contents, trans_id, 'file')
274
            except:
275
                # Clean up the file, it never got registered so
276
                # TreeTransform.finalize() won't clean it up.
277
                f.close()
278
                os.unlink(name)
279
                raise
280
2247.1.2 by John Arbash Meinel
Switch from for line in foo: f.write(line) to f.writelines(foo)
281
            f.writelines(contents)
1711.7.8 by John Arbash Meinel
Use try/finally inside create_file for TreeTransform to ensure the file handle gets closed
282
        finally:
283
            f.close()
1534.7.117 by Aaron Bentley
Simplified permission handling of existing files in transform.
284
        self._set_mode(trans_id, mode_id, S_ISREG)
285
286
    def _set_mode(self, trans_id, mode_id, typefunc):
1534.7.157 by Aaron Bentley
Added more docs
287
        """Set the mode of new file contents.
288
        The mode_id is the existing file to get the mode from (often the same
289
        as trans_id).  The operation is only performed if there's a mode match
290
        according to typefunc.
291
        """
1534.7.117 by Aaron Bentley
Simplified permission handling of existing files in transform.
292
        if mode_id is None:
293
            mode_id = trans_id
294
        try:
295
            old_path = self._tree_id_paths[mode_id]
296
        except KeyError:
297
            return
298
        try:
2027.1.1 by John Arbash Meinel
Fix bug #56549, and write a direct test that the right path is being statted
299
            mode = os.stat(self._tree.abspath(old_path)).st_mode
1534.7.117 by Aaron Bentley
Simplified permission handling of existing files in transform.
300
        except OSError, e:
301
            if e.errno == errno.ENOENT:
302
                return
303
            else:
304
                raise
305
        if typefunc(mode):
306
            os.chmod(self._limbo_name(trans_id), mode)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
307
1534.7.20 by Aaron Bentley
Added directory handling
308
    def create_directory(self, trans_id):
1534.7.21 by Aaron Bentley
Updated docstrings
309
        """Schedule creation of a new directory.
310
        
311
        See also new_directory.
312
        """
1534.7.73 by Aaron Bentley
Changed model again. Now iterator is used immediately.
313
        os.mkdir(self._limbo_name(trans_id))
314
        unique_add(self._new_contents, trans_id, 'directory')
1534.7.20 by Aaron Bentley
Added directory handling
315
1534.7.22 by Aaron Bentley
Added symlink support
316
    def create_symlink(self, target, trans_id):
317
        """Schedule creation of a new symbolic link.
318
319
        target is a bytestring.
320
        See also new_symlink.
321
        """
1534.7.73 by Aaron Bentley
Changed model again. Now iterator is used immediately.
322
        os.symlink(target, self._limbo_name(trans_id))
323
        unique_add(self._new_contents, trans_id, 'symlink')
1534.7.22 by Aaron Bentley
Added symlink support
324
1534.7.129 by Aaron Bentley
Converted test cases to Tree Transform
325
    def cancel_creation(self, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
326
        """Cancel the creation of new file contents."""
1534.7.129 by Aaron Bentley
Converted test cases to Tree Transform
327
        del self._new_contents[trans_id]
1558.12.9 by Aaron Bentley
Handle resolving conflicts with directories properly
328
        delete_any(self._limbo_name(trans_id))
1534.7.129 by Aaron Bentley
Converted test cases to Tree Transform
329
1534.7.34 by Aaron Bentley
Proper conflicts for removals
330
    def delete_contents(self, trans_id):
331
        """Schedule the contents of a path entry for deletion"""
1534.7.130 by Aaron Bentley
More conflict handling, test porting
332
        self.tree_kind(trans_id)
1534.7.34 by Aaron Bentley
Proper conflicts for removals
333
        self._removed_contents.add(trans_id)
334
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
335
    def cancel_deletion(self, trans_id):
336
        """Cancel a scheduled deletion"""
337
        self._removed_contents.remove(trans_id)
338
1534.7.39 by Aaron Bentley
Ensured that files can be unversioned (de-versioned?)
339
    def unversion_file(self, trans_id):
340
        """Schedule a path entry to become unversioned"""
341
        self._removed_id.add(trans_id)
342
343
    def delete_versioned(self, trans_id):
344
        """Delete and unversion a versioned file"""
345
        self.delete_contents(trans_id)
346
        self.unversion_file(trans_id)
347
1534.7.25 by Aaron Bentley
Added set_executability
348
    def set_executability(self, executability, trans_id):
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
349
        """Schedule setting of the 'execute' bit
350
        To unschedule, set to None
351
        """
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
352
        if executability is None:
353
            del self._new_executability[trans_id]
354
        else:
355
            unique_add(self._new_executability, trans_id, executability)
1534.7.25 by Aaron Bentley
Added set_executability
356
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
357
    def version_file(self, file_id, trans_id):
1534.7.21 by Aaron Bentley
Updated docstrings
358
        """Schedule a file to become versioned."""
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
359
        assert file_id is not None
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
360
        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
361
        unique_add(self._r_new_id, file_id, trans_id)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
362
1534.7.105 by Aaron Bentley
Got merge with rename working
363
    def cancel_versioning(self, trans_id):
364
        """Undo a previous versioning of a file"""
365
        file_id = self._new_id[trans_id]
366
        del self._new_id[trans_id]
367
        del self._r_new_id[file_id]
368
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
369
    def new_paths(self):
1534.7.21 by Aaron Bentley
Updated docstrings
370
        """Determine the paths of all new and changed files"""
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
371
        new_ids = set()
1534.7.132 by Aaron Bentley
Got cooked conflicts working
372
        fp = FinalPaths(self)
1534.7.4 by Aaron Bentley
Unified all file types as 'contents'
373
        for id_set in (self._new_name, self._new_parent, self._new_contents,
1534.7.25 by Aaron Bentley
Added set_executability
374
                       self._new_id, self._new_executability):
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
375
            new_ids.update(id_set)
376
        new_paths = [(fp.get_path(t), t) for t in new_ids]
377
        new_paths.sort()
378
        return new_paths
1534.7.6 by Aaron Bentley
Added conflict handling
379
1534.7.34 by Aaron Bentley
Proper conflicts for removals
380
    def tree_kind(self, trans_id):
1534.7.40 by Aaron Bentley
Updated docs
381
        """Determine the file kind in the working tree.
382
383
        Raises NoSuchFile if the file does not exist
384
        """
1534.7.34 by Aaron Bentley
Proper conflicts for removals
385
        path = self._tree_id_paths.get(trans_id)
386
        if path is None:
387
            raise NoSuchFile(None)
388
        try:
389
            return file_kind(self._tree.abspath(path))
390
        except OSError, e:
391
            if e.errno != errno.ENOENT:
392
                raise
393
            else:
394
                raise NoSuchFile(path)
395
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
396
    def final_kind(self, trans_id):
1534.7.156 by Aaron Bentley
PEP8 fixes
397
        """Determine the final file kind, after any changes applied.
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
398
        
399
        Raises NoSuchFile if the file does not exist/has no contents.
400
        (It is conceivable that a path would be created without the
401
        corresponding contents insertion command)
402
        """
403
        if trans_id in self._new_contents:
1534.7.73 by Aaron Bentley
Changed model again. Now iterator is used immediately.
404
            return self._new_contents[trans_id]
1534.7.34 by Aaron Bentley
Proper conflicts for removals
405
        elif trans_id in self._removed_contents:
406
            raise NoSuchFile(None)
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
407
        else:
1534.7.34 by Aaron Bentley
Proper conflicts for removals
408
            return self.tree_kind(trans_id)
1534.7.8 by Aaron Bentley
Added TreeTransform.final_kind
409
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
410
    def tree_file_id(self, trans_id):
1534.7.41 by Aaron Bentley
Got inventory ID movement working
411
        """Determine the file id associated with the trans_id in the tree"""
412
        try:
413
            path = self._tree_id_paths[trans_id]
414
        except KeyError:
415
            # the file is a new, unversioned file, or invalid trans_id
416
            return None
417
        # the file is old; the old id is still valid
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
418
        if self._new_root == trans_id:
419
            return self._tree.inventory.root.file_id
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
420
        return self._tree.inventory.path2id(path)
1534.7.41 by Aaron Bentley
Got inventory ID movement working
421
1534.7.13 by Aaron Bentley
Implemented final_file_id
422
    def final_file_id(self, trans_id):
1534.7.156 by Aaron Bentley
PEP8 fixes
423
        """Determine the file id after any changes are applied, or None.
1534.7.21 by Aaron Bentley
Updated docstrings
424
        
425
        None indicates that the file will not be versioned after changes are
426
        applied.
427
        """
1534.7.13 by Aaron Bentley
Implemented final_file_id
428
        try:
429
            # there is a new id for this file
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
430
            assert self._new_id[trans_id] is not None
1534.7.13 by Aaron Bentley
Implemented final_file_id
431
            return self._new_id[trans_id]
432
        except KeyError:
1534.7.39 by Aaron Bentley
Ensured that files can be unversioned (de-versioned?)
433
            if trans_id in self._removed_id:
434
                return None
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
435
        return self.tree_file_id(trans_id)
1534.7.13 by Aaron Bentley
Implemented final_file_id
436
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
437
    def inactive_file_id(self, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
438
        """Return the inactive file_id associated with a transaction id.
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
439
        That is, the one in the tree or in non_present_ids.
440
        The file_id may actually be active, too.
441
        """
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
442
        file_id = self.tree_file_id(trans_id)
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
443
        if file_id is not None:
444
            return file_id
445
        for key, value in self._non_present_ids.iteritems():
446
            if value == trans_id:
447
                return key
448
1534.7.17 by Aaron Bentley
Added final_parent function
449
    def final_parent(self, trans_id):
1534.7.156 by Aaron Bentley
PEP8 fixes
450
        """Determine the parent file_id, after any changes are applied.
1534.7.21 by Aaron Bentley
Updated docstrings
451
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
452
        ROOT_PARENT is returned for the tree root.
1534.7.21 by Aaron Bentley
Updated docstrings
453
        """
1534.7.17 by Aaron Bentley
Added final_parent function
454
        try:
455
            return self._new_parent[trans_id]
456
        except KeyError:
457
            return self.get_tree_parent(trans_id)
458
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
459
    def final_name(self, trans_id):
1534.7.40 by Aaron Bentley
Updated docs
460
        """Determine the final filename, after all changes are applied."""
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
461
        try:
462
            return self._new_name[trans_id]
463
        except KeyError:
1731.1.33 by Aaron Bentley
Revert no-special-root changes
464
            try:
465
                return os.path.basename(self._tree_id_paths[trans_id])
466
            except KeyError:
467
                raise NoFinalPath(trans_id, self)
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
468
1534.10.28 by Aaron Bentley
Use numbered backup files
469
    def by_parent(self):
1534.7.40 by Aaron Bentley
Updated docs
470
        """Return a map of parent: children for known parents.
471
        
472
        Only new paths and parents of tree files with assigned ids are used.
473
        """
1534.7.6 by Aaron Bentley
Added conflict handling
474
        by_parent = {}
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
475
        items = list(self._new_parent.iteritems())
1534.7.76 by Aaron Bentley
Fixed final_parent, for the case where finding a parent adds tree id paths.
476
        items.extend((t, self.final_parent(t)) for t in 
477
                      self._tree_id_paths.keys())
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
478
        for trans_id, parent_id in items:
1534.7.6 by Aaron Bentley
Added conflict handling
479
            if parent_id not in by_parent:
480
                by_parent[parent_id] = set()
481
            by_parent[parent_id].add(trans_id)
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
482
        return by_parent
1534.7.11 by Aaron Bentley
Refactored conflict handling
483
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
484
    def path_changed(self, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
485
        """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)
486
        return (trans_id in self._new_name) or (trans_id in self._new_parent)
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
487
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
488
    def new_contents(self, trans_id):
489
        return (trans_id in self._new_contents)
490
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
491
    def find_conflicts(self):
1534.7.40 by Aaron Bentley
Updated docs
492
        """Find any violations of inventory or filesystem invariants"""
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
493
        if self.__done is True:
494
            raise ReusingTransform()
495
        conflicts = []
496
        # ensure all children of all existent parents are known
497
        # all children of non-existent parents are known, by definition.
498
        self._add_tree_children()
1534.10.28 by Aaron Bentley
Use numbered backup files
499
        by_parent = self.by_parent()
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
500
        conflicts.extend(self._unversioned_parents(by_parent))
1534.7.19 by Aaron Bentley
Added tests for parent loops
501
        conflicts.extend(self._parent_loops())
1534.7.11 by Aaron Bentley
Refactored conflict handling
502
        conflicts.extend(self._duplicate_entries(by_parent))
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
503
        conflicts.extend(self._duplicate_ids())
1534.7.11 by Aaron Bentley
Refactored conflict handling
504
        conflicts.extend(self._parent_type_conflicts(by_parent))
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
505
        conflicts.extend(self._improper_versioning())
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
506
        conflicts.extend(self._executability_conflicts())
1534.7.152 by Aaron Bentley
Fixed overwrites
507
        conflicts.extend(self._overwrite_conflicts())
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
508
        return conflicts
509
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
510
    def _add_tree_children(self):
1534.7.156 by Aaron Bentley
PEP8 fixes
511
        """Add all the children of all active parents to the known paths.
1534.7.40 by Aaron Bentley
Updated docs
512
513
        Active parents are those which gain children, and those which are
514
        removed.  This is a necessary first step in detecting conflicts.
515
        """
1534.10.28 by Aaron Bentley
Use numbered backup files
516
        parents = self.by_parent().keys()
1534.7.34 by Aaron Bentley
Proper conflicts for removals
517
        parents.extend([t for t in self._removed_contents if 
518
                        self.tree_kind(t) == 'directory'])
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
519
        for trans_id in self._removed_id:
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
520
            file_id = self.tree_file_id(trans_id)
1731.1.2 by Aaron Bentley
Removed all remaining uses of root_directory
521
            if self._tree.inventory[file_id].kind == 'directory':
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
522
                parents.append(trans_id)
523
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
524
        for parent_id in parents:
1534.7.67 by Aaron Bentley
Refactored _add_tree_children
525
            # ensure that all children are registered with the transaction
526
            list(self.iter_tree_children(parent_id))
527
528
    def iter_tree_children(self, parent_id):
529
        """Iterate through the entry's tree children, if any"""
530
        try:
531
            path = self._tree_id_paths[parent_id]
532
        except KeyError:
533
            return
534
        try:
535
            children = os.listdir(self._tree.abspath(path))
536
        except OSError, e:
1534.7.71 by abentley
All tests pass under Windows
537
            if e.errno != errno.ENOENT and e.errno != errno.ESRCH:
1534.7.67 by Aaron Bentley
Refactored _add_tree_children
538
                raise
539
            return
540
            
541
        for child in children:
542
            childpath = joinpath(path, child)
1534.7.180 by Aaron Bentley
Merge from mainline
543
            if self._tree.is_control_filename(childpath):
1534.7.67 by Aaron Bentley
Refactored _add_tree_children
544
                continue
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
545
            yield self.trans_id_tree_path(childpath)
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
546
1534.10.28 by Aaron Bentley
Use numbered backup files
547
    def has_named_child(self, by_parent, parent_id, name):
548
        try:
549
            children = by_parent[parent_id]
550
        except KeyError:
551
            children = []
552
        for child in children:
553
            if self.final_name(child) == name:
554
                return True
555
        try:
556
            path = self._tree_id_paths[parent_id]
557
        except KeyError:
558
            return False
559
        childpath = joinpath(path, name)
560
        child_id = self._tree_path_ids.get(childpath)
561
        if child_id is None:
562
            return lexists(self._tree.abspath(childpath))
563
        else:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
564
            if self.final_parent(child_id) != parent_id:
1534.10.28 by Aaron Bentley
Use numbered backup files
565
                return False
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
566
            if child_id in self._removed_contents:
1534.10.28 by Aaron Bentley
Use numbered backup files
567
                # XXX What about dangling file-ids?
568
                return False
569
            else:
570
                return True
571
1534.7.19 by Aaron Bentley
Added tests for parent loops
572
    def _parent_loops(self):
573
        """No entry should be its own ancestor"""
574
        conflicts = []
575
        for trans_id in self._new_parent:
576
            seen = set()
577
            parent_id = trans_id
1534.7.31 by Aaron Bentley
Changed tree root parent to ROOT_PARENT
578
            while parent_id is not ROOT_PARENT:
1534.7.19 by Aaron Bentley
Added tests for parent loops
579
                seen.add(parent_id)
1731.1.33 by Aaron Bentley
Revert no-special-root changes
580
                try:
581
                    parent_id = self.final_parent(parent_id)
582
                except KeyError:
583
                    break
1534.7.19 by Aaron Bentley
Added tests for parent loops
584
                if parent_id == trans_id:
585
                    conflicts.append(('parent loop', trans_id))
586
                if parent_id in seen:
587
                    break
588
        return conflicts
589
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
590
    def _unversioned_parents(self, by_parent):
591
        """If parent directories are versioned, children must be versioned."""
592
        conflicts = []
593
        for parent_id, children in by_parent.iteritems():
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
594
            if parent_id is ROOT_PARENT:
595
                continue
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
596
            if self.final_file_id(parent_id) is not None:
597
                continue
598
            for child_id in children:
599
                if self.final_file_id(child_id) is not None:
600
                    conflicts.append(('unversioned parent', parent_id))
601
                    break;
602
        return conflicts
603
604
    def _improper_versioning(self):
1534.7.156 by Aaron Bentley
PEP8 fixes
605
        """Cannot version a file with no contents, or a bad type.
1534.7.15 by Aaron Bentley
Add conflict types related to versioning
606
        
607
        However, existing entries with no contents are okay.
608
        """
609
        conflicts = []
610
        for trans_id in self._new_id.iterkeys():
611
            try:
612
                kind = self.final_kind(trans_id)
613
            except NoSuchFile:
614
                conflicts.append(('versioning no contents', trans_id))
615
                continue
616
            if not InventoryEntry.versionable_kind(kind):
1534.7.20 by Aaron Bentley
Added directory handling
617
                conflicts.append(('versioning bad kind', trans_id, kind))
1534.7.11 by Aaron Bentley
Refactored conflict handling
618
        return conflicts
619
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
620
    def _executability_conflicts(self):
1534.7.40 by Aaron Bentley
Updated docs
621
        """Check for bad executability changes.
622
        
623
        Only versioned files may have their executability set, because
624
        1. only versioned entries can have executability under windows
625
        2. only files can be executable.  (The execute bit on a directory
626
           does not indicate searchability)
627
        """
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
628
        conflicts = []
629
        for trans_id in self._new_executability:
630
            if self.final_file_id(trans_id) is None:
631
                conflicts.append(('unversioned executability', trans_id))
1534.7.34 by Aaron Bentley
Proper conflicts for removals
632
            else:
633
                try:
634
                    non_file = self.final_kind(trans_id) != "file"
635
                except NoSuchFile:
636
                    non_file = True
637
                if non_file is True:
638
                    conflicts.append(('non-file executability', trans_id))
1534.7.26 by Aaron Bentley
Added conflicts for setting executability on unversioned/non-file entries
639
        return conflicts
640
1534.7.152 by Aaron Bentley
Fixed overwrites
641
    def _overwrite_conflicts(self):
642
        """Check for overwrites (not permitted on Win32)"""
643
        conflicts = []
644
        for trans_id in self._new_contents:
645
            try:
646
                self.tree_kind(trans_id)
647
            except NoSuchFile:
648
                continue
649
            if trans_id not in self._removed_contents:
650
                conflicts.append(('overwrite', trans_id,
651
                                 self.final_name(trans_id)))
652
        return conflicts
653
1534.7.11 by Aaron Bentley
Refactored conflict handling
654
    def _duplicate_entries(self, by_parent):
655
        """No directory may have two entries with the same name."""
656
        conflicts = []
1534.7.6 by Aaron Bentley
Added conflict handling
657
        for children in by_parent.itervalues():
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
658
            name_ids = [(self.final_name(t), t) for t in children]
1534.7.6 by Aaron Bentley
Added conflict handling
659
            name_ids.sort()
660
            last_name = None
661
            last_trans_id = None
662
            for name, trans_id in name_ids:
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
663
                try:
664
                    kind = self.final_kind(trans_id)
665
                except NoSuchFile:
666
                    kind = None
667
                file_id = self.final_file_id(trans_id)
668
                if kind is None and file_id is None:
669
                    continue
1534.7.6 by Aaron Bentley
Added conflict handling
670
                if name == last_name:
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
671
                    conflicts.append(('duplicate', last_trans_id, trans_id,
672
                    name))
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
673
                last_name = name
674
                last_trans_id = trans_id
1534.7.11 by Aaron Bentley
Refactored conflict handling
675
        return conflicts
676
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
677
    def _duplicate_ids(self):
678
        """Each inventory id may only be used once"""
679
        conflicts = []
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
680
        removed_tree_ids = set((self.tree_file_id(trans_id) for trans_id in
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
681
                                self._removed_id))
682
        active_tree_ids = set((f for f in self._tree.inventory if
683
                               f not in removed_tree_ids))
684
        for trans_id, file_id in self._new_id.iteritems():
685
            if file_id in active_tree_ids:
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
686
                old_trans_id = self.trans_id_tree_file_id(file_id)
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
687
                conflicts.append(('duplicate id', old_trans_id, trans_id))
688
        return conflicts
689
1534.7.11 by Aaron Bentley
Refactored conflict handling
690
    def _parent_type_conflicts(self, by_parent):
691
        """parents must have directory 'contents'."""
692
        conflicts = []
1534.7.37 by Aaron Bentley
Allowed removed dirs to have content-free children.
693
        for parent_id, children in by_parent.iteritems():
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
694
            if parent_id is ROOT_PARENT:
695
                continue
1534.7.37 by Aaron Bentley
Allowed removed dirs to have content-free children.
696
            if not self._any_contents(children):
697
                continue
698
            for child in children:
699
                try:
700
                    self.final_kind(child)
701
                except NoSuchFile:
702
                    continue
1534.7.10 by Aaron Bentley
Implemented missing parent and non-directory parent conflicts
703
            try:
704
                kind = self.final_kind(parent_id)
705
            except NoSuchFile:
706
                kind = None
707
            if kind is None:
708
                conflicts.append(('missing parent', parent_id))
709
            elif kind != "directory":
710
                conflicts.append(('non-directory parent', parent_id))
1534.7.6 by Aaron Bentley
Added conflict handling
711
        return conflicts
1534.7.37 by Aaron Bentley
Allowed removed dirs to have content-free children.
712
713
    def _any_contents(self, trans_ids):
714
        """Return true if any of the trans_ids, will have contents."""
715
        for trans_id in trans_ids:
716
            try:
717
                kind = self.final_kind(trans_id)
718
            except NoSuchFile:
719
                continue
720
            return True
721
        return False
1534.7.6 by Aaron Bentley
Added conflict handling
722
            
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
723
    def apply(self):
1534.7.156 by Aaron Bentley
PEP8 fixes
724
        """Apply all changes to the inventory and filesystem.
1534.7.21 by Aaron Bentley
Updated docstrings
725
        
726
        If filesystem or inventory conflicts are present, MalformedTransform
727
        will be thrown.
728
        """
1534.7.49 by Aaron Bentley
Printed conflicts in MalformedTransform
729
        conflicts = self.find_conflicts()
730
        if len(conflicts) != 0:
731
            raise MalformedTransform(conflicts=conflicts)
1534.7.41 by Aaron Bentley
Got inventory ID movement working
732
        limbo_inv = {}
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
733
        inv = self._tree.inventory
1551.2.31 by Aaron Bentley
Got merge and revert using nested pbs
734
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
735
        try:
736
            child_pb.update('Apply phase', 0, 2)
737
            self._apply_removals(inv, limbo_inv)
738
            child_pb.update('Apply phase', 1, 2)
739
            modified_paths = self._apply_insertions(inv, limbo_inv)
740
        finally:
741
            child_pb.finished()
1534.7.35 by Aaron Bentley
Got file renaming working
742
        self._tree._write_inventory(inv)
743
        self.__done = True
1534.7.59 by Aaron Bentley
Simplified tests
744
        self.finalize()
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
745
        return _TransformResults(modified_paths)
1534.7.35 by Aaron Bentley
Got file renaming working
746
1534.7.72 by Aaron Bentley
Moved new content generation to pre-renames
747
    def _limbo_name(self, trans_id):
748
        """Generate the limbo name of a file"""
1534.7.166 by Aaron Bentley
Swapped os.path.join for pathjoin everywhere
749
        return pathjoin(self._limbodir, trans_id)
1534.7.72 by Aaron Bentley
Moved new content generation to pre-renames
750
1534.7.41 by Aaron Bentley
Got inventory ID movement working
751
    def _apply_removals(self, inv, limbo_inv):
1534.7.36 by Aaron Bentley
Added rename tests
752
        """Perform tree operations that remove directory/inventory names.
753
        
754
        That is, delete files that are to be deleted, and put any files that
755
        need renaming into limbo.  This must be done in strict child-to-parent
756
        order.
757
        """
1534.7.35 by Aaron Bentley
Got file renaming working
758
        tree_paths = list(self._tree_path_ids.iteritems())
759
        tree_paths.sort(reverse=True)
1551.2.31 by Aaron Bentley
Got merge and revert using nested pbs
760
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
761
        try:
762
            for num, data in enumerate(tree_paths):
763
                path, trans_id = data
764
                child_pb.update('removing file', num, len(tree_paths))
765
                full_path = self._tree.abspath(path)
766
                if trans_id in self._removed_contents:
1558.12.9 by Aaron Bentley
Handle resolving conflicts with directories properly
767
                    delete_any(full_path)
1551.2.31 by Aaron Bentley
Got merge and revert using nested pbs
768
                elif trans_id in self._new_name or trans_id in \
769
                    self._new_parent:
770
                    try:
771
                        os.rename(full_path, self._limbo_name(trans_id))
772
                    except OSError, e:
773
                        if e.errno != errno.ENOENT:
774
                            raise
775
                if trans_id in self._removed_id:
776
                    if trans_id == self._new_root:
777
                        file_id = self._tree.inventory.root.file_id
778
                    else:
779
                        file_id = self.tree_file_id(trans_id)
780
                    del inv[file_id]
781
                elif trans_id in self._new_name or trans_id in self._new_parent:
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
782
                    file_id = self.tree_file_id(trans_id)
1551.2.31 by Aaron Bentley
Got merge and revert using nested pbs
783
                    if file_id is not None:
784
                        limbo_inv[trans_id] = inv[file_id]
785
                        del inv[file_id]
786
        finally:
787
            child_pb.finished()
1534.7.34 by Aaron Bentley
Proper conflicts for removals
788
1534.7.41 by Aaron Bentley
Got inventory ID movement working
789
    def _apply_insertions(self, inv, limbo_inv):
1534.7.36 by Aaron Bentley
Added rename tests
790
        """Perform tree operations that insert directory/inventory names.
791
        
792
        That is, create any files that need to be created, and restore from
793
        limbo any files that needed renaming.  This must be done in strict
794
        parent-to-child order.
795
        """
1534.9.1 by Aaron Bentley
Added progress bars to merge
796
        new_paths = self.new_paths()
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
797
        modified_paths = []
1551.2.31 by Aaron Bentley
Got merge and revert using nested pbs
798
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
799
        try:
800
            for num, (path, trans_id) in enumerate(new_paths):
801
                child_pb.update('adding file', num, len(new_paths))
1534.7.48 by Aaron Bentley
Ensured we can move/rename dangling inventory entries
802
                try:
1551.2.31 by Aaron Bentley
Got merge and revert using nested pbs
803
                    kind = self._new_contents[trans_id]
804
                except KeyError:
805
                    kind = contents = None
806
                if trans_id in self._new_contents or \
807
                    self.path_changed(trans_id):
808
                    full_path = self._tree.abspath(path)
809
                    try:
810
                        os.rename(self._limbo_name(trans_id), full_path)
811
                    except OSError, e:
812
                        # We may be renaming a dangling inventory id
813
                        if e.errno != errno.ENOENT:
814
                            raise
815
                    if trans_id in self._new_contents:
816
                        modified_paths.append(full_path)
817
                        del self._new_contents[trans_id]
818
819
                if trans_id in self._new_id:
820
                    if kind is None:
821
                        kind = file_kind(self._tree.abspath(path))
822
                    inv.add_path(path, kind, self._new_id[trans_id])
823
                elif trans_id in self._new_name or trans_id in\
824
                    self._new_parent:
825
                    entry = limbo_inv.get(trans_id)
826
                    if entry is not None:
827
                        entry.name = self.final_name(trans_id)
828
                        parent_path = os.path.dirname(path)
829
                        entry.parent_id = \
830
                            self._tree.inventory.path2id(parent_path)
831
                        inv.add(entry)
832
833
                # requires files and inventory entries to be in place
834
                if trans_id in self._new_executability:
835
                    self._set_executability(path, inv, trans_id)
836
        finally:
837
            child_pb.finished()
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
838
        return modified_paths
1534.7.40 by Aaron Bentley
Updated docs
839
1534.7.25 by Aaron Bentley
Added set_executability
840
    def _set_executability(self, path, inv, trans_id):
1534.7.40 by Aaron Bentley
Updated docs
841
        """Set the executability of versioned files """
1534.7.25 by Aaron Bentley
Added set_executability
842
        file_id = inv.path2id(path)
843
        new_executability = self._new_executability[trans_id]
844
        inv[file_id].executable = new_executability
845
        if supports_executable():
846
            abspath = self._tree.abspath(path)
847
            current_mode = os.stat(abspath).st_mode
848
            if new_executability:
849
                umask = os.umask(0)
850
                os.umask(umask)
851
                to_mode = current_mode | (0100 & ~umask)
852
                # Enable x-bit for others only if they can read it.
853
                if current_mode & 0004:
854
                    to_mode |= 0001 & ~umask
855
                if current_mode & 0040:
856
                    to_mode |= 0010 & ~umask
857
            else:
858
                to_mode = current_mode & ~0111
859
            os.chmod(abspath, to_mode)
860
1534.7.23 by Aaron Bentley
Transform.new_entry -> Transform._new_entry
861
    def _new_entry(self, name, parent_id, file_id):
1534.7.21 by Aaron Bentley
Updated docstrings
862
        """Helper function to create a new filesystem entry."""
1534.7.2 by Aaron Bentley
Added convenience function
863
        trans_id = self.create_path(name, parent_id)
864
        if file_id is not None:
865
            self.version_file(file_id, trans_id)
866
        return trans_id
867
1534.7.27 by Aaron Bentley
Added execute bit to new_file method
868
    def new_file(self, name, parent_id, contents, file_id=None, 
869
                 executable=None):
1534.7.156 by Aaron Bentley
PEP8 fixes
870
        """Convenience method to create files.
1534.7.21 by Aaron Bentley
Updated docstrings
871
        
872
        name is the name of the file to create.
873
        parent_id is the transaction id of the parent directory of the file.
874
        contents is an iterator of bytestrings, which will be used to produce
875
        the file.
1740.2.4 by Aaron Bentley
Update transform tests and docs
876
        :param file_id: The inventory ID of the file, if it is to be versioned.
877
        :param executable: Only valid when a file_id has been supplied.
1534.7.21 by Aaron Bentley
Updated docstrings
878
        """
1534.7.23 by Aaron Bentley
Transform.new_entry -> Transform._new_entry
879
        trans_id = self._new_entry(name, parent_id, file_id)
1740.2.4 by Aaron Bentley
Update transform tests and docs
880
        # TODO: rather than scheduling a set_executable call,
881
        # have create_file create the file with the right mode.
1534.7.20 by Aaron Bentley
Added directory handling
882
        self.create_file(contents, trans_id)
1534.7.27 by Aaron Bentley
Added execute bit to new_file method
883
        if executable is not None:
884
            self.set_executability(executable, trans_id)
1534.7.20 by Aaron Bentley
Added directory handling
885
        return trans_id
886
887
    def new_directory(self, name, parent_id, file_id=None):
1534.7.156 by Aaron Bentley
PEP8 fixes
888
        """Convenience method to create directories.
1534.7.21 by Aaron Bentley
Updated docstrings
889
890
        name is the name of the directory to create.
891
        parent_id is the transaction id of the parent directory of the
892
        directory.
893
        file_id is the inventory ID of the directory, if it is to be versioned.
894
        """
1534.7.23 by Aaron Bentley
Transform.new_entry -> Transform._new_entry
895
        trans_id = self._new_entry(name, parent_id, file_id)
1534.7.20 by Aaron Bentley
Added directory handling
896
        self.create_directory(trans_id)
897
        return trans_id 
898
1534.7.22 by Aaron Bentley
Added symlink support
899
    def new_symlink(self, name, parent_id, target, file_id=None):
1534.7.156 by Aaron Bentley
PEP8 fixes
900
        """Convenience method to create symbolic link.
1534.7.22 by Aaron Bentley
Added symlink support
901
        
902
        name is the name of the symlink to create.
903
        parent_id is the transaction id of the parent directory of the symlink.
904
        target is a bytestring of the target of the symlink.
905
        file_id is the inventory ID of the file, if it is to be versioned.
906
        """
1534.7.23 by Aaron Bentley
Transform.new_entry -> Transform._new_entry
907
        trans_id = self._new_entry(name, parent_id, file_id)
1534.7.22 by Aaron Bentley
Added symlink support
908
        self.create_symlink(target, trans_id)
909
        return trans_id
910
1551.11.12 by Aaron Bentley
Changes from review
911
    def _affected_ids(self):
912
        """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
913
        trans_ids = set(self._removed_id)
914
        trans_ids.update(self._new_id.keys())
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
915
        trans_ids.update(self._removed_contents)
916
        trans_ids.update(self._new_contents.keys())
917
        trans_ids.update(self._new_executability.keys())
918
        trans_ids.update(self._new_name.keys())
919
        trans_ids.update(self._new_parent.keys())
1551.11.12 by Aaron Bentley
Changes from review
920
        return trans_ids
921
922
    def _get_file_id_maps(self):
923
        """Return mapping of file_ids to trans_ids in the to and from states"""
924
        trans_ids = self._affected_ids()
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
925
        from_trans_ids = {}
926
        to_trans_ids = {}
927
        # Build up two dicts: trans_ids associated with file ids in the
928
        # FROM state, vs the TO state.
929
        for trans_id in trans_ids:
930
            from_file_id = self.tree_file_id(trans_id)
931
            if from_file_id is not None:
932
                from_trans_ids[from_file_id] = trans_id
933
            to_file_id = self.final_file_id(trans_id)
934
            if to_file_id is not None:
935
                to_trans_ids[to_file_id] = trans_id
1551.11.12 by Aaron Bentley
Changes from review
936
        return from_trans_ids, to_trans_ids
937
938
    def _from_file_data(self, from_trans_id, from_versioned, file_id):
939
        """Get data about a file in the from (tree) state
940
941
        Return a (name, parent, kind, executable) tuple
942
        """
943
        from_path = self._tree_id_paths.get(from_trans_id)
944
        if from_versioned:
945
            # get data from working tree if versioned
946
            from_entry = self._tree.inventory[file_id]
947
            from_name = from_entry.name
948
            from_parent = from_entry.parent_id
949
        else:
950
            from_entry = None
951
            if from_path is None:
952
                # File does not exist in FROM state
953
                from_name = None
954
                from_parent = None
955
            else:
956
                # File exists, but is not versioned.  Have to use path-
957
                # splitting stuff
958
                from_name = os.path.basename(from_path)
959
                tree_parent = self.get_tree_parent(from_trans_id)
960
                from_parent = self.tree_file_id(tree_parent)
961
        if from_path is not None:
962
            from_kind, from_executable, from_stats = \
963
                self._tree._comparison_data(from_entry, from_path)
964
        else:
965
            from_kind = None
966
            from_executable = False
967
        return from_name, from_parent, from_kind, from_executable
968
969
    def _to_file_data(self, to_trans_id, from_trans_id, from_executable):
970
        """Get data about a file in the to (target) state
971
972
        Return a (name, parent, kind, executable) tuple
973
        """
974
        to_name = self.final_name(to_trans_id)
975
        try:
976
            to_kind = self.final_kind(to_trans_id)
977
        except NoSuchFile:
978
            to_kind = None
979
        to_parent = self.final_file_id(self.final_parent(to_trans_id))
980
        if to_trans_id in self._new_executability:
981
            to_executable = self._new_executability[to_trans_id]
982
        elif to_trans_id == from_trans_id:
983
            to_executable = from_executable
984
        else:
985
            to_executable = False
986
        return to_name, to_parent, to_kind, to_executable
987
988
    def _iter_changes(self):
989
        """Produce output in the same format as Tree._iter_changes.
990
991
        Will produce nonsensical results if invoked while inventory/filesystem
992
        conflicts (as reported by TreeTransform.find_conflicts()) are present.
993
994
        This reads the Transform, but only reproduces changes involving a
995
        file_id.  Files that are not versioned in either of the FROM or TO
996
        states are not reflected.
997
        """
998
        final_paths = FinalPaths(self)
999
        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
1000
        results = []
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1001
        # Now iterate through all active file_ids
1002
        for file_id in set(from_trans_ids.keys() + to_trans_ids.keys()):
1551.11.7 by Aaron Bentley
Stop modified flag bleeding into later changes
1003
            modified = False
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1004
            from_trans_id = from_trans_ids.get(file_id)
1005
            # find file ids, and determine versioning state
1006
            if from_trans_id is None:
1007
                from_versioned = False
1008
                from_trans_id = to_trans_ids[file_id]
1009
            else:
1010
                from_versioned = True
1011
            to_trans_id = to_trans_ids.get(file_id)
1012
            if to_trans_id is None:
1013
                to_versioned = False
1014
                to_trans_id = from_trans_id
1015
            else:
1016
                to_versioned = True
1551.11.12 by Aaron Bentley
Changes from review
1017
1018
            from_name, from_parent, from_kind, from_executable = \
1019
                self._from_file_data(from_trans_id, from_versioned, file_id)
1020
1021
            to_name, to_parent, to_kind, to_executable = \
1022
                self._to_file_data(to_trans_id, from_trans_id, from_executable)
1023
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1024
            to_path = final_paths.get_path(to_trans_id)
1025
            if from_kind != to_kind:
1026
                modified = True
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1027
            elif to_kind in ('file' or 'symlink') and (
1028
                to_trans_id != from_trans_id or
1029
                to_trans_id in self._new_contents):
1030
                modified = True
1031
            if (not modified and from_versioned == to_versioned and
1032
                from_parent==to_parent and from_name == to_name and
1033
                from_executable == to_executable):
1034
                continue
1551.11.4 by Aaron Bentley
Sort output of Transform.iter_changes by path
1035
            results.append((file_id, to_path, modified,
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1036
                   (from_versioned, to_versioned),
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1037
                   (from_parent, to_parent),
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1038
                   (from_name, to_name),
1039
                   (from_kind, to_kind),
1551.11.4 by Aaron Bentley
Sort output of Transform.iter_changes by path
1040
                   (from_executable, to_executable)))
1041
        return iter(sorted(results, key=lambda x:x[1]))
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1042
1043
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
1044
def joinpath(parent, child):
1534.7.40 by Aaron Bentley
Updated docs
1045
    """Join tree-relative paths, handling the tree root specially"""
1534.7.32 by Aaron Bentley
Got conflict handling working when conflicts involve existing files
1046
    if parent is None or parent == "":
1047
        return child
1048
    else:
1534.7.166 by Aaron Bentley
Swapped os.path.join for pathjoin everywhere
1049
        return pathjoin(parent, child)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1050
1534.7.167 by Aaron Bentley
PEP8 and comment cleanups
1051
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1052
class FinalPaths(object):
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
1053
    """Make path calculation cheap by memoizing paths.
1534.7.21 by Aaron Bentley
Updated docstrings
1054
1055
    The underlying tree must not be manipulated between calls, or else
1056
    the results will likely be incorrect.
1057
    """
1534.7.132 by Aaron Bentley
Got cooked conflicts working
1058
    def __init__(self, transform):
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1059
        object.__init__(self)
1060
        self._known_paths = {}
1534.7.33 by Aaron Bentley
Fixed naming
1061
        self.transform = transform
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1062
1063
    def _determine_path(self, trans_id):
1534.7.132 by Aaron Bentley
Got cooked conflicts working
1064
        if trans_id == self.transform.root:
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1065
            return ""
1534.7.33 by Aaron Bentley
Fixed naming
1066
        name = self.transform.final_name(trans_id)
1067
        parent_id = self.transform.final_parent(trans_id)
1534.7.132 by Aaron Bentley
Got cooked conflicts working
1068
        if parent_id == self.transform.root:
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1069
            return name
1070
        else:
1534.7.166 by Aaron Bentley
Swapped os.path.join for pathjoin everywhere
1071
            return pathjoin(self.get_path(parent_id), name)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1072
1073
    def get_path(self, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
1074
        """Find the final path associated with a trans_id"""
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
1075
        if trans_id not in self._known_paths:
1076
            self._known_paths[trans_id] = self._determine_path(trans_id)
1077
        return self._known_paths[trans_id]
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
1078
1534.7.30 by Aaron Bentley
Factored out topological id sorting
1079
def topology_sorted_ids(tree):
1534.7.40 by Aaron Bentley
Updated docs
1080
    """Determine the topological order of the ids in a tree"""
1534.7.30 by Aaron Bentley
Factored out topological id sorting
1081
    file_ids = list(tree)
1082
    file_ids.sort(key=tree.id2path)
1083
    return file_ids
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
1084
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1085
1534.7.165 by Aaron Bentley
Switched to build_tree instead of revert
1086
def build_tree(tree, wt):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1087
    """Create working tree for a branch, using a TreeTransform.
1088
    
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1089
    This function should be used on empty trees, having a tree root at most.
1090
    (see merge and revert functionality for working with existing trees)
1091
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1092
    Existing files are handled like so:
1093
    
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1094
    - Existing bzrdirs take precedence over creating new items.  They are
1095
      created as '%s.diverted' % name.
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1096
    - Otherwise, if the content on disk matches the content we are building,
1097
      it is silently replaced.
1098
    - Otherwise, conflict resolution will move the old file to 'oldname.moved'.
1099
    """
2255.7.51 by Robert Collins
Lock build_tree trees in write-first order, to support older formats that dont do lock_tree_write nicely.
1100
    wt.lock_tree_write()
2255.7.49 by Robert Collins
Lock trees passed in to build_tree.
1101
    try:
2255.7.51 by Robert Collins
Lock build_tree trees in write-first order, to support older formats that dont do lock_tree_write nicely.
1102
        tree.lock_read()
2255.7.49 by Robert Collins
Lock trees passed in to build_tree.
1103
        try:
1104
            return _build_tree(tree, wt)
1105
        finally:
2255.7.51 by Robert Collins
Lock build_tree trees in write-first order, to support older formats that dont do lock_tree_write nicely.
1106
            tree.unlock()
2255.7.49 by Robert Collins
Lock trees passed in to build_tree.
1107
    finally:
2255.7.51 by Robert Collins
Lock build_tree trees in write-first order, to support older formats that dont do lock_tree_write nicely.
1108
        wt.unlock()
2255.7.49 by Robert Collins
Lock trees passed in to build_tree.
1109
1110
def _build_tree(tree, wt):
1111
    """See build_tree."""
2090.2.1 by Martin Pool
Fix some code which relies on assertions and breaks under python -O
1112
    if len(wt.inventory) > 1:  # more than just a root
1113
        raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
1114
    file_trans_id = {}
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
1115
    top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1116
    pp = ProgressPhase("Build phase", 2, top_pb)
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1117
#    if tree.inventory.root is not None:
1118
#        wt.set_root_id(tree.inventory.root.file_id)
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
1119
    tt = TreeTransform(wt)
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1120
    divert = set()
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
1121
    try:
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
1122
        pp.next_phase()
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1123
        file_trans_id[wt.get_root_id()] = \
1124
            tt.trans_id_tree_file_id(wt.get_root_id())
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
1125
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1126
        try:
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1127
            for num, (tree_path, entry) in \
1128
                enumerate(tree.inventory.iter_entries_by_dir()):
1129
                pb.update("Building tree", num, len(tree.inventory))
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
1130
                if entry.parent_id is None:
1131
                    continue
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1132
                reparent = False
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1133
                file_id = entry.file_id
1134
                target_path = wt.abspath(tree_path)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1135
                try:
1136
                    kind = file_kind(target_path)
1137
                except NoSuchFile:
1138
                    pass
1139
                else:
1140
                    if kind == "directory":
1141
                        try:
1142
                            bzrdir.BzrDir.open(target_path)
1143
                        except errors.NotBranchError:
1144
                            pass
1145
                        else:
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1146
                            divert.add(file_id)
1147
                    if (file_id not in divert and
1148
                        _content_match(tree, entry, file_id, kind,
1149
                        target_path)):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1150
                        tt.delete_contents(tt.trans_id_tree_path(tree_path))
1151
                        if kind == 'directory':
1152
                            reparent = True
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
1153
                if entry.parent_id not in file_trans_id:
1154
                    raise repr(entry.parent_id)
1155
                parent_id = file_trans_id[entry.parent_id]
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1156
                file_trans_id[file_id] = new_by_entry(tt, entry, parent_id,
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
1157
                                                      tree)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1158
                if reparent:
1159
                    new_trans_id = file_trans_id[file_id]
1160
                    old_parent = tt.trans_id_tree_path(tree_path)
1161
                    _reparent_children(tt, old_parent, new_trans_id)
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
1162
        finally:
1163
            pb.finished()
1164
        pp.next_phase()
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1165
        divert_trans = set(file_trans_id[f] for f in divert)
1166
        resolver = lambda t, c: resolve_checkout(t, c, divert_trans)
1167
        raw_conflicts = resolve_conflicts(tt, pass_func=resolver)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1168
        conflicts = cook_conflicts(raw_conflicts, tt)
1169
        for conflict in conflicts:
1170
            warning(conflict)
1171
        try:
1172
            wt.add_conflicts(conflicts)
1173
        except errors.UnsupportedOperation:
1174
            pass
1534.7.47 by Aaron Bentley
Started work on 'revert'
1175
        tt.apply()
1176
    finally:
1177
        tt.finalize()
1558.11.1 by Aaron Bentley
Progress indicator for tree builts
1178
        top_pb.finished()
1534.7.47 by Aaron Bentley
Started work on 'revert'
1179
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1180
1181
def _reparent_children(tt, old_parent, new_parent):
1182
    for child in tt.iter_tree_children(old_parent):
1183
        tt.adjust_path(tt.final_name(child), new_parent, child)
1184
1185
1186
def _content_match(tree, entry, file_id, kind, target_path):
1187
    if entry.kind != kind:
1188
        return False
1189
    if entry.kind == "directory":
1190
        return True
1191
    if entry.kind == "file":
1192
        if tree.get_file(file_id).read() == file(target_path, 'rb').read():
1193
            return True
1194
    elif entry.kind == "symlink":
1195
        if tree.get_symlink_target(file_id) == os.readlink(target_path):
1196
            return True
1197
    return False
1198
1199
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1200
def resolve_checkout(tt, conflicts, divert):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1201
    new_conflicts = set()
1202
    for c_type, conflict in ((c[0], c) for c in conflicts):
1203
        # Anything but a 'duplicate' would indicate programmer error
1204
        assert c_type == 'duplicate', c_type
1205
        # 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
1206
        if tt.new_contents(conflict[1]):
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1207
            new_file = conflict[1]
1208
            old_file = conflict[2]
1209
        else:
1210
            new_file = conflict[2]
1211
            old_file = conflict[1]
1212
1213
        # We should only get here if the conflict wasn't completely
1214
        # resolved
1215
        final_parent = tt.final_parent(old_file)
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1216
        if new_file in divert:
1217
            new_name = tt.final_name(old_file)+'.diverted'
1218
            tt.adjust_path(new_name, final_parent, new_file)
1219
            new_conflicts.add((c_type, 'Diverted to',
1220
                               new_file, old_file))
1221
        else:
1222
            new_name = tt.final_name(old_file)+'.moved'
1223
            tt.adjust_path(new_name, final_parent, old_file)
1224
            new_conflicts.add((c_type, 'Moved existing file to',
1225
                               old_file, new_file))
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1226
    return new_conflicts
1227
1228
1534.7.47 by Aaron Bentley
Started work on 'revert'
1229
def new_by_entry(tt, entry, parent_id, tree):
1534.7.157 by Aaron Bentley
Added more docs
1230
    """Create a new file according to its inventory entry"""
1534.7.47 by Aaron Bentley
Started work on 'revert'
1231
    name = entry.name
1232
    kind = entry.kind
1233
    if kind == 'file':
1534.7.79 by Aaron Bentley
Stopped calling get_file_lines on WorkingTree
1234
        contents = tree.get_file(entry.file_id).readlines()
1534.7.47 by Aaron Bentley
Started work on 'revert'
1235
        executable = tree.is_executable(entry.file_id)
1236
        return tt.new_file(name, parent_id, contents, entry.file_id, 
1237
                           executable)
1238
    elif kind == 'directory':
1534.7.54 by Aaron Bentley
Fixed thinko
1239
        return tt.new_directory(name, parent_id, entry.file_id)
1534.7.47 by Aaron Bentley
Started work on 'revert'
1240
    elif kind == 'symlink':
1534.7.183 by Aaron Bentley
Fixed build_tree with symlinks
1241
        target = tree.get_symlink_target(entry.file_id)
1242
        return tt.new_symlink(name, parent_id, target, entry.file_id)
1534.7.47 by Aaron Bentley
Started work on 'revert'
1243
1534.7.117 by Aaron Bentley
Simplified permission handling of existing files in transform.
1244
def create_by_entry(tt, entry, tree, trans_id, lines=None, mode_id=None):
1534.7.157 by Aaron Bentley
Added more docs
1245
    """Create new file contents according to an inventory entry."""
1534.7.47 by Aaron Bentley
Started work on 'revert'
1246
    if entry.kind == "file":
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1247
        if lines is None:
1534.7.97 by Aaron Bentley
Ensured foo.BASE is a directory if there's a conflict
1248
            lines = tree.get_file(entry.file_id).readlines()
1534.7.117 by Aaron Bentley
Simplified permission handling of existing files in transform.
1249
        tt.create_file(lines, trans_id, mode_id=mode_id)
1534.7.47 by Aaron Bentley
Started work on 'revert'
1250
    elif entry.kind == "symlink":
1534.7.101 by Aaron Bentley
Got conflicts on symlinks working properly
1251
        tt.create_symlink(tree.get_symlink_target(entry.file_id), trans_id)
1534.7.47 by Aaron Bentley
Started work on 'revert'
1252
    elif entry.kind == "directory":
1534.7.51 by Aaron Bentley
New approach to revert
1253
        tt.create_directory(trans_id)
1534.7.47 by Aaron Bentley
Started work on 'revert'
1254
1534.7.89 by Aaron Bentley
Handle all content types in three-way
1255
def create_entry_executability(tt, entry, trans_id):
1534.7.157 by Aaron Bentley
Added more docs
1256
    """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
1257
    if entry.kind == "file":
1258
        tt.set_executability(entry.executable, trans_id)
1534.7.47 by Aaron Bentley
Started work on 'revert'
1259
1534.7.157 by Aaron Bentley
Added more docs
1260
2255.7.48 by Robert Collins
Deprecated and make work with DirState trees 'transform.find_interesting'.
1261
@deprecated_function(zero_fifteen)
1534.7.55 by Aaron Bentley
Fixed up the change detection
1262
def find_interesting(working_tree, target_tree, filenames):
2255.7.48 by Robert Collins
Deprecated and make work with DirState trees 'transform.find_interesting'.
1263
    """Find the ids corresponding to specified filenames.
1264
    
1265
    Deprecated: Please use tree1.paths2ids(filenames, [tree2]).
1266
    """
1267
    working_tree.lock_read()
1268
    try:
1269
        target_tree.lock_read()
1270
        try:
1271
            return working_tree.paths2ids(filenames, [target_tree])
1272
        finally:
1273
            target_tree.unlock()
1274
    finally:
1275
        working_tree.unlock()
1534.7.55 by Aaron Bentley
Fixed up the change detection
1276
1277
1534.7.56 by Aaron Bentley
Implemented the backup file detritus
1278
def change_entry(tt, file_id, working_tree, target_tree, 
1534.10.28 by Aaron Bentley
Use numbered backup files
1279
                 trans_id_file_id, backups, trans_id, by_parent):
1534.7.157 by Aaron Bentley
Added more docs
1280
    """Replace a file_id's contents with those from a target tree."""
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
1281
    e_trans_id = trans_id_file_id(file_id)
1534.7.55 by Aaron Bentley
Fixed up the change detection
1282
    entry = target_tree.inventory[file_id]
1283
    has_contents, contents_mod, meta_mod, = _entry_changes(file_id, entry, 
1284
                                                           working_tree)
1285
    if contents_mod:
1534.7.117 by Aaron Bentley
Simplified permission handling of existing files in transform.
1286
        mode_id = e_trans_id
1534.7.55 by Aaron Bentley
Fixed up the change detection
1287
        if has_contents:
1534.7.56 by Aaron Bentley
Implemented the backup file detritus
1288
            if not backups:
1289
                tt.delete_contents(e_trans_id)
1290
            else:
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
1291
                parent_trans_id = trans_id_file_id(entry.parent_id)
1534.10.28 by Aaron Bentley
Use numbered backup files
1292
                backup_name = get_backup_name(entry, by_parent,
1293
                                              parent_trans_id, tt)
1294
                tt.adjust_path(backup_name, parent_trans_id, e_trans_id)
1534.7.56 by Aaron Bentley
Implemented the backup file detritus
1295
                tt.unversion_file(e_trans_id)
1296
                e_trans_id = tt.create_path(entry.name, parent_trans_id)
1297
                tt.version_file(file_id, e_trans_id)
1298
                trans_id[file_id] = e_trans_id
1534.7.117 by Aaron Bentley
Simplified permission handling of existing files in transform.
1299
        create_by_entry(tt, entry, target_tree, e_trans_id, mode_id=mode_id)
1534.7.89 by Aaron Bentley
Handle all content types in three-way
1300
        create_entry_executability(tt, entry, e_trans_id)
1301
1711.4.26 by John Arbash Meinel
Fix #45010 correctly. Don't forget the execute bit.
1302
    elif meta_mod:
1303
        tt.set_executability(entry.executable, e_trans_id)
1534.7.55 by Aaron Bentley
Fixed up the change detection
1304
    if tt.final_name(e_trans_id) != entry.name:
1305
        adjust_path  = True
1306
    else:
1307
        parent_id = tt.final_parent(e_trans_id)
1308
        parent_file_id = tt.final_file_id(parent_id)
1309
        if parent_file_id != entry.parent_id:
1310
            adjust_path = True
1311
        else:
1312
            adjust_path = False
1313
    if adjust_path:
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
1314
        parent_trans_id = trans_id_file_id(entry.parent_id)
1534.7.56 by Aaron Bentley
Implemented the backup file detritus
1315
        tt.adjust_path(entry.name, parent_trans_id, e_trans_id)
1534.7.55 by Aaron Bentley
Fixed up the change detection
1316
1317
1534.10.28 by Aaron Bentley
Use numbered backup files
1318
def get_backup_name(entry, by_parent, parent_trans_id, tt):
2012.1.12 by Aaron Bentley
Use iter_changes for revert
1319
    return _get_backup_name(entry.name, by_parent, parent_trans_id, tt)
1320
1321
1322
def _get_backup_name(name, by_parent, parent_trans_id, tt):
1534.10.28 by Aaron Bentley
Use numbered backup files
1323
    """Produce a backup-style name that appears to be available"""
1324
    def name_gen():
1325
        counter = 1
1326
        while True:
2012.1.12 by Aaron Bentley
Use iter_changes for revert
1327
            yield "%s.~%d~" % (name, counter)
1534.10.28 by Aaron Bentley
Use numbered backup files
1328
            counter += 1
2012.1.12 by Aaron Bentley
Use iter_changes for revert
1329
    for new_name in name_gen():
1330
        if not tt.has_named_child(by_parent, parent_trans_id, new_name):
1331
            return new_name
1332
1534.10.28 by Aaron Bentley
Use numbered backup files
1333
1534.7.55 by Aaron Bentley
Fixed up the change detection
1334
def _entry_changes(file_id, entry, working_tree):
1534.7.156 by Aaron Bentley
PEP8 fixes
1335
    """Determine in which ways the inventory entry has changed.
1534.7.55 by Aaron Bentley
Fixed up the change detection
1336
1337
    Returns booleans: has_contents, content_mod, meta_mod
1338
    has_contents means there are currently contents, but they differ
1339
    contents_mod means contents need to be modified
1340
    meta_mod means the metadata needs to be modified
1341
    """
1342
    cur_entry = working_tree.inventory[file_id]
1343
    try:
1344
        working_kind = working_tree.kind(file_id)
1345
        has_contents = True
1757.2.4 by Robert Collins
Teach file_kind about NoSuchFile, reducing duplicate code, and add user files before entering the main loop in smart_add.
1346
    except NoSuchFile:
1534.7.55 by Aaron Bentley
Fixed up the change detection
1347
        has_contents = False
1348
        contents_mod = True
1349
        meta_mod = False
1350
    if has_contents is True:
1731.1.1 by Aaron Bentley
Make root entry an InventoryDirectory, make EmptyTree really empty
1351
        if entry.kind != working_kind:
1534.7.55 by Aaron Bentley
Fixed up the change detection
1352
            contents_mod, meta_mod = True, False
1353
        else:
1354
            cur_entry._read_tree_state(working_tree.id2path(file_id), 
1355
                                       working_tree)
1356
            contents_mod, meta_mod = entry.detect_changes(cur_entry)
1534.7.175 by Aaron Bentley
Ensured revert writes a normal inventory
1357
            cur_entry._forget_tree_state()
1534.7.55 by Aaron Bentley
Fixed up the change detection
1358
    return has_contents, contents_mod, meta_mod
1359
1534.7.56 by Aaron Bentley
Implemented the backup file detritus
1360
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
1361
def revert(working_tree, target_tree, filenames, backups=False,
2225.1.1 by Aaron Bentley
Added revert change display, with tests
1362
           pb=DummyProgress(), change_reporter=None):
1534.7.157 by Aaron Bentley
Added more docs
1363
    """Revert a working tree's contents to those of a target tree."""
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
1364
    target_tree.lock_read()
1534.9.7 by Aaron Bentley
Show progress bars in revert
1365
    tt = TreeTransform(working_tree, pb)
1534.7.47 by Aaron Bentley
Started work on 'revert'
1366
    try:
2012.1.12 by Aaron Bentley
Use iter_changes for revert
1367
        pp = ProgressPhase("Revert phase", 3, pb)
1368
        pp.next_phase()
1369
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1370
        try:
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
1371
            _alter_files(working_tree, target_tree, tt, child_pb,
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1372
                         filenames, backups)
1551.2.31 by Aaron Bentley
Got merge and revert using nested pbs
1373
        finally:
1374
            child_pb.finished()
1551.2.34 by Aaron Bentley
Refactored the revert phases
1375
        pp.next_phase()
1551.2.31 by Aaron Bentley
Got merge and revert using nested pbs
1376
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1377
        try:
1378
            raw_conflicts = resolve_conflicts(tt, child_pb)
1379
        finally:
1380
            child_pb.finished()
1558.7.13 by Aaron Bentley
WorkingTree.revert returns conflicts
1381
        conflicts = cook_conflicts(raw_conflicts, tt)
1551.11.5 by Aaron Bentley
cleanup
1382
        if change_reporter:
1383
            change_reporter = delta.ChangeReporter(working_tree.inventory)
1384
            delta.report_changes(tt._iter_changes(), change_reporter)
1551.11.6 by Aaron Bentley
Emit change listings before conflict warnings
1385
        for conflict in conflicts:
1386
            warning(conflict)
1387
        pp.next_phase()
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
1388
        tt.apply()
1534.7.193 by Aaron Bentley
Stopped revert from preserving file contents produced by merges
1389
        working_tree.set_merge_modified({})
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
1390
    finally:
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
1391
        target_tree.unlock()
1534.7.28 by Aaron Bentley
Nearly-working build_tree replacement
1392
        tt.finalize()
1534.9.4 by Aaron Bentley
Added progress bars to revert.
1393
        pb.clear()
1558.7.13 by Aaron Bentley
WorkingTree.revert returns conflicts
1394
    return conflicts
1534.7.51 by Aaron Bentley
New approach to revert
1395
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
1396
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1397
def _alter_files(working_tree, target_tree, tt, pb, specific_files,
1551.11.3 by Aaron Bentley
Use tree transform to emit upcoming change list
1398
                 backups):
2012.1.12 by Aaron Bentley
Use iter_changes for revert
1399
    merge_modified = working_tree.merge_modified()
1551.11.3 by Aaron Bentley
Use tree transform to emit upcoming change list
1400
    change_list = target_tree._iter_changes(working_tree,
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1401
        specific_files=specific_files, pb=pb)
2012.1.12 by Aaron Bentley
Use iter_changes for revert
1402
    if target_tree.inventory.root is None:
1403
        skip_root = True
1404
    else:
1405
        skip_root = False
1406
    basis_tree = None
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
1407
    try:
1408
        for id_num, (file_id, path, changed_content, versioned, parent, name,
1409
                kind, executable) in enumerate(change_list):
1410
            if skip_root and file_id[0] is not None and parent[0] is None:
1411
                continue
1412
            trans_id = tt.trans_id_file_id(file_id)
1413
            mode_id = None
1414
            if changed_content:
1415
                keep_content = False
1416
                if kind[0] == 'file' and (backups or kind[1] is None):
1417
                    wt_sha1 = working_tree.get_file_sha1(file_id)
1418
                    if merge_modified.get(file_id) != wt_sha1:
1419
                        # acquire the basis tree lazyily to prevent the expense
1420
                        # of accessing it when its not needed ? (Guessing, RBC,
1421
                        # 200702)
1422
                        if basis_tree is None:
1423
                            basis_tree = working_tree.basis_tree()
1424
                            basis_tree.lock_read()
1425
                        if file_id in basis_tree:
1426
                            if wt_sha1 != basis_tree.get_file_sha1(file_id):
1427
                                keep_content = True
1428
                        elif kind[1] is None and not versioned[1]:
2012.1.12 by Aaron Bentley
Use iter_changes for revert
1429
                            keep_content = True
2255.2.53 by Robert Collins
Teach TreeTransform to lock basis_trees if it acquires them, fixing revert on a dirstate working tree.
1430
                if kind[0] is not None:
1431
                    if not keep_content:
1432
                        tt.delete_contents(trans_id)
1433
                    elif kind[1] is not None:
1434
                        parent_trans_id = tt.trans_id_file_id(parent[0])
1435
                        by_parent = tt.by_parent()
1436
                        backup_name = _get_backup_name(name[0], by_parent,
1437
                                                       parent_trans_id, tt)
1438
                        tt.adjust_path(backup_name, parent_trans_id, trans_id)
1439
                        new_trans_id = tt.create_path(name[0], parent_trans_id)
1440
                        if versioned == (True, True):
1441
                            tt.unversion_file(trans_id)
1442
                            tt.version_file(file_id, new_trans_id)
1443
                        # New contents should have the same unix perms as old
1444
                        # contents
1445
                        mode_id = trans_id
1446
                        trans_id = new_trans_id
1447
                if kind[1] == 'directory':
1448
                    tt.create_directory(trans_id)
1449
                elif kind[1] == 'symlink':
1450
                    tt.create_symlink(target_tree.get_symlink_target(file_id),
1451
                                      trans_id)
1452
                elif kind[1] == 'file':
1453
                    tt.create_file(target_tree.get_file_lines(file_id),
1454
                                   trans_id, mode_id)
1455
                    # preserve the execute bit when backing up
1456
                    if keep_content and executable[0] == executable[1]:
1457
                        tt.set_executability(executable[1], trans_id)
1458
                else:
1459
                    assert kind[1] is None
1460
            if versioned == (False, True):
1461
                tt.version_file(file_id, trans_id)
1462
            if versioned == (True, False):
1463
                tt.unversion_file(trans_id)
1464
            if (name[1] is not None and 
1465
                (name[0] != name[1] or parent[0] != parent[1])):
1466
                tt.adjust_path(
1467
                    name[1], tt.trans_id_file_id(parent[1]), trans_id)
1468
            if executable[0] != executable[1] and kind[1] == "file":
1469
                tt.set_executability(executable[1], trans_id)
1470
    finally:
1471
        if basis_tree is not None:
1472
            basis_tree.unlock()
2012.1.12 by Aaron Bentley
Use iter_changes for revert
1473
1474
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1475
def resolve_conflicts(tt, pb=DummyProgress(), pass_func=None):
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
1476
    """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
1477
    if pass_func is None:
1478
        pass_func = conflict_pass
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
1479
    new_conflicts = set()
1534.9.1 by Aaron Bentley
Added progress bars to merge
1480
    try:
1481
        for n in range(10):
1482
            pb.update('Resolution pass', n+1, 10)
1483
            conflicts = tt.find_conflicts()
1484
            if len(conflicts) == 0:
1485
                return new_conflicts
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1486
            new_conflicts.update(pass_func(tt, conflicts))
1534.9.1 by Aaron Bentley
Added progress bars to merge
1487
        raise MalformedTransform(conflicts=conflicts)
1488
    finally:
1489
        pb.clear()
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
1490
1491
1492
def conflict_pass(tt, conflicts):
1534.7.157 by Aaron Bentley
Added more docs
1493
    """Resolve some classes of conflicts."""
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
1494
    new_conflicts = set()
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
1495
    for c_type, conflict in ((c[0], c) for c in conflicts):
1496
        if c_type == 'duplicate id':
1534.7.51 by Aaron Bentley
New approach to revert
1497
            tt.unversion_file(conflict[1])
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
1498
            new_conflicts.add((c_type, 'Unversioned existing file',
1499
                               conflict[1], conflict[2], ))
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
1500
        elif c_type == 'duplicate':
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
1501
            # files that were renamed take precedence
1502
            new_name = tt.final_name(conflict[1])+'.moved'
1503
            final_parent = tt.final_parent(conflict[1])
1504
            if tt.path_changed(conflict[1]):
1505
                tt.adjust_path(new_name, final_parent, conflict[2])
1534.7.171 by Aaron Bentley
Implemented stringifying filesystem conflicts
1506
                new_conflicts.add((c_type, 'Moved existing file to', 
1507
                                   conflict[2], conflict[1]))
1534.7.57 by Aaron Bentley
Enhanced conflict resolution.
1508
            else:
1509
                tt.adjust_path(new_name, final_parent, conflict[1])
1534.7.171 by Aaron Bentley
Implemented stringifying filesystem conflicts
1510
                new_conflicts.add((c_type, 'Moved existing file to', 
1511
                                  conflict[1], conflict[2]))
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
1512
        elif c_type == 'parent loop':
1513
            # break the loop by undoing one of the ops that caused the loop
1514
            cur = conflict[1]
1515
            while not tt.path_changed(cur):
1516
                cur = tt.final_parent(cur)
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
1517
            new_conflicts.add((c_type, 'Cancelled move', cur,
1518
                               tt.final_parent(cur),))
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
1519
            tt.adjust_path(tt.final_name(cur), tt.get_tree_parent(cur), cur)
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
1520
            
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
1521
        elif c_type == 'missing parent':
1534.7.128 by Aaron Bentley
Got missing contents test working
1522
            trans_id = conflict[1]
1523
            try:
1524
                tt.cancel_deletion(trans_id)
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
1525
                new_conflicts.add(('deleting parent', 'Not deleting', 
1526
                                   trans_id))
1534.7.128 by Aaron Bentley
Got missing contents test working
1527
            except KeyError:
1528
                tt.create_directory(trans_id)
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
1529
                new_conflicts.add((c_type, 'Created directory', trans_id))
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
1530
        elif c_type == 'unversioned parent':
1534.7.148 by Aaron Bentley
Handled the remaining file versioning case
1531
            tt.version_file(tt.inactive_file_id(conflict[1]), conflict[1])
1534.7.171 by Aaron Bentley
Implemented stringifying filesystem conflicts
1532
            new_conflicts.add((c_type, 'Versioned directory', conflict[1]))
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
1533
    return new_conflicts
1534
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
1535
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
1536
def cook_conflicts(raw_conflicts, tt):
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
1537
    """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
1538
    from bzrlib.conflicts import Conflict
1539
    conflict_iter = iter_cook_conflicts(raw_conflicts, tt)
1540
    return sorted(conflict_iter, key=Conflict.sort_key)
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
1541
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
1542
1543
def iter_cook_conflicts(raw_conflicts, tt):
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
1544
    from bzrlib.conflicts import Conflict
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
1545
    fp = FinalPaths(tt)
1534.7.169 by Aaron Bentley
Add filesystem/inventory conflicts to conflict output
1546
    for conflict in raw_conflicts:
1547
        c_type = conflict[0]
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
1548
        action = conflict[1]
1549
        modified_path = fp.get_path(conflict[2])
1550
        modified_id = tt.final_file_id(conflict[2])
1551
        if len(conflict) == 3:
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
1552
            yield Conflict.factory(c_type, action=action, path=modified_path,
1553
                                     file_id=modified_id)
1554
             
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
1555
        else:
1556
            conflicting_path = fp.get_path(conflict[3])
1557
            conflicting_id = tt.final_file_id(conflict[3])
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
1558
            yield Conflict.factory(c_type, action=action, path=modified_path,
1559
                                   file_id=modified_id, 
1560
                                   conflict_path=conflicting_path,
1561
                                   conflict_file_id=conflicting_id)