/brz/remove-bazaar

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