~bzr-pqm/bzr/bzr.dev

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