~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transform.py

  • Committer: Martin Pool
  • Date: 2010-06-02 05:03:31 UTC
  • mto: This revision was merged to the branch mainline in revision 5279.
  • Revision ID: mbp@canonical.com-20100602050331-n2p1qt8hfsahspnv
Correct more sloppy use of the term 'Linux'

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2006-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
import os
18
18
import errno
19
 
from stat import S_ISREG
 
19
from stat import S_ISREG, S_IEXEC
 
20
import time
20
21
 
21
22
from bzrlib.lazy_import import lazy_import
22
23
lazy_import(globals(), """
23
24
from bzrlib import (
 
25
    annotate,
 
26
    bencode,
24
27
    bzrdir,
 
28
    commit,
25
29
    delta,
26
30
    errors,
27
 
    inventory
 
31
    inventory,
 
32
    multiparent,
 
33
    osutils,
 
34
    revision as _mod_revision,
 
35
    ui,
28
36
    )
29
37
""")
30
38
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
31
 
                           ReusingTransform, NotVersionedError, CantMoveRoot,
32
 
                           ExistingLimbo, ImmortalLimbo, NoFinalPath)
 
39
                           ReusingTransform, CantMoveRoot,
 
40
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
 
41
                           UnableCreateSymlink)
 
42
from bzrlib.filters import filtered_output_bytes, ContentFilterContext
33
43
from bzrlib.inventory import InventoryEntry
34
 
from bzrlib.osutils import (file_kind, supports_executable, pathjoin, lexists,
35
 
                            delete_any)
36
 
from bzrlib.progress import DummyProgress, ProgressPhase
 
44
from bzrlib.osutils import (
 
45
    delete_any,
 
46
    file_kind,
 
47
    has_symlinks,
 
48
    lexists,
 
49
    pathjoin,
 
50
    sha_file,
 
51
    splitpath,
 
52
    supports_executable,
 
53
)
 
54
from bzrlib.progress import ProgressPhase
37
55
from bzrlib.symbol_versioning import (
38
56
        deprecated_function,
39
 
        zero_fifteen,
40
 
        zero_ninety,
 
57
        deprecated_in,
41
58
        )
42
59
from bzrlib.trace import mutter, warning
43
60
from bzrlib import tree
61
78
        self.rename_count = rename_count
62
79
 
63
80
 
64
 
class TreeTransform(object):
65
 
    """Represent a tree transformation.
66
 
    
67
 
    This object is designed to support incremental generation of the transform,
68
 
    in any order.
69
 
 
70
 
    However, it gives optimum performance when parent directories are created
71
 
    before their contents.  The transform is then able to put child files
72
 
    directly in their parent directory, avoiding later renames.
73
 
    
74
 
    It is easy to produce malformed transforms, but they are generally
75
 
    harmless.  Attempting to apply a malformed transform will cause an
76
 
    exception to be raised before any modifications are made to the tree.  
77
 
 
78
 
    Many kinds of malformed transforms can be corrected with the 
79
 
    resolve_conflicts function.  The remaining ones indicate programming error,
80
 
    such as trying to create a file with no path.
81
 
 
82
 
    Two sets of file creation methods are supplied.  Convenience methods are:
83
 
     * new_file
84
 
     * new_directory
85
 
     * new_symlink
86
 
 
87
 
    These are composed of the low-level methods:
88
 
     * create_path
89
 
     * create_file or create_directory or create_symlink
90
 
     * version_file
91
 
     * set_executability
92
 
    """
93
 
    def __init__(self, tree, pb=DummyProgress()):
94
 
        """Note: a tree_write lock is taken on the tree.
95
 
        
96
 
        Use TreeTransform.finalize() to release the lock (can be omitted if
97
 
        TreeTransform.apply() called).
 
81
class TreeTransformBase(object):
 
82
    """The base class for TreeTransform and its kin."""
 
83
 
 
84
    def __init__(self, tree, pb=None,
 
85
                 case_sensitive=True):
 
86
        """Constructor.
 
87
 
 
88
        :param tree: The tree that will be transformed, but not necessarily
 
89
            the output tree.
 
90
        :param pb: ignored
 
91
        :param case_sensitive: If True, the target of the transform is
 
92
            case sensitive, not just case preserving.
98
93
        """
99
94
        object.__init__(self)
100
95
        self._tree = tree
101
 
        self._tree.lock_tree_write()
102
 
        try:
103
 
            control_files = self._tree._control_files
104
 
            self._limbodir = urlutils.local_path_from_url(
105
 
                control_files.controlfilename('limbo'))
106
 
            try:
107
 
                os.mkdir(self._limbodir)
108
 
            except OSError, e:
109
 
                if e.errno == errno.EEXIST:
110
 
                    raise ExistingLimbo(self._limbodir)
111
 
            self._deletiondir = urlutils.local_path_from_url(
112
 
                control_files.controlfilename('pending-deletion'))
113
 
            try:
114
 
                os.mkdir(self._deletiondir)
115
 
            except OSError, e:
116
 
                if e.errno == errno.EEXIST:
117
 
                    raise errors.ExistingPendingDeletion(self._deletiondir)
118
 
 
119
 
        except: 
120
 
            self._tree.unlock()
121
 
            raise
122
 
 
123
96
        self._id_number = 0
 
97
        # mapping of trans_id -> new basename
124
98
        self._new_name = {}
 
99
        # mapping of trans_id -> new parent trans_id
125
100
        self._new_parent = {}
 
101
        # mapping of trans_id with new contents -> new file_kind
126
102
        self._new_contents = {}
127
 
        # A mapping of transform ids to their limbo filename
128
 
        self._limbo_files = {}
129
 
        # A mapping of transform ids to a set of the transform ids of children
130
 
        # that their limbo directory has
131
 
        self._limbo_children = {}
132
 
        # Map transform ids to maps of child filename to child transform id
133
 
        self._limbo_children_names = {}
134
 
        # List of transform ids that need to be renamed from limbo into place
135
 
        self._needs_rename = set()
 
103
        # Set of trans_ids whose contents will be removed
136
104
        self._removed_contents = set()
 
105
        # Mapping of trans_id -> new execute-bit value
137
106
        self._new_executability = {}
 
107
        # Mapping of trans_id -> new tree-reference value
138
108
        self._new_reference_revision = {}
 
109
        # Mapping of trans_id -> new file_id
139
110
        self._new_id = {}
 
111
        # Mapping of old file-id -> trans_id
140
112
        self._non_present_ids = {}
 
113
        # Mapping of new file_id -> trans_id
141
114
        self._r_new_id = {}
 
115
        # Set of trans_ids that will be removed
142
116
        self._removed_id = set()
 
117
        # Mapping of path in old tree -> trans_id
143
118
        self._tree_path_ids = {}
 
119
        # Mapping trans_id -> path in old tree
144
120
        self._tree_id_paths = {}
145
 
        # Cache of realpath results, to speed up canonical_path
146
 
        self._realpaths = {}
147
 
        # Cache of relpath results, to speed up canonical_path
148
 
        self._relpaths = {}
149
 
        self._new_root = self.trans_id_tree_file_id(tree.get_root_id())
150
 
        self.__done = False
 
121
        # The trans_id that will be used as the tree root
 
122
        root_id = tree.get_root_id()
 
123
        if root_id is not None:
 
124
            self._new_root = self.trans_id_tree_file_id(root_id)
 
125
        else:
 
126
            self._new_root = None
 
127
        # Indictor of whether the transform has been applied
 
128
        self._done = False
 
129
        # A progress bar
151
130
        self._pb = pb
 
131
        # Whether the target is case sensitive
 
132
        self._case_sensitive_target = case_sensitive
 
133
        # A counter of how many files have been renamed
152
134
        self.rename_count = 0
153
135
 
 
136
    def finalize(self):
 
137
        """Release the working tree lock, if held.
 
138
 
 
139
        This is required if apply has not been invoked, but can be invoked
 
140
        even after apply.
 
141
        """
 
142
        if self._tree is None:
 
143
            return
 
144
        self._tree.unlock()
 
145
        self._tree = None
 
146
 
154
147
    def __get_root(self):
155
148
        return self._new_root
156
149
 
157
150
    root = property(__get_root)
158
151
 
159
 
    def finalize(self):
160
 
        """Release the working tree lock, if held, clean up limbo dir.
161
 
 
162
 
        This is required if apply has not been invoked, but can be invoked
163
 
        even after apply.
164
 
        """
165
 
        if self._tree is None:
166
 
            return
167
 
        try:
168
 
            entries = [(self._limbo_name(t), t, k) for t, k in
169
 
                       self._new_contents.iteritems()]
170
 
            entries.sort(reverse=True)
171
 
            for path, trans_id, kind in entries:
172
 
                if kind == "directory":
173
 
                    os.rmdir(path)
174
 
                else:
175
 
                    os.unlink(path)
176
 
            try:
177
 
                os.rmdir(self._limbodir)
178
 
            except OSError:
179
 
                # We don't especially care *why* the dir is immortal.
180
 
                raise ImmortalLimbo(self._limbodir)
181
 
            try:
182
 
                os.rmdir(self._deletiondir)
183
 
            except OSError:
184
 
                raise errors.ImmortalPendingDeletion(self._deletiondir)
185
 
        finally:
186
 
            self._tree.unlock()
187
 
            self._tree = None
188
 
 
189
152
    def _assign_id(self):
190
153
        """Produce a new tranform id"""
191
154
        new_id = "new-%s" % self._id_number
201
164
 
202
165
    def adjust_path(self, name, parent, trans_id):
203
166
        """Change the path that is assigned to a transaction id."""
 
167
        if parent is None:
 
168
            raise ValueError("Parent trans-id may not be None")
204
169
        if trans_id == self._new_root:
205
170
            raise CantMoveRoot
206
 
        previous_parent = self._new_parent.get(trans_id)
207
 
        previous_name = self._new_name.get(trans_id)
208
171
        self._new_name[trans_id] = name
209
172
        self._new_parent[trans_id] = parent
210
 
        if (trans_id in self._limbo_files and
211
 
            trans_id not in self._needs_rename):
212
 
            self._rename_in_limbo([trans_id])
213
 
            self._limbo_children[previous_parent].remove(trans_id)
214
 
            del self._limbo_children_names[previous_parent][previous_name]
215
 
 
216
 
    def _rename_in_limbo(self, trans_ids):
217
 
        """Fix limbo names so that the right final path is produced.
218
 
 
219
 
        This means we outsmarted ourselves-- we tried to avoid renaming
220
 
        these files later by creating them with their final names in their
221
 
        final parents.  But now the previous name or parent is no longer
222
 
        suitable, so we have to rename them.
223
 
 
224
 
        Even for trans_ids that have no new contents, we must remove their
225
 
        entries from _limbo_files, because they are now stale.
226
 
        """
227
 
        for trans_id in trans_ids:
228
 
            old_path = self._limbo_files.pop(trans_id)
229
 
            if trans_id not in self._new_contents:
230
 
                continue
231
 
            new_path = self._limbo_name(trans_id)
232
 
            os.rename(old_path, new_path)
233
173
 
234
174
    def adjust_root_path(self, name, parent):
235
175
        """Emulate moving the root by moving all children, instead.
236
 
        
 
176
 
237
177
        We do this by undoing the association of root's transaction id with the
238
178
        current tree.  This allows us to create a new directory with that
239
 
        transaction id.  We unversion the root directory and version the 
 
179
        transaction id.  We unversion the root directory and version the
240
180
        physically new directory, and hope someone versions the tree root
241
181
        later.
242
182
        """
245
185
        # force moving all children of root
246
186
        for child_id in self.iter_tree_children(old_root):
247
187
            if child_id != parent:
248
 
                self.adjust_path(self.final_name(child_id), 
 
188
                self.adjust_path(self.final_name(child_id),
249
189
                                 self.final_parent(child_id), child_id)
250
190
            file_id = self.final_file_id(child_id)
251
191
            if file_id is not None:
252
192
                self.unversion_file(child_id)
253
193
            self.version_file(file_id, child_id)
254
 
        
 
194
 
255
195
        # the physical root needs a new transaction id
256
196
        self._tree_path_ids.pop("")
257
197
        self._tree_id_paths.pop(old_root)
263
203
        self.version_file(old_root_file_id, old_root)
264
204
        self.unversion_file(self._new_root)
265
205
 
 
206
    def fixup_new_roots(self):
 
207
        """Reinterpret requests to change the root directory
 
208
 
 
209
        Instead of creating a root directory, or moving an existing directory,
 
210
        all the attributes and children of the new root are applied to the
 
211
        existing root directory.
 
212
 
 
213
        This means that the old root trans-id becomes obsolete, so it is
 
214
        recommended only to invoke this after the root trans-id has become
 
215
        irrelevant.
 
216
        """
 
217
        new_roots = [k for k, v in self._new_parent.iteritems() if v is
 
218
                     ROOT_PARENT]
 
219
        if len(new_roots) < 1:
 
220
            return
 
221
        if len(new_roots) != 1:
 
222
            raise ValueError('A tree cannot have two roots!')
 
223
        if self._new_root is None:
 
224
            self._new_root = new_roots[0]
 
225
            return
 
226
        old_new_root = new_roots[0]
 
227
        # TODO: What to do if a old_new_root is present, but self._new_root is
 
228
        #       not listed as being removed? This code explicitly unversions
 
229
        #       the old root and versions it with the new file_id. Though that
 
230
        #       seems like an incomplete delta
 
231
 
 
232
        # unversion the new root's directory.
 
233
        file_id = self.final_file_id(old_new_root)
 
234
        if old_new_root in self._new_id:
 
235
            self.cancel_versioning(old_new_root)
 
236
        else:
 
237
            self.unversion_file(old_new_root)
 
238
        # if, at this stage, root still has an old file_id, zap it so we can
 
239
        # stick a new one in.
 
240
        if (self.tree_file_id(self._new_root) is not None and
 
241
            self._new_root not in self._removed_id):
 
242
            self.unversion_file(self._new_root)
 
243
        self.version_file(file_id, self._new_root)
 
244
 
 
245
        # Now move children of new root into old root directory.
 
246
        # Ensure all children are registered with the transaction, but don't
 
247
        # use directly-- some tree children have new parents
 
248
        list(self.iter_tree_children(old_new_root))
 
249
        # Move all children of new root into old root directory.
 
250
        for child in self.by_parent().get(old_new_root, []):
 
251
            self.adjust_path(self.final_name(child), self._new_root, child)
 
252
 
 
253
        # Ensure old_new_root has no directory.
 
254
        if old_new_root in self._new_contents:
 
255
            self.cancel_creation(old_new_root)
 
256
        else:
 
257
            self.delete_contents(old_new_root)
 
258
 
 
259
        # prevent deletion of root directory.
 
260
        if self._new_root in self._removed_contents:
 
261
            self.cancel_deletion(self._new_root)
 
262
 
 
263
        # destroy path info for old_new_root.
 
264
        del self._new_parent[old_new_root]
 
265
        del self._new_name[old_new_root]
 
266
 
266
267
    def trans_id_tree_file_id(self, inventory_id):
267
268
        """Determine the transaction id of a working tree file.
268
 
        
 
269
 
269
270
        This reflects only files that already exist, not ones that will be
270
271
        added by transactions.
271
272
        """
272
 
        path = self._tree.inventory.id2path(inventory_id)
 
273
        if inventory_id is None:
 
274
            raise ValueError('None is not a valid file id')
 
275
        path = self._tree.id2path(inventory_id)
273
276
        return self.trans_id_tree_path(path)
274
277
 
275
278
    def trans_id_file_id(self, file_id):
278
281
        a transaction has been unversioned, it is deliberately still returned.
279
282
        (this will likely lead to an unversioned parent conflict.)
280
283
        """
 
284
        if file_id is None:
 
285
            raise ValueError('None is not a valid file id')
281
286
        if file_id in self._r_new_id and self._r_new_id[file_id] is not None:
282
287
            return self._r_new_id[file_id]
283
 
        elif file_id in self._tree.inventory:
284
 
            return self.trans_id_tree_file_id(file_id)
285
 
        elif file_id in self._non_present_ids:
286
 
            return self._non_present_ids[file_id]
287
 
        else:
288
 
            trans_id = self._assign_id()
289
 
            self._non_present_ids[file_id] = trans_id
290
 
            return trans_id
291
 
 
292
 
    def canonical_path(self, path):
293
 
        """Get the canonical tree-relative path"""
294
 
        # don't follow final symlinks
295
 
        abs = self._tree.abspath(path)
296
 
        if abs in self._relpaths:
297
 
            return self._relpaths[abs]
298
 
        dirname, basename = os.path.split(abs)
299
 
        if dirname not in self._realpaths:
300
 
            self._realpaths[dirname] = os.path.realpath(dirname)
301
 
        dirname = self._realpaths[dirname]
302
 
        abs = pathjoin(dirname, basename)
303
 
        if dirname in self._relpaths:
304
 
            relpath = pathjoin(self._relpaths[dirname], basename)
305
 
            relpath = relpath.rstrip('/\\')
306
 
        else:
307
 
            relpath = self._tree.relpath(abs)
308
 
        self._relpaths[abs] = relpath
309
 
        return relpath
 
288
        else:
 
289
            try:
 
290
                self._tree.iter_entries_by_dir([file_id]).next()
 
291
            except StopIteration:
 
292
                if file_id in self._non_present_ids:
 
293
                    return self._non_present_ids[file_id]
 
294
                else:
 
295
                    trans_id = self._assign_id()
 
296
                    self._non_present_ids[file_id] = trans_id
 
297
                    return trans_id
 
298
            else:
 
299
                return self.trans_id_tree_file_id(file_id)
310
300
 
311
301
    def trans_id_tree_path(self, path):
312
302
        """Determine (and maybe set) the transaction ID for a tree path."""
323
313
            return ROOT_PARENT
324
314
        return self.trans_id_tree_path(os.path.dirname(path))
325
315
 
326
 
    def create_file(self, contents, trans_id, mode_id=None):
327
 
        """Schedule creation of a new file.
328
 
 
329
 
        See also new_file.
330
 
        
331
 
        Contents is an iterator of strings, all of which will be written
332
 
        to the target destination.
333
 
 
334
 
        New file takes the permissions of any existing file with that id,
335
 
        unless mode_id is specified.
336
 
        """
337
 
        name = self._limbo_name(trans_id)
338
 
        f = open(name, 'wb')
339
 
        try:
340
 
            try:
341
 
                unique_add(self._new_contents, trans_id, 'file')
342
 
            except:
343
 
                # Clean up the file, it never got registered so
344
 
                # TreeTransform.finalize() won't clean it up.
345
 
                f.close()
346
 
                os.unlink(name)
347
 
                raise
348
 
 
349
 
            f.writelines(contents)
350
 
        finally:
351
 
            f.close()
352
 
        self._set_mode(trans_id, mode_id, S_ISREG)
353
 
 
354
 
    def _set_mode(self, trans_id, mode_id, typefunc):
355
 
        """Set the mode of new file contents.
356
 
        The mode_id is the existing file to get the mode from (often the same
357
 
        as trans_id).  The operation is only performed if there's a mode match
358
 
        according to typefunc.
359
 
        """
360
 
        if mode_id is None:
361
 
            mode_id = trans_id
362
 
        try:
363
 
            old_path = self._tree_id_paths[mode_id]
364
 
        except KeyError:
365
 
            return
366
 
        try:
367
 
            mode = os.stat(self._tree.abspath(old_path)).st_mode
368
 
        except OSError, e:
369
 
            if e.errno == errno.ENOENT:
370
 
                return
371
 
            else:
372
 
                raise
373
 
        if typefunc(mode):
374
 
            os.chmod(self._limbo_name(trans_id), mode)
375
 
 
376
 
    def create_directory(self, trans_id):
377
 
        """Schedule creation of a new directory.
378
 
        
379
 
        See also new_directory.
380
 
        """
381
 
        os.mkdir(self._limbo_name(trans_id))
382
 
        unique_add(self._new_contents, trans_id, 'directory')
383
 
 
384
 
    def create_symlink(self, target, trans_id):
385
 
        """Schedule creation of a new symbolic link.
386
 
 
387
 
        target is a bytestring.
388
 
        See also new_symlink.
389
 
        """
390
 
        os.symlink(target, self._limbo_name(trans_id))
391
 
        unique_add(self._new_contents, trans_id, 'symlink')
392
 
 
393
 
    def cancel_creation(self, trans_id):
394
 
        """Cancel the creation of new file contents."""
395
 
        del self._new_contents[trans_id]
396
 
        children = self._limbo_children.get(trans_id)
397
 
        # if this is a limbo directory with children, move them before removing
398
 
        # the directory
399
 
        if children is not None:
400
 
            self._rename_in_limbo(children)
401
 
            del self._limbo_children[trans_id]
402
 
            del self._limbo_children_names[trans_id]
403
 
        delete_any(self._limbo_name(trans_id))
404
 
 
405
316
    def delete_contents(self, trans_id):
406
317
        """Schedule the contents of a path entry for deletion"""
 
318
        # Ensure that the object exists in the WorkingTree, this will raise an
 
319
        # exception if there is a problem
407
320
        self.tree_kind(trans_id)
408
321
        self._removed_contents.add(trans_id)
409
322
 
435
348
 
436
349
    def version_file(self, file_id, trans_id):
437
350
        """Schedule a file to become versioned."""
438
 
        assert file_id is not None
 
351
        if file_id is None:
 
352
            raise ValueError()
439
353
        unique_add(self._new_id, trans_id, file_id)
440
354
        unique_add(self._r_new_id, file_id, trans_id)
441
355
 
445
359
        del self._new_id[trans_id]
446
360
        del self._r_new_id[file_id]
447
361
 
448
 
    def new_paths(self):
449
 
        """Determine the paths of all new and changed files"""
450
 
        new_ids = set()
451
 
        fp = FinalPaths(self)
452
 
        for id_set in (self._new_name, self._new_parent, self._new_contents,
453
 
                       self._new_id, self._new_executability):
454
 
            new_ids.update(id_set)
455
 
        new_paths = [(fp.get_path(t), t) for t in new_ids]
456
 
        new_paths.sort()
457
 
        return new_paths
458
 
 
459
 
    def tree_kind(self, trans_id):
460
 
        """Determine the file kind in the working tree.
461
 
 
462
 
        Raises NoSuchFile if the file does not exist
 
362
    def new_paths(self, filesystem_only=False):
 
363
        """Determine the paths of all new and changed files.
 
364
 
 
365
        :param filesystem_only: if True, only calculate values for files
 
366
            that require renames or execute bit changes.
463
367
        """
464
 
        path = self._tree_id_paths.get(trans_id)
465
 
        if path is None:
466
 
            raise NoSuchFile(None)
467
 
        try:
468
 
            return file_kind(self._tree.abspath(path))
469
 
        except OSError, e:
470
 
            if e.errno != errno.ENOENT:
471
 
                raise
472
 
            else:
473
 
                raise NoSuchFile(path)
 
368
        new_ids = set()
 
369
        if filesystem_only:
 
370
            stale_ids = self._needs_rename.difference(self._new_name)
 
371
            stale_ids.difference_update(self._new_parent)
 
372
            stale_ids.difference_update(self._new_contents)
 
373
            stale_ids.difference_update(self._new_id)
 
374
            needs_rename = self._needs_rename.difference(stale_ids)
 
375
            id_sets = (needs_rename, self._new_executability)
 
376
        else:
 
377
            id_sets = (self._new_name, self._new_parent, self._new_contents,
 
378
                       self._new_id, self._new_executability)
 
379
        for id_set in id_sets:
 
380
            new_ids.update(id_set)
 
381
        return sorted(FinalPaths(self).get_paths(new_ids))
 
382
 
 
383
    def _inventory_altered(self):
 
384
        """Get the trans_ids and paths of files needing new inv entries."""
 
385
        new_ids = set()
 
386
        for id_set in [self._new_name, self._new_parent, self._new_id,
 
387
                       self._new_executability]:
 
388
            new_ids.update(id_set)
 
389
        changed_kind = set(self._removed_contents)
 
390
        changed_kind.intersection_update(self._new_contents)
 
391
        changed_kind.difference_update(new_ids)
 
392
        changed_kind = (t for t in changed_kind if self.tree_kind(t) !=
 
393
                        self.final_kind(t))
 
394
        new_ids.update(changed_kind)
 
395
        return sorted(FinalPaths(self).get_paths(new_ids))
474
396
 
475
397
    def final_kind(self, trans_id):
476
398
        """Determine the final file kind, after any changes applied.
477
 
        
 
399
 
478
400
        Raises NoSuchFile if the file does not exist/has no contents.
479
401
        (It is conceivable that a path would be created without the
480
402
        corresponding contents insertion command)
495
417
            return None
496
418
        # the file is old; the old id is still valid
497
419
        if self._new_root == trans_id:
498
 
            return self._tree.inventory.root.file_id
499
 
        return self._tree.inventory.path2id(path)
 
420
            return self._tree.get_root_id()
 
421
        return self._tree.path2id(path)
500
422
 
501
423
    def final_file_id(self, trans_id):
502
424
        """Determine the file id after any changes are applied, or None.
503
 
        
 
425
 
504
426
        None indicates that the file will not be versioned after changes are
505
427
        applied.
506
428
        """
507
429
        try:
508
 
            # there is a new id for this file
509
 
            assert self._new_id[trans_id] is not None
510
430
            return self._new_id[trans_id]
511
431
        except KeyError:
512
432
            if trans_id in self._removed_id:
547
467
 
548
468
    def by_parent(self):
549
469
        """Return a map of parent: children for known parents.
550
 
        
 
470
 
551
471
        Only new paths and parents of tree files with assigned ids are used.
552
472
        """
553
473
        by_parent = {}
554
474
        items = list(self._new_parent.iteritems())
555
 
        items.extend((t, self.final_parent(t)) for t in 
 
475
        items.extend((t, self.final_parent(t)) for t in
556
476
                      self._tree_id_paths.keys())
557
477
        for trans_id, parent_id in items:
558
478
            if parent_id not in by_parent:
569
489
 
570
490
    def find_conflicts(self):
571
491
        """Find any violations of inventory or filesystem invariants"""
572
 
        if self.__done is True:
 
492
        if self._done is True:
573
493
            raise ReusingTransform()
574
494
        conflicts = []
575
495
        # ensure all children of all existent parents are known
586
506
        conflicts.extend(self._overwrite_conflicts())
587
507
        return conflicts
588
508
 
 
509
    def _check_malformed(self):
 
510
        conflicts = self.find_conflicts()
 
511
        if len(conflicts) != 0:
 
512
            raise MalformedTransform(conflicts=conflicts)
 
513
 
589
514
    def _add_tree_children(self):
590
515
        """Add all the children of all active parents to the known paths.
591
516
 
593
518
        removed.  This is a necessary first step in detecting conflicts.
594
519
        """
595
520
        parents = self.by_parent().keys()
596
 
        parents.extend([t for t in self._removed_contents if 
 
521
        parents.extend([t for t in self._removed_contents if
597
522
                        self.tree_kind(t) == 'directory'])
598
523
        for trans_id in self._removed_id:
599
524
            file_id = self.tree_file_id(trans_id)
600
 
            if self._tree.inventory[file_id].kind == 'directory':
 
525
            if file_id is not None:
 
526
                if self._tree.inventory[file_id].kind == 'directory':
 
527
                    parents.append(trans_id)
 
528
            elif self.tree_kind(trans_id) == 'directory':
601
529
                parents.append(trans_id)
602
530
 
603
531
        for parent_id in parents:
604
532
            # ensure that all children are registered with the transaction
605
533
            list(self.iter_tree_children(parent_id))
606
534
 
607
 
    def iter_tree_children(self, parent_id):
608
 
        """Iterate through the entry's tree children, if any"""
609
 
        try:
610
 
            path = self._tree_id_paths[parent_id]
611
 
        except KeyError:
612
 
            return
613
 
        try:
614
 
            children = os.listdir(self._tree.abspath(path))
615
 
        except OSError, e:
616
 
            if e.errno != errno.ENOENT and e.errno != errno.ESRCH:
617
 
                raise
618
 
            return
619
 
            
620
 
        for child in children:
621
 
            childpath = joinpath(path, child)
622
 
            if self._tree.is_control_filename(childpath):
623
 
                continue
624
 
            yield self.trans_id_tree_path(childpath)
625
 
 
626
535
    def has_named_child(self, by_parent, parent_id, name):
627
536
        try:
628
537
            children = by_parent[parent_id]
682
591
 
683
592
    def _improper_versioning(self):
684
593
        """Cannot version a file with no contents, or a bad type.
685
 
        
 
594
 
686
595
        However, existing entries with no contents are okay.
687
596
        """
688
597
        conflicts = []
698
607
 
699
608
    def _executability_conflicts(self):
700
609
        """Check for bad executability changes.
701
 
        
 
610
 
702
611
        Only versioned files may have their executability set, because
703
612
        1. only versioned entries can have executability under windows
704
613
        2. only files can be executable.  (The execute bit on a directory
737
646
            return conflicts
738
647
        for children in by_parent.itervalues():
739
648
            name_ids = [(self.final_name(t), t) for t in children]
 
649
            if not self._case_sensitive_target:
 
650
                name_ids = [(n.lower(), t) for n, t in name_ids]
740
651
            name_ids.sort()
741
652
            last_name = None
742
653
            last_trans_id = None
760
671
        conflicts = []
761
672
        removed_tree_ids = set((self.tree_file_id(trans_id) for trans_id in
762
673
                                self._removed_id))
763
 
        active_tree_ids = set((f for f in self._tree.inventory if
764
 
                               f not in removed_tree_ids))
 
674
        all_ids = self._tree.all_file_ids()
 
675
        active_tree_ids = all_ids.difference(removed_tree_ids)
765
676
        for trans_id, file_id in self._new_id.iteritems():
766
677
            if file_id in active_tree_ids:
767
678
                old_trans_id = self.trans_id_tree_file_id(file_id)
800
711
                continue
801
712
            return True
802
713
        return False
803
 
            
804
 
    def apply(self, no_conflicts=False, _mover=None):
805
 
        """Apply all changes to the inventory and filesystem.
806
 
        
807
 
        If filesystem or inventory conflicts are present, MalformedTransform
808
 
        will be thrown.
809
 
 
810
 
        If apply succeeds, finalize is not necessary.
811
 
 
812
 
        :param no_conflicts: if True, the caller guarantees there are no
813
 
            conflicts, so no check is made.
814
 
        :param _mover: Supply an alternate FileMover, for testing
815
 
        """
816
 
        if not no_conflicts:
817
 
            conflicts = self.find_conflicts()
818
 
            if len(conflicts) != 0:
819
 
                raise MalformedTransform(conflicts=conflicts)
820
 
        inv = self._tree.inventory
821
 
        inventory_delta = []
822
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
823
 
        try:
824
 
            if _mover is None:
825
 
                mover = _FileMover()
826
 
            else:
827
 
                mover = _mover
828
 
            try:
829
 
                child_pb.update('Apply phase', 0, 2)
830
 
                self._apply_removals(inv, inventory_delta, mover)
831
 
                child_pb.update('Apply phase', 1, 2)
832
 
                modified_paths = self._apply_insertions(inv, inventory_delta,
833
 
                                                        mover)
834
 
            except:
835
 
                mover.rollback()
836
 
                raise
837
 
            else:
838
 
                mover.apply_deletions()
839
 
        finally:
840
 
            child_pb.finished()
841
 
        self._tree.apply_inventory_delta(inventory_delta)
842
 
        self.__done = True
843
 
        self.finalize()
844
 
        return _TransformResults(modified_paths, self.rename_count)
845
 
 
846
 
    def _limbo_name(self, trans_id):
847
 
        """Generate the limbo name of a file"""
848
 
        limbo_name = self._limbo_files.get(trans_id)
849
 
        if limbo_name is not None:
850
 
            return limbo_name
851
 
        parent = self._new_parent.get(trans_id)
852
 
        # if the parent directory is already in limbo (e.g. when building a
853
 
        # tree), choose a limbo name inside the parent, to reduce further
854
 
        # renames.
855
 
        use_direct_path = False
856
 
        if self._new_contents.get(parent) == 'directory':
857
 
            filename = self._new_name.get(trans_id)
858
 
            if filename is not None:
859
 
                if parent not in self._limbo_children:
860
 
                    self._limbo_children[parent] = set()
861
 
                    self._limbo_children_names[parent] = {}
862
 
                    use_direct_path = True
863
 
                # the direct path can only be used if no other file has
864
 
                # already taken this pathname, i.e. if the name is unused, or
865
 
                # if it is already associated with this trans_id.
866
 
                elif (self._limbo_children_names[parent].get(filename)
867
 
                      in (trans_id, None)):
868
 
                    use_direct_path = True
869
 
        if use_direct_path:
870
 
            limbo_name = pathjoin(self._limbo_files[parent], filename)
871
 
            self._limbo_children[parent].add(trans_id)
872
 
            self._limbo_children_names[parent][filename] = trans_id
873
 
        else:
874
 
            limbo_name = pathjoin(self._limbodir, trans_id)
875
 
            self._needs_rename.add(trans_id)
876
 
        self._limbo_files[trans_id] = limbo_name
877
 
        return limbo_name
878
 
 
879
 
    def _apply_removals(self, inv, inventory_delta, mover):
880
 
        """Perform tree operations that remove directory/inventory names.
881
 
        
882
 
        That is, delete files that are to be deleted, and put any files that
883
 
        need renaming into limbo.  This must be done in strict child-to-parent
884
 
        order.
885
 
        """
886
 
        tree_paths = list(self._tree_path_ids.iteritems())
887
 
        tree_paths.sort(reverse=True)
888
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
889
 
        try:
890
 
            for num, data in enumerate(tree_paths):
891
 
                path, trans_id = data
892
 
                child_pb.update('removing file', num, len(tree_paths))
893
 
                full_path = self._tree.abspath(path)
894
 
                if trans_id in self._removed_contents:
895
 
                    mover.pre_delete(full_path, os.path.join(self._deletiondir,
896
 
                                     trans_id))
897
 
                elif trans_id in self._new_name or trans_id in \
898
 
                    self._new_parent:
899
 
                    try:
900
 
                        mover.rename(full_path, self._limbo_name(trans_id))
901
 
                    except OSError, e:
902
 
                        if e.errno != errno.ENOENT:
903
 
                            raise
904
 
                    else:
905
 
                        self.rename_count += 1
906
 
                if trans_id in self._removed_id:
907
 
                    if trans_id == self._new_root:
908
 
                        file_id = self._tree.inventory.root.file_id
909
 
                    else:
910
 
                        file_id = self.tree_file_id(trans_id)
911
 
                    assert file_id is not None
912
 
                    inventory_delta.append((path, None, file_id, None))
913
 
        finally:
914
 
            child_pb.finished()
915
 
 
916
 
    def _apply_insertions(self, inv, inventory_delta, mover):
917
 
        """Perform tree operations that insert directory/inventory names.
918
 
        
919
 
        That is, create any files that need to be created, and restore from
920
 
        limbo any files that needed renaming.  This must be done in strict
921
 
        parent-to-child order.
922
 
        """
923
 
        new_paths = self.new_paths()
924
 
        modified_paths = []
925
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
926
 
        try:
927
 
            for num, (path, trans_id) in enumerate(new_paths):
928
 
                new_entry = None
929
 
                child_pb.update('adding file', num, len(new_paths))
930
 
                try:
931
 
                    kind = self._new_contents[trans_id]
932
 
                except KeyError:
933
 
                    kind = contents = None
934
 
                if trans_id in self._new_contents or \
935
 
                    self.path_changed(trans_id):
936
 
                    full_path = self._tree.abspath(path)
937
 
                    if trans_id in self._needs_rename:
938
 
                        try:
939
 
                            mover.rename(self._limbo_name(trans_id), full_path)
940
 
                        except OSError, e:
941
 
                            # We may be renaming a dangling inventory id
942
 
                            if e.errno != errno.ENOENT:
943
 
                                raise
944
 
                        else:
945
 
                            self.rename_count += 1
946
 
                    if trans_id in self._new_contents:
947
 
                        modified_paths.append(full_path)
948
 
                        del self._new_contents[trans_id]
949
 
 
950
 
                if trans_id in self._new_id:
951
 
                    if kind is None:
952
 
                        kind = file_kind(self._tree.abspath(path))
953
 
                    if trans_id in self._new_reference_revision:
954
 
                        new_entry = inventory.TreeReference(
955
 
                            self._new_id[trans_id],
956
 
                            self._new_name[trans_id], 
957
 
                            self.final_file_id(self._new_parent[trans_id]),
958
 
                            None, self._new_reference_revision[trans_id])
959
 
                    else:
960
 
                        new_entry = inventory.make_entry(kind,
961
 
                            self.final_name(trans_id),
962
 
                            self.final_file_id(self.final_parent(trans_id)),
963
 
                            self._new_id[trans_id])
964
 
                else:
965
 
                    if trans_id in self._new_name or trans_id in\
966
 
                        self._new_parent or\
967
 
                        trans_id in self._new_executability:
968
 
                        file_id = self.final_file_id(trans_id)
969
 
                        if file_id is not None:
970
 
                            entry = inv[file_id]
971
 
                            new_entry = entry.copy()
972
 
 
973
 
                    if trans_id in self._new_name or trans_id in\
974
 
                        self._new_parent:
975
 
                            if new_entry is not None:
976
 
                                new_entry.name = self.final_name(trans_id)
977
 
                                parent = self.final_parent(trans_id)
978
 
                                parent_id = self.final_file_id(parent)
979
 
                                new_entry.parent_id = parent_id
980
 
 
981
 
                if trans_id in self._new_executability:
982
 
                    self._set_executability(path, new_entry, trans_id)
983
 
                if new_entry is not None:
984
 
                    if new_entry.file_id in inv:
985
 
                        old_path = inv.id2path(new_entry.file_id)
986
 
                    else:
987
 
                        old_path = None
988
 
                    inventory_delta.append((old_path, path,
989
 
                                            new_entry.file_id,
990
 
                                            new_entry))
991
 
        finally:
992
 
            child_pb.finished()
993
 
        return modified_paths
994
 
 
995
 
    def _set_executability(self, path, entry, trans_id):
 
714
 
 
715
    def _set_executability(self, path, trans_id):
996
716
        """Set the executability of versioned files """
997
 
        new_executability = self._new_executability[trans_id]
998
 
        entry.executable = new_executability
999
717
        if supports_executable():
 
718
            new_executability = self._new_executability[trans_id]
1000
719
            abspath = self._tree.abspath(path)
1001
720
            current_mode = os.stat(abspath).st_mode
1002
721
            if new_executability:
1019
738
            self.version_file(file_id, trans_id)
1020
739
        return trans_id
1021
740
 
1022
 
    def new_file(self, name, parent_id, contents, file_id=None, 
 
741
    def new_file(self, name, parent_id, contents, file_id=None,
1023
742
                 executable=None):
1024
743
        """Convenience method to create files.
1025
 
        
 
744
 
1026
745
        name is the name of the file to create.
1027
746
        parent_id is the transaction id of the parent directory of the file.
1028
747
        contents is an iterator of bytestrings, which will be used to produce
1048
767
        """
1049
768
        trans_id = self._new_entry(name, parent_id, file_id)
1050
769
        self.create_directory(trans_id)
1051
 
        return trans_id 
 
770
        return trans_id
1052
771
 
1053
772
    def new_symlink(self, name, parent_id, target, file_id=None):
1054
773
        """Convenience method to create symbolic link.
1055
 
        
 
774
 
1056
775
        name is the name of the symlink to create.
1057
776
        parent_id is the transaction id of the parent directory of the symlink.
1058
777
        target is a bytestring of the target of the symlink.
1097
816
        from_path = self._tree_id_paths.get(from_trans_id)
1098
817
        if from_versioned:
1099
818
            # get data from working tree if versioned
1100
 
            from_entry = self._tree.inventory[file_id]
 
819
            from_entry = self._tree.iter_entries_by_dir([file_id]).next()[1]
1101
820
            from_name = from_entry.name
1102
821
            from_parent = from_entry.parent_id
1103
822
        else:
1139
858
            to_executable = False
1140
859
        return to_name, to_parent, to_kind, to_executable
1141
860
 
1142
 
    def _iter_changes(self):
1143
 
        """Produce output in the same format as Tree._iter_changes.
 
861
    def iter_changes(self):
 
862
        """Produce output in the same format as Tree.iter_changes.
1144
863
 
1145
864
        Will produce nonsensical results if invoked while inventory/filesystem
1146
865
        conflicts (as reported by TreeTransform.find_conflicts()) are present.
1201
920
                   (from_executable, to_executable)))
1202
921
        return iter(sorted(results, key=lambda x:x[1]))
1203
922
 
 
923
    def get_preview_tree(self):
 
924
        """Return a tree representing the result of the transform.
 
925
 
 
926
        The tree is a snapshot, and altering the TreeTransform will invalidate
 
927
        it.
 
928
        """
 
929
        return _PreviewTree(self)
 
930
 
 
931
    def commit(self, branch, message, merge_parents=None, strict=False,
 
932
               timestamp=None, timezone=None, committer=None, authors=None,
 
933
               revprops=None, revision_id=None):
 
934
        """Commit the result of this TreeTransform to a branch.
 
935
 
 
936
        :param branch: The branch to commit to.
 
937
        :param message: The message to attach to the commit.
 
938
        :param merge_parents: Additional parent revision-ids specified by
 
939
            pending merges.
 
940
        :param strict: If True, abort the commit if there are unversioned
 
941
            files.
 
942
        :param timestamp: if not None, seconds-since-epoch for the time and
 
943
            date.  (May be a float.)
 
944
        :param timezone: Optional timezone for timestamp, as an offset in
 
945
            seconds.
 
946
        :param committer: Optional committer in email-id format.
 
947
            (e.g. "J Random Hacker <jrandom@example.com>")
 
948
        :param authors: Optional list of authors in email-id format.
 
949
        :param revprops: Optional dictionary of revision properties.
 
950
        :param revision_id: Optional revision id.  (Specifying a revision-id
 
951
            may reduce performance for some non-native formats.)
 
952
        :return: The revision_id of the revision committed.
 
953
        """
 
954
        self._check_malformed()
 
955
        if strict:
 
956
            unversioned = set(self._new_contents).difference(set(self._new_id))
 
957
            for trans_id in unversioned:
 
958
                if self.final_file_id(trans_id) is None:
 
959
                    raise errors.StrictCommitFailed()
 
960
 
 
961
        revno, last_rev_id = branch.last_revision_info()
 
962
        if last_rev_id == _mod_revision.NULL_REVISION:
 
963
            if merge_parents is not None:
 
964
                raise ValueError('Cannot supply merge parents for first'
 
965
                                 ' commit.')
 
966
            parent_ids = []
 
967
        else:
 
968
            parent_ids = [last_rev_id]
 
969
            if merge_parents is not None:
 
970
                parent_ids.extend(merge_parents)
 
971
        if self._tree.get_revision_id() != last_rev_id:
 
972
            raise ValueError('TreeTransform not based on branch basis: %s' %
 
973
                             self._tree.get_revision_id())
 
974
        revprops = commit.Commit.update_revprops(revprops, branch, authors)
 
975
        builder = branch.get_commit_builder(parent_ids,
 
976
                                            timestamp=timestamp,
 
977
                                            timezone=timezone,
 
978
                                            committer=committer,
 
979
                                            revprops=revprops,
 
980
                                            revision_id=revision_id)
 
981
        preview = self.get_preview_tree()
 
982
        list(builder.record_iter_changes(preview, last_rev_id,
 
983
                                         self.iter_changes()))
 
984
        builder.finish_inventory()
 
985
        revision_id = builder.commit(message)
 
986
        branch.set_last_revision_info(revno + 1, revision_id)
 
987
        return revision_id
 
988
 
 
989
    def _text_parent(self, trans_id):
 
990
        file_id = self.tree_file_id(trans_id)
 
991
        try:
 
992
            if file_id is None or self._tree.kind(file_id) != 'file':
 
993
                return None
 
994
        except errors.NoSuchFile:
 
995
            return None
 
996
        return file_id
 
997
 
 
998
    def _get_parents_texts(self, trans_id):
 
999
        """Get texts for compression parents of this file."""
 
1000
        file_id = self._text_parent(trans_id)
 
1001
        if file_id is None:
 
1002
            return ()
 
1003
        return (self._tree.get_file_text(file_id),)
 
1004
 
 
1005
    def _get_parents_lines(self, trans_id):
 
1006
        """Get lines for compression parents of this file."""
 
1007
        file_id = self._text_parent(trans_id)
 
1008
        if file_id is None:
 
1009
            return ()
 
1010
        return (self._tree.get_file_lines(file_id),)
 
1011
 
 
1012
    def serialize(self, serializer):
 
1013
        """Serialize this TreeTransform.
 
1014
 
 
1015
        :param serializer: A Serialiser like pack.ContainerSerializer.
 
1016
        """
 
1017
        new_name = dict((k, v.encode('utf-8')) for k, v in
 
1018
                        self._new_name.items())
 
1019
        new_executability = dict((k, int(v)) for k, v in
 
1020
                                 self._new_executability.items())
 
1021
        tree_path_ids = dict((k.encode('utf-8'), v)
 
1022
                             for k, v in self._tree_path_ids.items())
 
1023
        attribs = {
 
1024
            '_id_number': self._id_number,
 
1025
            '_new_name': new_name,
 
1026
            '_new_parent': self._new_parent,
 
1027
            '_new_executability': new_executability,
 
1028
            '_new_id': self._new_id,
 
1029
            '_tree_path_ids': tree_path_ids,
 
1030
            '_removed_id': list(self._removed_id),
 
1031
            '_removed_contents': list(self._removed_contents),
 
1032
            '_non_present_ids': self._non_present_ids,
 
1033
            }
 
1034
        yield serializer.bytes_record(bencode.bencode(attribs),
 
1035
                                      (('attribs',),))
 
1036
        for trans_id, kind in self._new_contents.items():
 
1037
            if kind == 'file':
 
1038
                lines = osutils.chunks_to_lines(
 
1039
                    self._read_file_chunks(trans_id))
 
1040
                parents = self._get_parents_lines(trans_id)
 
1041
                mpdiff = multiparent.MultiParent.from_lines(lines, parents)
 
1042
                content = ''.join(mpdiff.to_patch())
 
1043
            if kind == 'directory':
 
1044
                content = ''
 
1045
            if kind == 'symlink':
 
1046
                content = self._read_symlink_target(trans_id)
 
1047
            yield serializer.bytes_record(content, ((trans_id, kind),))
 
1048
 
 
1049
    def deserialize(self, records):
 
1050
        """Deserialize a stored TreeTransform.
 
1051
 
 
1052
        :param records: An iterable of (names, content) tuples, as per
 
1053
            pack.ContainerPushParser.
 
1054
        """
 
1055
        names, content = records.next()
 
1056
        attribs = bencode.bdecode(content)
 
1057
        self._id_number = attribs['_id_number']
 
1058
        self._new_name = dict((k, v.decode('utf-8'))
 
1059
                            for k, v in attribs['_new_name'].items())
 
1060
        self._new_parent = attribs['_new_parent']
 
1061
        self._new_executability = dict((k, bool(v)) for k, v in
 
1062
            attribs['_new_executability'].items())
 
1063
        self._new_id = attribs['_new_id']
 
1064
        self._r_new_id = dict((v, k) for k, v in self._new_id.items())
 
1065
        self._tree_path_ids = {}
 
1066
        self._tree_id_paths = {}
 
1067
        for bytepath, trans_id in attribs['_tree_path_ids'].items():
 
1068
            path = bytepath.decode('utf-8')
 
1069
            self._tree_path_ids[path] = trans_id
 
1070
            self._tree_id_paths[trans_id] = path
 
1071
        self._removed_id = set(attribs['_removed_id'])
 
1072
        self._removed_contents = set(attribs['_removed_contents'])
 
1073
        self._non_present_ids = attribs['_non_present_ids']
 
1074
        for ((trans_id, kind),), content in records:
 
1075
            if kind == 'file':
 
1076
                mpdiff = multiparent.MultiParent.from_patch(content)
 
1077
                lines = mpdiff.to_lines(self._get_parents_texts(trans_id))
 
1078
                self.create_file(lines, trans_id)
 
1079
            if kind == 'directory':
 
1080
                self.create_directory(trans_id)
 
1081
            if kind == 'symlink':
 
1082
                self.create_symlink(content.decode('utf-8'), trans_id)
 
1083
 
 
1084
 
 
1085
class DiskTreeTransform(TreeTransformBase):
 
1086
    """Tree transform storing its contents on disk."""
 
1087
 
 
1088
    def __init__(self, tree, limbodir, pb=None,
 
1089
                 case_sensitive=True):
 
1090
        """Constructor.
 
1091
        :param tree: The tree that will be transformed, but not necessarily
 
1092
            the output tree.
 
1093
        :param limbodir: A directory where new files can be stored until
 
1094
            they are installed in their proper places
 
1095
        :param pb: ignored
 
1096
        :param case_sensitive: If True, the target of the transform is
 
1097
            case sensitive, not just case preserving.
 
1098
        """
 
1099
        TreeTransformBase.__init__(self, tree, pb, case_sensitive)
 
1100
        self._limbodir = limbodir
 
1101
        self._deletiondir = None
 
1102
        # A mapping of transform ids to their limbo filename
 
1103
        self._limbo_files = {}
 
1104
        # A mapping of transform ids to a set of the transform ids of children
 
1105
        # that their limbo directory has
 
1106
        self._limbo_children = {}
 
1107
        # Map transform ids to maps of child filename to child transform id
 
1108
        self._limbo_children_names = {}
 
1109
        # List of transform ids that need to be renamed from limbo into place
 
1110
        self._needs_rename = set()
 
1111
        self._creation_mtime = None
 
1112
 
 
1113
    def finalize(self):
 
1114
        """Release the working tree lock, if held, clean up limbo dir.
 
1115
 
 
1116
        This is required if apply has not been invoked, but can be invoked
 
1117
        even after apply.
 
1118
        """
 
1119
        if self._tree is None:
 
1120
            return
 
1121
        try:
 
1122
            entries = [(self._limbo_name(t), t, k) for t, k in
 
1123
                       self._new_contents.iteritems()]
 
1124
            entries.sort(reverse=True)
 
1125
            for path, trans_id, kind in entries:
 
1126
                delete_any(path)
 
1127
            try:
 
1128
                delete_any(self._limbodir)
 
1129
            except OSError:
 
1130
                # We don't especially care *why* the dir is immortal.
 
1131
                raise ImmortalLimbo(self._limbodir)
 
1132
            try:
 
1133
                if self._deletiondir is not None:
 
1134
                    delete_any(self._deletiondir)
 
1135
            except OSError:
 
1136
                raise errors.ImmortalPendingDeletion(self._deletiondir)
 
1137
        finally:
 
1138
            TreeTransformBase.finalize(self)
 
1139
 
 
1140
    def _limbo_name(self, trans_id):
 
1141
        """Generate the limbo name of a file"""
 
1142
        limbo_name = self._limbo_files.get(trans_id)
 
1143
        if limbo_name is None:
 
1144
            limbo_name = self._generate_limbo_path(trans_id)
 
1145
            self._limbo_files[trans_id] = limbo_name
 
1146
        return limbo_name
 
1147
 
 
1148
    def _generate_limbo_path(self, trans_id):
 
1149
        """Generate a limbo path using the trans_id as the relative path.
 
1150
 
 
1151
        This is suitable as a fallback, and when the transform should not be
 
1152
        sensitive to the path encoding of the limbo directory.
 
1153
        """
 
1154
        self._needs_rename.add(trans_id)
 
1155
        return pathjoin(self._limbodir, trans_id)
 
1156
 
 
1157
    def adjust_path(self, name, parent, trans_id):
 
1158
        previous_parent = self._new_parent.get(trans_id)
 
1159
        previous_name = self._new_name.get(trans_id)
 
1160
        TreeTransformBase.adjust_path(self, name, parent, trans_id)
 
1161
        if (trans_id in self._limbo_files and
 
1162
            trans_id not in self._needs_rename):
 
1163
            self._rename_in_limbo([trans_id])
 
1164
            if previous_parent != parent:
 
1165
                self._limbo_children[previous_parent].remove(trans_id)
 
1166
            if previous_parent != parent or previous_name != name:
 
1167
                del self._limbo_children_names[previous_parent][previous_name]
 
1168
 
 
1169
    def _rename_in_limbo(self, trans_ids):
 
1170
        """Fix limbo names so that the right final path is produced.
 
1171
 
 
1172
        This means we outsmarted ourselves-- we tried to avoid renaming
 
1173
        these files later by creating them with their final names in their
 
1174
        final parents.  But now the previous name or parent is no longer
 
1175
        suitable, so we have to rename them.
 
1176
 
 
1177
        Even for trans_ids that have no new contents, we must remove their
 
1178
        entries from _limbo_files, because they are now stale.
 
1179
        """
 
1180
        for trans_id in trans_ids:
 
1181
            old_path = self._limbo_files.pop(trans_id)
 
1182
            if trans_id not in self._new_contents:
 
1183
                continue
 
1184
            new_path = self._limbo_name(trans_id)
 
1185
            osutils.rename(old_path, new_path)
 
1186
            for descendant in self._limbo_descendants(trans_id):
 
1187
                desc_path = self._limbo_files[descendant]
 
1188
                desc_path = new_path + desc_path[len(old_path):]
 
1189
                self._limbo_files[descendant] = desc_path
 
1190
 
 
1191
    def _limbo_descendants(self, trans_id):
 
1192
        """Return the set of trans_ids whose limbo paths descend from this."""
 
1193
        descendants = set(self._limbo_children.get(trans_id, []))
 
1194
        for descendant in list(descendants):
 
1195
            descendants.update(self._limbo_descendants(descendant))
 
1196
        return descendants
 
1197
 
 
1198
    def create_file(self, contents, trans_id, mode_id=None):
 
1199
        """Schedule creation of a new file.
 
1200
 
 
1201
        See also new_file.
 
1202
 
 
1203
        Contents is an iterator of strings, all of which will be written
 
1204
        to the target destination.
 
1205
 
 
1206
        New file takes the permissions of any existing file with that id,
 
1207
        unless mode_id is specified.
 
1208
        """
 
1209
        name = self._limbo_name(trans_id)
 
1210
        f = open(name, 'wb')
 
1211
        try:
 
1212
            try:
 
1213
                unique_add(self._new_contents, trans_id, 'file')
 
1214
            except:
 
1215
                # Clean up the file, it never got registered so
 
1216
                # TreeTransform.finalize() won't clean it up.
 
1217
                f.close()
 
1218
                os.unlink(name)
 
1219
                raise
 
1220
 
 
1221
            f.writelines(contents)
 
1222
        finally:
 
1223
            f.close()
 
1224
        self._set_mtime(name)
 
1225
        self._set_mode(trans_id, mode_id, S_ISREG)
 
1226
 
 
1227
    def _read_file_chunks(self, trans_id):
 
1228
        cur_file = open(self._limbo_name(trans_id), 'rb')
 
1229
        try:
 
1230
            return cur_file.readlines()
 
1231
        finally:
 
1232
            cur_file.close()
 
1233
 
 
1234
    def _read_symlink_target(self, trans_id):
 
1235
        return os.readlink(self._limbo_name(trans_id))
 
1236
 
 
1237
    def _set_mtime(self, path):
 
1238
        """All files that are created get the same mtime.
 
1239
 
 
1240
        This time is set by the first object to be created.
 
1241
        """
 
1242
        if self._creation_mtime is None:
 
1243
            self._creation_mtime = time.time()
 
1244
        os.utime(path, (self._creation_mtime, self._creation_mtime))
 
1245
 
 
1246
    def create_hardlink(self, path, trans_id):
 
1247
        """Schedule creation of a hard link"""
 
1248
        name = self._limbo_name(trans_id)
 
1249
        try:
 
1250
            os.link(path, name)
 
1251
        except OSError, e:
 
1252
            if e.errno != errno.EPERM:
 
1253
                raise
 
1254
            raise errors.HardLinkNotSupported(path)
 
1255
        try:
 
1256
            unique_add(self._new_contents, trans_id, 'file')
 
1257
        except:
 
1258
            # Clean up the file, it never got registered so
 
1259
            # TreeTransform.finalize() won't clean it up.
 
1260
            os.unlink(name)
 
1261
            raise
 
1262
 
 
1263
    def create_directory(self, trans_id):
 
1264
        """Schedule creation of a new directory.
 
1265
 
 
1266
        See also new_directory.
 
1267
        """
 
1268
        os.mkdir(self._limbo_name(trans_id))
 
1269
        unique_add(self._new_contents, trans_id, 'directory')
 
1270
 
 
1271
    def create_symlink(self, target, trans_id):
 
1272
        """Schedule creation of a new symbolic link.
 
1273
 
 
1274
        target is a bytestring.
 
1275
        See also new_symlink.
 
1276
        """
 
1277
        if has_symlinks():
 
1278
            os.symlink(target, self._limbo_name(trans_id))
 
1279
            unique_add(self._new_contents, trans_id, 'symlink')
 
1280
        else:
 
1281
            try:
 
1282
                path = FinalPaths(self).get_path(trans_id)
 
1283
            except KeyError:
 
1284
                path = None
 
1285
            raise UnableCreateSymlink(path=path)
 
1286
 
 
1287
    def cancel_creation(self, trans_id):
 
1288
        """Cancel the creation of new file contents."""
 
1289
        del self._new_contents[trans_id]
 
1290
        children = self._limbo_children.get(trans_id)
 
1291
        # if this is a limbo directory with children, move them before removing
 
1292
        # the directory
 
1293
        if children is not None:
 
1294
            self._rename_in_limbo(children)
 
1295
            del self._limbo_children[trans_id]
 
1296
            del self._limbo_children_names[trans_id]
 
1297
        delete_any(self._limbo_name(trans_id))
 
1298
 
 
1299
 
 
1300
class TreeTransform(DiskTreeTransform):
 
1301
    """Represent a tree transformation.
 
1302
 
 
1303
    This object is designed to support incremental generation of the transform,
 
1304
    in any order.
 
1305
 
 
1306
    However, it gives optimum performance when parent directories are created
 
1307
    before their contents.  The transform is then able to put child files
 
1308
    directly in their parent directory, avoiding later renames.
 
1309
 
 
1310
    It is easy to produce malformed transforms, but they are generally
 
1311
    harmless.  Attempting to apply a malformed transform will cause an
 
1312
    exception to be raised before any modifications are made to the tree.
 
1313
 
 
1314
    Many kinds of malformed transforms can be corrected with the
 
1315
    resolve_conflicts function.  The remaining ones indicate programming error,
 
1316
    such as trying to create a file with no path.
 
1317
 
 
1318
    Two sets of file creation methods are supplied.  Convenience methods are:
 
1319
     * new_file
 
1320
     * new_directory
 
1321
     * new_symlink
 
1322
 
 
1323
    These are composed of the low-level methods:
 
1324
     * create_path
 
1325
     * create_file or create_directory or create_symlink
 
1326
     * version_file
 
1327
     * set_executability
 
1328
 
 
1329
    Transform/Transaction ids
 
1330
    -------------------------
 
1331
    trans_ids are temporary ids assigned to all files involved in a transform.
 
1332
    It's possible, even common, that not all files in the Tree have trans_ids.
 
1333
 
 
1334
    trans_ids are used because filenames and file_ids are not good enough
 
1335
    identifiers; filenames change, and not all files have file_ids.  File-ids
 
1336
    are also associated with trans-ids, so that moving a file moves its
 
1337
    file-id.
 
1338
 
 
1339
    trans_ids are only valid for the TreeTransform that generated them.
 
1340
 
 
1341
    Limbo
 
1342
    -----
 
1343
    Limbo is a temporary directory use to hold new versions of files.
 
1344
    Files are added to limbo by create_file, create_directory, create_symlink,
 
1345
    and their convenience variants (new_*).  Files may be removed from limbo
 
1346
    using cancel_creation.  Files are renamed from limbo into their final
 
1347
    location as part of TreeTransform.apply
 
1348
 
 
1349
    Limbo must be cleaned up, by either calling TreeTransform.apply or
 
1350
    calling TreeTransform.finalize.
 
1351
 
 
1352
    Files are placed into limbo inside their parent directories, where
 
1353
    possible.  This reduces subsequent renames, and makes operations involving
 
1354
    lots of files faster.  This optimization is only possible if the parent
 
1355
    directory is created *before* creating any of its children, so avoid
 
1356
    creating children before parents, where possible.
 
1357
 
 
1358
    Pending-deletion
 
1359
    ----------------
 
1360
    This temporary directory is used by _FileMover for storing files that are
 
1361
    about to be deleted.  In case of rollback, the files will be restored.
 
1362
    FileMover does not delete files until it is sure that a rollback will not
 
1363
    happen.
 
1364
    """
 
1365
    def __init__(self, tree, pb=None):
 
1366
        """Note: a tree_write lock is taken on the tree.
 
1367
 
 
1368
        Use TreeTransform.finalize() to release the lock (can be omitted if
 
1369
        TreeTransform.apply() called).
 
1370
        """
 
1371
        tree.lock_tree_write()
 
1372
 
 
1373
        try:
 
1374
            limbodir = urlutils.local_path_from_url(
 
1375
                tree._transport.abspath('limbo'))
 
1376
            try:
 
1377
                os.mkdir(limbodir)
 
1378
            except OSError, e:
 
1379
                if e.errno == errno.EEXIST:
 
1380
                    raise ExistingLimbo(limbodir)
 
1381
            deletiondir = urlutils.local_path_from_url(
 
1382
                tree._transport.abspath('pending-deletion'))
 
1383
            try:
 
1384
                os.mkdir(deletiondir)
 
1385
            except OSError, e:
 
1386
                if e.errno == errno.EEXIST:
 
1387
                    raise errors.ExistingPendingDeletion(deletiondir)
 
1388
        except:
 
1389
            tree.unlock()
 
1390
            raise
 
1391
 
 
1392
        # Cache of realpath results, to speed up canonical_path
 
1393
        self._realpaths = {}
 
1394
        # Cache of relpath results, to speed up canonical_path
 
1395
        self._relpaths = {}
 
1396
        DiskTreeTransform.__init__(self, tree, limbodir, pb,
 
1397
                                   tree.case_sensitive)
 
1398
        self._deletiondir = deletiondir
 
1399
 
 
1400
    def canonical_path(self, path):
 
1401
        """Get the canonical tree-relative path"""
 
1402
        # don't follow final symlinks
 
1403
        abs = self._tree.abspath(path)
 
1404
        if abs in self._relpaths:
 
1405
            return self._relpaths[abs]
 
1406
        dirname, basename = os.path.split(abs)
 
1407
        if dirname not in self._realpaths:
 
1408
            self._realpaths[dirname] = os.path.realpath(dirname)
 
1409
        dirname = self._realpaths[dirname]
 
1410
        abs = pathjoin(dirname, basename)
 
1411
        if dirname in self._relpaths:
 
1412
            relpath = pathjoin(self._relpaths[dirname], basename)
 
1413
            relpath = relpath.rstrip('/\\')
 
1414
        else:
 
1415
            relpath = self._tree.relpath(abs)
 
1416
        self._relpaths[abs] = relpath
 
1417
        return relpath
 
1418
 
 
1419
    def tree_kind(self, trans_id):
 
1420
        """Determine the file kind in the working tree.
 
1421
 
 
1422
        Raises NoSuchFile if the file does not exist
 
1423
        """
 
1424
        path = self._tree_id_paths.get(trans_id)
 
1425
        if path is None:
 
1426
            raise NoSuchFile(None)
 
1427
        try:
 
1428
            return file_kind(self._tree.abspath(path))
 
1429
        except OSError, e:
 
1430
            if e.errno != errno.ENOENT:
 
1431
                raise
 
1432
            else:
 
1433
                raise NoSuchFile(path)
 
1434
 
 
1435
    def _set_mode(self, trans_id, mode_id, typefunc):
 
1436
        """Set the mode of new file contents.
 
1437
        The mode_id is the existing file to get the mode from (often the same
 
1438
        as trans_id).  The operation is only performed if there's a mode match
 
1439
        according to typefunc.
 
1440
        """
 
1441
        if mode_id is None:
 
1442
            mode_id = trans_id
 
1443
        try:
 
1444
            old_path = self._tree_id_paths[mode_id]
 
1445
        except KeyError:
 
1446
            return
 
1447
        try:
 
1448
            mode = os.stat(self._tree.abspath(old_path)).st_mode
 
1449
        except OSError, e:
 
1450
            if e.errno in (errno.ENOENT, errno.ENOTDIR):
 
1451
                # Either old_path doesn't exist, or the parent of the
 
1452
                # target is not a directory (but will be one eventually)
 
1453
                # Either way, we know it doesn't exist *right now*
 
1454
                # See also bug #248448
 
1455
                return
 
1456
            else:
 
1457
                raise
 
1458
        if typefunc(mode):
 
1459
            os.chmod(self._limbo_name(trans_id), mode)
 
1460
 
 
1461
    def iter_tree_children(self, parent_id):
 
1462
        """Iterate through the entry's tree children, if any"""
 
1463
        try:
 
1464
            path = self._tree_id_paths[parent_id]
 
1465
        except KeyError:
 
1466
            return
 
1467
        try:
 
1468
            children = os.listdir(self._tree.abspath(path))
 
1469
        except OSError, e:
 
1470
            if not (osutils._is_error_enotdir(e)
 
1471
                    or e.errno in (errno.ENOENT, errno.ESRCH)):
 
1472
                raise
 
1473
            return
 
1474
 
 
1475
        for child in children:
 
1476
            childpath = joinpath(path, child)
 
1477
            if self._tree.is_control_filename(childpath):
 
1478
                continue
 
1479
            yield self.trans_id_tree_path(childpath)
 
1480
 
 
1481
    def _generate_limbo_path(self, trans_id):
 
1482
        """Generate a limbo path using the final path if possible.
 
1483
 
 
1484
        This optimizes the performance of applying the tree transform by
 
1485
        avoiding renames.  These renames can be avoided only when the parent
 
1486
        directory is already scheduled for creation.
 
1487
 
 
1488
        If the final path cannot be used, falls back to using the trans_id as
 
1489
        the relpath.
 
1490
        """
 
1491
        parent = self._new_parent.get(trans_id)
 
1492
        # if the parent directory is already in limbo (e.g. when building a
 
1493
        # tree), choose a limbo name inside the parent, to reduce further
 
1494
        # renames.
 
1495
        use_direct_path = False
 
1496
        if self._new_contents.get(parent) == 'directory':
 
1497
            filename = self._new_name.get(trans_id)
 
1498
            if filename is not None:
 
1499
                if parent not in self._limbo_children:
 
1500
                    self._limbo_children[parent] = set()
 
1501
                    self._limbo_children_names[parent] = {}
 
1502
                    use_direct_path = True
 
1503
                # the direct path can only be used if no other file has
 
1504
                # already taken this pathname, i.e. if the name is unused, or
 
1505
                # if it is already associated with this trans_id.
 
1506
                elif self._case_sensitive_target:
 
1507
                    if (self._limbo_children_names[parent].get(filename)
 
1508
                        in (trans_id, None)):
 
1509
                        use_direct_path = True
 
1510
                else:
 
1511
                    for l_filename, l_trans_id in\
 
1512
                        self._limbo_children_names[parent].iteritems():
 
1513
                        if l_trans_id == trans_id:
 
1514
                            continue
 
1515
                        if l_filename.lower() == filename.lower():
 
1516
                            break
 
1517
                    else:
 
1518
                        use_direct_path = True
 
1519
 
 
1520
        if not use_direct_path:
 
1521
            return DiskTreeTransform._generate_limbo_path(self, trans_id)
 
1522
 
 
1523
        limbo_name = pathjoin(self._limbo_files[parent], filename)
 
1524
        self._limbo_children[parent].add(trans_id)
 
1525
        self._limbo_children_names[parent][filename] = trans_id
 
1526
        return limbo_name
 
1527
 
 
1528
 
 
1529
    def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
 
1530
        """Apply all changes to the inventory and filesystem.
 
1531
 
 
1532
        If filesystem or inventory conflicts are present, MalformedTransform
 
1533
        will be thrown.
 
1534
 
 
1535
        If apply succeeds, finalize is not necessary.
 
1536
 
 
1537
        :param no_conflicts: if True, the caller guarantees there are no
 
1538
            conflicts, so no check is made.
 
1539
        :param precomputed_delta: An inventory delta to use instead of
 
1540
            calculating one.
 
1541
        :param _mover: Supply an alternate FileMover, for testing
 
1542
        """
 
1543
        if not no_conflicts:
 
1544
            self._check_malformed()
 
1545
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1546
        try:
 
1547
            if precomputed_delta is None:
 
1548
                child_pb.update('Apply phase', 0, 2)
 
1549
                inventory_delta = self._generate_inventory_delta()
 
1550
                offset = 1
 
1551
            else:
 
1552
                inventory_delta = precomputed_delta
 
1553
                offset = 0
 
1554
            if _mover is None:
 
1555
                mover = _FileMover()
 
1556
            else:
 
1557
                mover = _mover
 
1558
            try:
 
1559
                child_pb.update('Apply phase', 0 + offset, 2 + offset)
 
1560
                self._apply_removals(mover)
 
1561
                child_pb.update('Apply phase', 1 + offset, 2 + offset)
 
1562
                modified_paths = self._apply_insertions(mover)
 
1563
            except:
 
1564
                mover.rollback()
 
1565
                raise
 
1566
            else:
 
1567
                mover.apply_deletions()
 
1568
        finally:
 
1569
            child_pb.finished()
 
1570
        self._tree.apply_inventory_delta(inventory_delta)
 
1571
        self._done = True
 
1572
        self.finalize()
 
1573
        return _TransformResults(modified_paths, self.rename_count)
 
1574
 
 
1575
    def _generate_inventory_delta(self):
 
1576
        """Generate an inventory delta for the current transform."""
 
1577
        inventory_delta = []
 
1578
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1579
        new_paths = self._inventory_altered()
 
1580
        total_entries = len(new_paths) + len(self._removed_id)
 
1581
        try:
 
1582
            for num, trans_id in enumerate(self._removed_id):
 
1583
                if (num % 10) == 0:
 
1584
                    child_pb.update('removing file', num, total_entries)
 
1585
                if trans_id == self._new_root:
 
1586
                    file_id = self._tree.get_root_id()
 
1587
                else:
 
1588
                    file_id = self.tree_file_id(trans_id)
 
1589
                # File-id isn't really being deleted, just moved
 
1590
                if file_id in self._r_new_id:
 
1591
                    continue
 
1592
                path = self._tree_id_paths[trans_id]
 
1593
                inventory_delta.append((path, None, file_id, None))
 
1594
            new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
 
1595
                                     new_paths)
 
1596
            entries = self._tree.iter_entries_by_dir(
 
1597
                new_path_file_ids.values())
 
1598
            old_paths = dict((e.file_id, p) for p, e in entries)
 
1599
            final_kinds = {}
 
1600
            for num, (path, trans_id) in enumerate(new_paths):
 
1601
                if (num % 10) == 0:
 
1602
                    child_pb.update('adding file',
 
1603
                                    num + len(self._removed_id), total_entries)
 
1604
                file_id = new_path_file_ids[trans_id]
 
1605
                if file_id is None:
 
1606
                    continue
 
1607
                needs_entry = False
 
1608
                try:
 
1609
                    kind = self.final_kind(trans_id)
 
1610
                except NoSuchFile:
 
1611
                    kind = self._tree.stored_kind(file_id)
 
1612
                parent_trans_id = self.final_parent(trans_id)
 
1613
                parent_file_id = new_path_file_ids.get(parent_trans_id)
 
1614
                if parent_file_id is None:
 
1615
                    parent_file_id = self.final_file_id(parent_trans_id)
 
1616
                if trans_id in self._new_reference_revision:
 
1617
                    new_entry = inventory.TreeReference(
 
1618
                        file_id,
 
1619
                        self._new_name[trans_id],
 
1620
                        self.final_file_id(self._new_parent[trans_id]),
 
1621
                        None, self._new_reference_revision[trans_id])
 
1622
                else:
 
1623
                    new_entry = inventory.make_entry(kind,
 
1624
                        self.final_name(trans_id),
 
1625
                        parent_file_id, file_id)
 
1626
                old_path = old_paths.get(new_entry.file_id)
 
1627
                new_executability = self._new_executability.get(trans_id)
 
1628
                if new_executability is not None:
 
1629
                    new_entry.executable = new_executability
 
1630
                inventory_delta.append(
 
1631
                    (old_path, path, new_entry.file_id, new_entry))
 
1632
        finally:
 
1633
            child_pb.finished()
 
1634
        return inventory_delta
 
1635
 
 
1636
    def _apply_removals(self, mover):
 
1637
        """Perform tree operations that remove directory/inventory names.
 
1638
 
 
1639
        That is, delete files that are to be deleted, and put any files that
 
1640
        need renaming into limbo.  This must be done in strict child-to-parent
 
1641
        order.
 
1642
 
 
1643
        If inventory_delta is None, no inventory delta generation is performed.
 
1644
        """
 
1645
        tree_paths = list(self._tree_path_ids.iteritems())
 
1646
        tree_paths.sort(reverse=True)
 
1647
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1648
        try:
 
1649
            for num, data in enumerate(tree_paths):
 
1650
                path, trans_id = data
 
1651
                child_pb.update('removing file', num, len(tree_paths))
 
1652
                full_path = self._tree.abspath(path)
 
1653
                if trans_id in self._removed_contents:
 
1654
                    delete_path = os.path.join(self._deletiondir, trans_id)
 
1655
                    mover.pre_delete(full_path, delete_path)
 
1656
                elif (trans_id in self._new_name
 
1657
                      or trans_id in self._new_parent):
 
1658
                    try:
 
1659
                        mover.rename(full_path, self._limbo_name(trans_id))
 
1660
                    except errors.TransformRenameFailed, e:
 
1661
                        if e.errno != errno.ENOENT:
 
1662
                            raise
 
1663
                    else:
 
1664
                        self.rename_count += 1
 
1665
        finally:
 
1666
            child_pb.finished()
 
1667
 
 
1668
    def _apply_insertions(self, mover):
 
1669
        """Perform tree operations that insert directory/inventory names.
 
1670
 
 
1671
        That is, create any files that need to be created, and restore from
 
1672
        limbo any files that needed renaming.  This must be done in strict
 
1673
        parent-to-child order.
 
1674
 
 
1675
        If inventory_delta is None, no inventory delta is calculated, and
 
1676
        no list of modified paths is returned.
 
1677
        """
 
1678
        new_paths = self.new_paths(filesystem_only=True)
 
1679
        modified_paths = []
 
1680
        new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
 
1681
                                 new_paths)
 
1682
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1683
        try:
 
1684
            for num, (path, trans_id) in enumerate(new_paths):
 
1685
                if (num % 10) == 0:
 
1686
                    child_pb.update('adding file', num, len(new_paths))
 
1687
                full_path = self._tree.abspath(path)
 
1688
                if trans_id in self._needs_rename:
 
1689
                    try:
 
1690
                        mover.rename(self._limbo_name(trans_id), full_path)
 
1691
                    except errors.TransformRenameFailed, e:
 
1692
                        # We may be renaming a dangling inventory id
 
1693
                        if e.errno != errno.ENOENT:
 
1694
                            raise
 
1695
                    else:
 
1696
                        self.rename_count += 1
 
1697
                if (trans_id in self._new_contents or
 
1698
                    self.path_changed(trans_id)):
 
1699
                    if trans_id in self._new_contents:
 
1700
                        modified_paths.append(full_path)
 
1701
                if trans_id in self._new_executability:
 
1702
                    self._set_executability(path, trans_id)
 
1703
        finally:
 
1704
            child_pb.finished()
 
1705
        self._new_contents.clear()
 
1706
        return modified_paths
 
1707
 
 
1708
 
 
1709
class TransformPreview(DiskTreeTransform):
 
1710
    """A TreeTransform for generating preview trees.
 
1711
 
 
1712
    Unlike TreeTransform, this version works when the input tree is a
 
1713
    RevisionTree, rather than a WorkingTree.  As a result, it tends to ignore
 
1714
    unversioned files in the input tree.
 
1715
    """
 
1716
 
 
1717
    def __init__(self, tree, pb=None, case_sensitive=True):
 
1718
        tree.lock_read()
 
1719
        limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
 
1720
        DiskTreeTransform.__init__(self, tree, limbodir, pb, case_sensitive)
 
1721
 
 
1722
    def canonical_path(self, path):
 
1723
        return path
 
1724
 
 
1725
    def tree_kind(self, trans_id):
 
1726
        path = self._tree_id_paths.get(trans_id)
 
1727
        if path is None:
 
1728
            raise NoSuchFile(None)
 
1729
        file_id = self._tree.path2id(path)
 
1730
        return self._tree.kind(file_id)
 
1731
 
 
1732
    def _set_mode(self, trans_id, mode_id, typefunc):
 
1733
        """Set the mode of new file contents.
 
1734
        The mode_id is the existing file to get the mode from (often the same
 
1735
        as trans_id).  The operation is only performed if there's a mode match
 
1736
        according to typefunc.
 
1737
        """
 
1738
        # is it ok to ignore this?  probably
 
1739
        pass
 
1740
 
 
1741
    def iter_tree_children(self, parent_id):
 
1742
        """Iterate through the entry's tree children, if any"""
 
1743
        try:
 
1744
            path = self._tree_id_paths[parent_id]
 
1745
        except KeyError:
 
1746
            return
 
1747
        file_id = self.tree_file_id(parent_id)
 
1748
        if file_id is None:
 
1749
            return
 
1750
        entry = self._tree.iter_entries_by_dir([file_id]).next()[1]
 
1751
        children = getattr(entry, 'children', {})
 
1752
        for child in children:
 
1753
            childpath = joinpath(path, child)
 
1754
            yield self.trans_id_tree_path(childpath)
 
1755
 
 
1756
 
 
1757
class _PreviewTree(tree.Tree):
 
1758
    """Partial implementation of Tree to support show_diff_trees"""
 
1759
 
 
1760
    def __init__(self, transform):
 
1761
        self._transform = transform
 
1762
        self._final_paths = FinalPaths(transform)
 
1763
        self.__by_parent = None
 
1764
        self._parent_ids = []
 
1765
        self._all_children_cache = {}
 
1766
        self._path2trans_id_cache = {}
 
1767
        self._final_name_cache = {}
 
1768
        self._iter_changes_cache = dict((c[0], c) for c in
 
1769
                                        self._transform.iter_changes())
 
1770
 
 
1771
    def _content_change(self, file_id):
 
1772
        """Return True if the content of this file changed"""
 
1773
        changes = self._iter_changes_cache.get(file_id)
 
1774
        # changes[2] is true if the file content changed.  See
 
1775
        # InterTree.iter_changes.
 
1776
        return (changes is not None and changes[2])
 
1777
 
 
1778
    def _get_repository(self):
 
1779
        repo = getattr(self._transform._tree, '_repository', None)
 
1780
        if repo is None:
 
1781
            repo = self._transform._tree.branch.repository
 
1782
        return repo
 
1783
 
 
1784
    def _iter_parent_trees(self):
 
1785
        for revision_id in self.get_parent_ids():
 
1786
            try:
 
1787
                yield self.revision_tree(revision_id)
 
1788
            except errors.NoSuchRevisionInTree:
 
1789
                yield self._get_repository().revision_tree(revision_id)
 
1790
 
 
1791
    def _get_file_revision(self, file_id, vf, tree_revision):
 
1792
        parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
 
1793
                       self._iter_parent_trees()]
 
1794
        vf.add_lines((file_id, tree_revision), parent_keys,
 
1795
                     self.get_file_lines(file_id))
 
1796
        repo = self._get_repository()
 
1797
        base_vf = repo.texts
 
1798
        if base_vf not in vf.fallback_versionedfiles:
 
1799
            vf.fallback_versionedfiles.append(base_vf)
 
1800
        return tree_revision
 
1801
 
 
1802
    def _stat_limbo_file(self, file_id):
 
1803
        trans_id = self._transform.trans_id_file_id(file_id)
 
1804
        name = self._transform._limbo_name(trans_id)
 
1805
        return os.lstat(name)
 
1806
 
 
1807
    @property
 
1808
    def _by_parent(self):
 
1809
        if self.__by_parent is None:
 
1810
            self.__by_parent = self._transform.by_parent()
 
1811
        return self.__by_parent
 
1812
 
 
1813
    def _comparison_data(self, entry, path):
 
1814
        kind, size, executable, link_or_sha1 = self.path_content_summary(path)
 
1815
        if kind == 'missing':
 
1816
            kind = None
 
1817
            executable = False
 
1818
        else:
 
1819
            file_id = self._transform.final_file_id(self._path2trans_id(path))
 
1820
            executable = self.is_executable(file_id, path)
 
1821
        return kind, executable, None
 
1822
 
 
1823
    def is_locked(self):
 
1824
        return False
 
1825
 
 
1826
    def lock_read(self):
 
1827
        # Perhaps in theory, this should lock the TreeTransform?
 
1828
        return self
 
1829
 
 
1830
    def unlock(self):
 
1831
        pass
 
1832
 
 
1833
    @property
 
1834
    def inventory(self):
 
1835
        """This Tree does not use inventory as its backing data."""
 
1836
        raise NotImplementedError(_PreviewTree.inventory)
 
1837
 
 
1838
    def get_root_id(self):
 
1839
        return self._transform.final_file_id(self._transform.root)
 
1840
 
 
1841
    def all_file_ids(self):
 
1842
        tree_ids = set(self._transform._tree.all_file_ids())
 
1843
        tree_ids.difference_update(self._transform.tree_file_id(t)
 
1844
                                   for t in self._transform._removed_id)
 
1845
        tree_ids.update(self._transform._new_id.values())
 
1846
        return tree_ids
 
1847
 
 
1848
    def __iter__(self):
 
1849
        return iter(self.all_file_ids())
 
1850
 
 
1851
    def _has_id(self, file_id, fallback_check):
 
1852
        if file_id in self._transform._r_new_id:
 
1853
            return True
 
1854
        elif file_id in set([self._transform.tree_file_id(trans_id) for
 
1855
            trans_id in self._transform._removed_id]):
 
1856
            return False
 
1857
        else:
 
1858
            return fallback_check(file_id)
 
1859
 
 
1860
    def has_id(self, file_id):
 
1861
        return self._has_id(file_id, self._transform._tree.has_id)
 
1862
 
 
1863
    def has_or_had_id(self, file_id):
 
1864
        return self._has_id(file_id, self._transform._tree.has_or_had_id)
 
1865
 
 
1866
    def _path2trans_id(self, path):
 
1867
        # We must not use None here, because that is a valid value to store.
 
1868
        trans_id = self._path2trans_id_cache.get(path, object)
 
1869
        if trans_id is not object:
 
1870
            return trans_id
 
1871
        segments = splitpath(path)
 
1872
        cur_parent = self._transform.root
 
1873
        for cur_segment in segments:
 
1874
            for child in self._all_children(cur_parent):
 
1875
                final_name = self._final_name_cache.get(child)
 
1876
                if final_name is None:
 
1877
                    final_name = self._transform.final_name(child)
 
1878
                    self._final_name_cache[child] = final_name
 
1879
                if final_name == cur_segment:
 
1880
                    cur_parent = child
 
1881
                    break
 
1882
            else:
 
1883
                self._path2trans_id_cache[path] = None
 
1884
                return None
 
1885
        self._path2trans_id_cache[path] = cur_parent
 
1886
        return cur_parent
 
1887
 
 
1888
    def path2id(self, path):
 
1889
        return self._transform.final_file_id(self._path2trans_id(path))
 
1890
 
 
1891
    def id2path(self, file_id):
 
1892
        trans_id = self._transform.trans_id_file_id(file_id)
 
1893
        try:
 
1894
            return self._final_paths._determine_path(trans_id)
 
1895
        except NoFinalPath:
 
1896
            raise errors.NoSuchId(self, file_id)
 
1897
 
 
1898
    def _all_children(self, trans_id):
 
1899
        children = self._all_children_cache.get(trans_id)
 
1900
        if children is not None:
 
1901
            return children
 
1902
        children = set(self._transform.iter_tree_children(trans_id))
 
1903
        # children in the _new_parent set are provided by _by_parent.
 
1904
        children.difference_update(self._transform._new_parent.keys())
 
1905
        children.update(self._by_parent.get(trans_id, []))
 
1906
        self._all_children_cache[trans_id] = children
 
1907
        return children
 
1908
 
 
1909
    def iter_children(self, file_id):
 
1910
        trans_id = self._transform.trans_id_file_id(file_id)
 
1911
        for child_trans_id in self._all_children(trans_id):
 
1912
            yield self._transform.final_file_id(child_trans_id)
 
1913
 
 
1914
    def extras(self):
 
1915
        possible_extras = set(self._transform.trans_id_tree_path(p) for p
 
1916
                              in self._transform._tree.extras())
 
1917
        possible_extras.update(self._transform._new_contents)
 
1918
        possible_extras.update(self._transform._removed_id)
 
1919
        for trans_id in possible_extras:
 
1920
            if self._transform.final_file_id(trans_id) is None:
 
1921
                yield self._final_paths._determine_path(trans_id)
 
1922
 
 
1923
    def _make_inv_entries(self, ordered_entries, specific_file_ids=None,
 
1924
        yield_parents=False):
 
1925
        for trans_id, parent_file_id in ordered_entries:
 
1926
            file_id = self._transform.final_file_id(trans_id)
 
1927
            if file_id is None:
 
1928
                continue
 
1929
            if (specific_file_ids is not None
 
1930
                and file_id not in specific_file_ids):
 
1931
                continue
 
1932
            try:
 
1933
                kind = self._transform.final_kind(trans_id)
 
1934
            except NoSuchFile:
 
1935
                kind = self._transform._tree.stored_kind(file_id)
 
1936
            new_entry = inventory.make_entry(
 
1937
                kind,
 
1938
                self._transform.final_name(trans_id),
 
1939
                parent_file_id, file_id)
 
1940
            yield new_entry, trans_id
 
1941
 
 
1942
    def _list_files_by_dir(self):
 
1943
        todo = [ROOT_PARENT]
 
1944
        ordered_ids = []
 
1945
        while len(todo) > 0:
 
1946
            parent = todo.pop()
 
1947
            parent_file_id = self._transform.final_file_id(parent)
 
1948
            children = list(self._all_children(parent))
 
1949
            paths = dict(zip(children, self._final_paths.get_paths(children)))
 
1950
            children.sort(key=paths.get)
 
1951
            todo.extend(reversed(children))
 
1952
            for trans_id in children:
 
1953
                ordered_ids.append((trans_id, parent_file_id))
 
1954
        return ordered_ids
 
1955
 
 
1956
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
 
1957
        # This may not be a maximally efficient implementation, but it is
 
1958
        # reasonably straightforward.  An implementation that grafts the
 
1959
        # TreeTransform changes onto the tree's iter_entries_by_dir results
 
1960
        # might be more efficient, but requires tricky inferences about stack
 
1961
        # position.
 
1962
        ordered_ids = self._list_files_by_dir()
 
1963
        for entry, trans_id in self._make_inv_entries(ordered_ids,
 
1964
            specific_file_ids, yield_parents=yield_parents):
 
1965
            yield unicode(self._final_paths.get_path(trans_id)), entry
 
1966
 
 
1967
    def _iter_entries_for_dir(self, dir_path):
 
1968
        """Return path, entry for items in a directory without recursing down."""
 
1969
        dir_file_id = self.path2id(dir_path)
 
1970
        ordered_ids = []
 
1971
        for file_id in self.iter_children(dir_file_id):
 
1972
            trans_id = self._transform.trans_id_file_id(file_id)
 
1973
            ordered_ids.append((trans_id, file_id))
 
1974
        for entry, trans_id in self._make_inv_entries(ordered_ids):
 
1975
            yield unicode(self._final_paths.get_path(trans_id)), entry
 
1976
 
 
1977
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
1978
        """See WorkingTree.list_files."""
 
1979
        # XXX This should behave like WorkingTree.list_files, but is really
 
1980
        # more like RevisionTree.list_files.
 
1981
        if recursive:
 
1982
            prefix = None
 
1983
            if from_dir:
 
1984
                prefix = from_dir + '/'
 
1985
            entries = self.iter_entries_by_dir()
 
1986
            for path, entry in entries:
 
1987
                if entry.name == '' and not include_root:
 
1988
                    continue
 
1989
                if prefix:
 
1990
                    if not path.startswith(prefix):
 
1991
                        continue
 
1992
                    path = path[len(prefix):]
 
1993
                yield path, 'V', entry.kind, entry.file_id, entry
 
1994
        else:
 
1995
            if from_dir is None and include_root is True:
 
1996
                root_entry = inventory.make_entry('directory', '',
 
1997
                    ROOT_PARENT, self.get_root_id())
 
1998
                yield '', 'V', 'directory', root_entry.file_id, root_entry
 
1999
            entries = self._iter_entries_for_dir(from_dir or '')
 
2000
            for path, entry in entries:
 
2001
                yield path, 'V', entry.kind, entry.file_id, entry
 
2002
 
 
2003
    def kind(self, file_id):
 
2004
        trans_id = self._transform.trans_id_file_id(file_id)
 
2005
        return self._transform.final_kind(trans_id)
 
2006
 
 
2007
    def stored_kind(self, file_id):
 
2008
        trans_id = self._transform.trans_id_file_id(file_id)
 
2009
        try:
 
2010
            return self._transform._new_contents[trans_id]
 
2011
        except KeyError:
 
2012
            return self._transform._tree.stored_kind(file_id)
 
2013
 
 
2014
    def get_file_mtime(self, file_id, path=None):
 
2015
        """See Tree.get_file_mtime"""
 
2016
        if not self._content_change(file_id):
 
2017
            return self._transform._tree.get_file_mtime(file_id)
 
2018
        return self._stat_limbo_file(file_id).st_mtime
 
2019
 
 
2020
    def _file_size(self, entry, stat_value):
 
2021
        return self.get_file_size(entry.file_id)
 
2022
 
 
2023
    def get_file_size(self, file_id):
 
2024
        """See Tree.get_file_size"""
 
2025
        if self.kind(file_id) == 'file':
 
2026
            return self._transform._tree.get_file_size(file_id)
 
2027
        else:
 
2028
            return None
 
2029
 
 
2030
    def get_file_sha1(self, file_id, path=None, stat_value=None):
 
2031
        trans_id = self._transform.trans_id_file_id(file_id)
 
2032
        kind = self._transform._new_contents.get(trans_id)
 
2033
        if kind is None:
 
2034
            return self._transform._tree.get_file_sha1(file_id)
 
2035
        if kind == 'file':
 
2036
            fileobj = self.get_file(file_id)
 
2037
            try:
 
2038
                return sha_file(fileobj)
 
2039
            finally:
 
2040
                fileobj.close()
 
2041
 
 
2042
    def is_executable(self, file_id, path=None):
 
2043
        if file_id is None:
 
2044
            return False
 
2045
        trans_id = self._transform.trans_id_file_id(file_id)
 
2046
        try:
 
2047
            return self._transform._new_executability[trans_id]
 
2048
        except KeyError:
 
2049
            try:
 
2050
                return self._transform._tree.is_executable(file_id, path)
 
2051
            except OSError, e:
 
2052
                if e.errno == errno.ENOENT:
 
2053
                    return False
 
2054
                raise
 
2055
            except errors.NoSuchId:
 
2056
                return False
 
2057
 
 
2058
    def path_content_summary(self, path):
 
2059
        trans_id = self._path2trans_id(path)
 
2060
        tt = self._transform
 
2061
        tree_path = tt._tree_id_paths.get(trans_id)
 
2062
        kind = tt._new_contents.get(trans_id)
 
2063
        if kind is None:
 
2064
            if tree_path is None or trans_id in tt._removed_contents:
 
2065
                return 'missing', None, None, None
 
2066
            summary = tt._tree.path_content_summary(tree_path)
 
2067
            kind, size, executable, link_or_sha1 = summary
 
2068
        else:
 
2069
            link_or_sha1 = None
 
2070
            limbo_name = tt._limbo_name(trans_id)
 
2071
            if trans_id in tt._new_reference_revision:
 
2072
                kind = 'tree-reference'
 
2073
            if kind == 'file':
 
2074
                statval = os.lstat(limbo_name)
 
2075
                size = statval.st_size
 
2076
                if not supports_executable():
 
2077
                    executable = False
 
2078
                else:
 
2079
                    executable = statval.st_mode & S_IEXEC
 
2080
            else:
 
2081
                size = None
 
2082
                executable = None
 
2083
            if kind == 'symlink':
 
2084
                link_or_sha1 = os.readlink(limbo_name).decode(osutils._fs_enc)
 
2085
        executable = tt._new_executability.get(trans_id, executable)
 
2086
        return kind, size, executable, link_or_sha1
 
2087
 
 
2088
    def iter_changes(self, from_tree, include_unchanged=False,
 
2089
                      specific_files=None, pb=None, extra_trees=None,
 
2090
                      require_versioned=True, want_unversioned=False):
 
2091
        """See InterTree.iter_changes.
 
2092
 
 
2093
        This has a fast path that is only used when the from_tree matches
 
2094
        the transform tree, and no fancy options are supplied.
 
2095
        """
 
2096
        if (from_tree is not self._transform._tree or include_unchanged or
 
2097
            specific_files or want_unversioned):
 
2098
            return tree.InterTree(from_tree, self).iter_changes(
 
2099
                include_unchanged=include_unchanged,
 
2100
                specific_files=specific_files,
 
2101
                pb=pb,
 
2102
                extra_trees=extra_trees,
 
2103
                require_versioned=require_versioned,
 
2104
                want_unversioned=want_unversioned)
 
2105
        if want_unversioned:
 
2106
            raise ValueError('want_unversioned is not supported')
 
2107
        return self._transform.iter_changes()
 
2108
 
 
2109
    def get_file(self, file_id, path=None):
 
2110
        """See Tree.get_file"""
 
2111
        if not self._content_change(file_id):
 
2112
            return self._transform._tree.get_file(file_id, path)
 
2113
        trans_id = self._transform.trans_id_file_id(file_id)
 
2114
        name = self._transform._limbo_name(trans_id)
 
2115
        return open(name, 'rb')
 
2116
 
 
2117
    def get_file_with_stat(self, file_id, path=None):
 
2118
        return self.get_file(file_id, path), None
 
2119
 
 
2120
    def annotate_iter(self, file_id,
 
2121
                      default_revision=_mod_revision.CURRENT_REVISION):
 
2122
        changes = self._iter_changes_cache.get(file_id)
 
2123
        if changes is None:
 
2124
            get_old = True
 
2125
        else:
 
2126
            changed_content, versioned, kind = (changes[2], changes[3],
 
2127
                                                changes[6])
 
2128
            if kind[1] is None:
 
2129
                return None
 
2130
            get_old = (kind[0] == 'file' and versioned[0])
 
2131
        if get_old:
 
2132
            old_annotation = self._transform._tree.annotate_iter(file_id,
 
2133
                default_revision=default_revision)
 
2134
        else:
 
2135
            old_annotation = []
 
2136
        if changes is None:
 
2137
            return old_annotation
 
2138
        if not changed_content:
 
2139
            return old_annotation
 
2140
        # TODO: This is doing something similar to what WT.annotate_iter is
 
2141
        #       doing, however it fails slightly because it doesn't know what
 
2142
        #       the *other* revision_id is, so it doesn't know how to give the
 
2143
        #       other as the origin for some lines, they all get
 
2144
        #       'default_revision'
 
2145
        #       It would be nice to be able to use the new Annotator based
 
2146
        #       approach, as well.
 
2147
        return annotate.reannotate([old_annotation],
 
2148
                                   self.get_file(file_id).readlines(),
 
2149
                                   default_revision)
 
2150
 
 
2151
    def get_symlink_target(self, file_id):
 
2152
        """See Tree.get_symlink_target"""
 
2153
        if not self._content_change(file_id):
 
2154
            return self._transform._tree.get_symlink_target(file_id)
 
2155
        trans_id = self._transform.trans_id_file_id(file_id)
 
2156
        name = self._transform._limbo_name(trans_id)
 
2157
        return osutils.readlink(name)
 
2158
 
 
2159
    def walkdirs(self, prefix=''):
 
2160
        pending = [self._transform.root]
 
2161
        while len(pending) > 0:
 
2162
            parent_id = pending.pop()
 
2163
            children = []
 
2164
            subdirs = []
 
2165
            prefix = prefix.rstrip('/')
 
2166
            parent_path = self._final_paths.get_path(parent_id)
 
2167
            parent_file_id = self._transform.final_file_id(parent_id)
 
2168
            for child_id in self._all_children(parent_id):
 
2169
                path_from_root = self._final_paths.get_path(child_id)
 
2170
                basename = self._transform.final_name(child_id)
 
2171
                file_id = self._transform.final_file_id(child_id)
 
2172
                try:
 
2173
                    kind = self._transform.final_kind(child_id)
 
2174
                    versioned_kind = kind
 
2175
                except NoSuchFile:
 
2176
                    kind = 'unknown'
 
2177
                    versioned_kind = self._transform._tree.stored_kind(file_id)
 
2178
                if versioned_kind == 'directory':
 
2179
                    subdirs.append(child_id)
 
2180
                children.append((path_from_root, basename, kind, None,
 
2181
                                 file_id, versioned_kind))
 
2182
            children.sort()
 
2183
            if parent_path.startswith(prefix):
 
2184
                yield (parent_path, parent_file_id), children
 
2185
            pending.extend(sorted(subdirs, key=self._final_paths.get_path,
 
2186
                                  reverse=True))
 
2187
 
 
2188
    def get_parent_ids(self):
 
2189
        return self._parent_ids
 
2190
 
 
2191
    def set_parent_ids(self, parent_ids):
 
2192
        self._parent_ids = parent_ids
 
2193
 
 
2194
    def get_revision_tree(self, revision_id):
 
2195
        return self._transform._tree.get_revision_tree(revision_id)
 
2196
 
1204
2197
 
1205
2198
def joinpath(parent, child):
1206
2199
    """Join tree-relative paths, handling the tree root specially"""
1222
2215
        self.transform = transform
1223
2216
 
1224
2217
    def _determine_path(self, trans_id):
1225
 
        if trans_id == self.transform.root:
 
2218
        if (trans_id == self.transform.root or trans_id == ROOT_PARENT):
1226
2219
            return ""
1227
2220
        name = self.transform.final_name(trans_id)
1228
2221
        parent_id = self.transform.final_parent(trans_id)
1237
2230
            self._known_paths[trans_id] = self._determine_path(trans_id)
1238
2231
        return self._known_paths[trans_id]
1239
2232
 
 
2233
    def get_paths(self, trans_ids):
 
2234
        return [(self.get_path(t), t) for t in trans_ids]
 
2235
 
 
2236
 
 
2237
 
1240
2238
def topology_sorted_ids(tree):
1241
2239
    """Determine the topological order of the ids in a tree"""
1242
2240
    file_ids = list(tree)
1244
2242
    return file_ids
1245
2243
 
1246
2244
 
1247
 
def build_tree(tree, wt):
 
2245
def build_tree(tree, wt, accelerator_tree=None, hardlink=False,
 
2246
               delta_from_tree=False):
1248
2247
    """Create working tree for a branch, using a TreeTransform.
1249
 
    
 
2248
 
1250
2249
    This function should be used on empty trees, having a tree root at most.
1251
2250
    (see merge and revert functionality for working with existing trees)
1252
2251
 
1253
2252
    Existing files are handled like so:
1254
 
    
 
2253
 
1255
2254
    - Existing bzrdirs take precedence over creating new items.  They are
1256
2255
      created as '%s.diverted' % name.
1257
2256
    - Otherwise, if the content on disk matches the content we are building,
1258
2257
      it is silently replaced.
1259
2258
    - Otherwise, conflict resolution will move the old file to 'oldname.moved'.
 
2259
 
 
2260
    :param tree: The tree to convert wt into a copy of
 
2261
    :param wt: The working tree that files will be placed into
 
2262
    :param accelerator_tree: A tree which can be used for retrieving file
 
2263
        contents more quickly than tree itself, i.e. a workingtree.  tree
 
2264
        will be used for cases where accelerator_tree's content is different.
 
2265
    :param hardlink: If true, hard-link files to accelerator_tree, where
 
2266
        possible.  accelerator_tree must implement abspath, i.e. be a
 
2267
        working tree.
 
2268
    :param delta_from_tree: If true, build_tree may use the input Tree to
 
2269
        generate the inventory delta.
1260
2270
    """
1261
2271
    wt.lock_tree_write()
1262
2272
    try:
1263
2273
        tree.lock_read()
1264
2274
        try:
1265
 
            return _build_tree(tree, wt)
 
2275
            if accelerator_tree is not None:
 
2276
                accelerator_tree.lock_read()
 
2277
            try:
 
2278
                return _build_tree(tree, wt, accelerator_tree, hardlink,
 
2279
                                   delta_from_tree)
 
2280
            finally:
 
2281
                if accelerator_tree is not None:
 
2282
                    accelerator_tree.unlock()
1266
2283
        finally:
1267
2284
            tree.unlock()
1268
2285
    finally:
1269
2286
        wt.unlock()
1270
2287
 
1271
 
def _build_tree(tree, wt):
 
2288
 
 
2289
def _build_tree(tree, wt, accelerator_tree, hardlink, delta_from_tree):
1272
2290
    """See build_tree."""
1273
 
    if len(wt.inventory) > 1:  # more than just a root
1274
 
        raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
 
2291
    for num, _unused in enumerate(wt.all_file_ids()):
 
2292
        if num > 0:  # more than just a root
 
2293
            raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
 
2294
    existing_files = set()
 
2295
    for dir, files in wt.walkdirs():
 
2296
        existing_files.update(f[0] for f in files)
1275
2297
    file_trans_id = {}
1276
2298
    top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1277
2299
    pp = ProgressPhase("Build phase", 2, top_pb)
1283
2305
        # is set within the tree, nor setting the root and thus
1284
2306
        # marking the tree as dirty, because we use two different
1285
2307
        # idioms here: tree interfaces and inventory interfaces.
1286
 
        if wt.path2id('') != tree.inventory.root.file_id:
1287
 
            wt.set_root_id(tree.inventory.root.file_id)
 
2308
        if wt.get_root_id() != tree.get_root_id():
 
2309
            wt.set_root_id(tree.get_root_id())
1288
2310
            wt.flush()
1289
2311
    tt = TreeTransform(wt)
1290
2312
    divert = set()
1295
2317
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1296
2318
        try:
1297
2319
            deferred_contents = []
 
2320
            num = 0
 
2321
            total = len(tree.inventory)
 
2322
            if delta_from_tree:
 
2323
                precomputed_delta = []
 
2324
            else:
 
2325
                precomputed_delta = None
1298
2326
            for num, (tree_path, entry) in \
1299
2327
                enumerate(tree.inventory.iter_entries_by_dir()):
1300
 
                pb.update("Building tree", num - len(deferred_contents),
1301
 
                          len(tree.inventory))
 
2328
                pb.update("Building tree", num - len(deferred_contents), total)
1302
2329
                if entry.parent_id is None:
1303
2330
                    continue
1304
2331
                reparent = False
1305
2332
                file_id = entry.file_id
1306
 
                target_path = wt.abspath(tree_path)
1307
 
                try:
 
2333
                if delta_from_tree:
 
2334
                    precomputed_delta.append((None, tree_path, file_id, entry))
 
2335
                if tree_path in existing_files:
 
2336
                    target_path = wt.abspath(tree_path)
1308
2337
                    kind = file_kind(target_path)
1309
 
                except NoSuchFile:
1310
 
                    pass
1311
 
                else:
1312
2338
                    if kind == "directory":
1313
2339
                        try:
1314
2340
                            bzrdir.BzrDir.open(target_path)
1322
2348
                        tt.delete_contents(tt.trans_id_tree_path(tree_path))
1323
2349
                        if kind == 'directory':
1324
2350
                            reparent = True
1325
 
                if entry.parent_id not in file_trans_id:
1326
 
                    raise AssertionError(
1327
 
                        'entry %s parent id %r is not in file_trans_id %r'
1328
 
                        % (entry, entry.parent_id, file_trans_id))
1329
2351
                parent_id = file_trans_id[entry.parent_id]
1330
2352
                if entry.kind == 'file':
1331
2353
                    # We *almost* replicate new_by_entry, so that we can defer
1332
2354
                    # getting the file text, and get them all at once.
1333
2355
                    trans_id = tt.create_path(entry.name, parent_id)
1334
2356
                    file_trans_id[file_id] = trans_id
1335
 
                    tt.version_file(entry.file_id, trans_id)
1336
 
                    executable = tree.is_executable(entry.file_id, tree_path)
1337
 
                    if executable is not None:
 
2357
                    tt.version_file(file_id, trans_id)
 
2358
                    executable = tree.is_executable(file_id, tree_path)
 
2359
                    if executable:
1338
2360
                        tt.set_executability(executable, trans_id)
1339
 
                    deferred_contents.append((entry.file_id, trans_id))
 
2361
                    trans_data = (trans_id, tree_path)
 
2362
                    deferred_contents.append((file_id, trans_data))
1340
2363
                else:
1341
2364
                    file_trans_id[file_id] = new_by_entry(tt, entry, parent_id,
1342
2365
                                                          tree)
1344
2367
                    new_trans_id = file_trans_id[file_id]
1345
2368
                    old_parent = tt.trans_id_tree_path(tree_path)
1346
2369
                    _reparent_children(tt, old_parent, new_trans_id)
1347
 
            for num, (trans_id, bytes) in enumerate(
1348
 
                tree.iter_files_bytes(deferred_contents)):
1349
 
                tt.create_file(bytes, trans_id)
1350
 
                pb.update('Adding file contents',
1351
 
                          (num + len(tree.inventory) - len(deferred_contents)),
1352
 
                          len(tree.inventory))
 
2370
            offset = num + 1 - len(deferred_contents)
 
2371
            _create_files(tt, tree, deferred_contents, pb, offset,
 
2372
                          accelerator_tree, hardlink)
1353
2373
        finally:
1354
2374
            pb.finished()
1355
2375
        pp.next_phase()
1356
2376
        divert_trans = set(file_trans_id[f] for f in divert)
1357
2377
        resolver = lambda t, c: resolve_checkout(t, c, divert_trans)
1358
2378
        raw_conflicts = resolve_conflicts(tt, pass_func=resolver)
 
2379
        if len(raw_conflicts) > 0:
 
2380
            precomputed_delta = None
1359
2381
        conflicts = cook_conflicts(raw_conflicts, tt)
1360
2382
        for conflict in conflicts:
1361
2383
            warning(conflict)
1363
2385
            wt.add_conflicts(conflicts)
1364
2386
        except errors.UnsupportedOperation:
1365
2387
            pass
1366
 
        result = tt.apply()
 
2388
        result = tt.apply(no_conflicts=True,
 
2389
                          precomputed_delta=precomputed_delta)
1367
2390
    finally:
1368
2391
        tt.finalize()
1369
2392
        top_pb.finished()
1370
2393
    return result
1371
2394
 
1372
2395
 
 
2396
def _create_files(tt, tree, desired_files, pb, offset, accelerator_tree,
 
2397
                  hardlink):
 
2398
    total = len(desired_files) + offset
 
2399
    wt = tt._tree
 
2400
    if accelerator_tree is None:
 
2401
        new_desired_files = desired_files
 
2402
    else:
 
2403
        iter = accelerator_tree.iter_changes(tree, include_unchanged=True)
 
2404
        unchanged = [(f, p[1]) for (f, p, c, v, d, n, k, e)
 
2405
                     in iter if not (c or e[0] != e[1])]
 
2406
        if accelerator_tree.supports_content_filtering():
 
2407
            unchanged = [(f, p) for (f, p) in unchanged
 
2408
                         if not accelerator_tree.iter_search_rules([p]).next()]
 
2409
        unchanged = dict(unchanged)
 
2410
        new_desired_files = []
 
2411
        count = 0
 
2412
        for file_id, (trans_id, tree_path) in desired_files:
 
2413
            accelerator_path = unchanged.get(file_id)
 
2414
            if accelerator_path is None:
 
2415
                new_desired_files.append((file_id, (trans_id, tree_path)))
 
2416
                continue
 
2417
            pb.update('Adding file contents', count + offset, total)
 
2418
            if hardlink:
 
2419
                tt.create_hardlink(accelerator_tree.abspath(accelerator_path),
 
2420
                                   trans_id)
 
2421
            else:
 
2422
                contents = accelerator_tree.get_file(file_id, accelerator_path)
 
2423
                if wt.supports_content_filtering():
 
2424
                    filters = wt._content_filter_stack(tree_path)
 
2425
                    contents = filtered_output_bytes(contents, filters,
 
2426
                        ContentFilterContext(tree_path, tree))
 
2427
                try:
 
2428
                    tt.create_file(contents, trans_id)
 
2429
                finally:
 
2430
                    try:
 
2431
                        contents.close()
 
2432
                    except AttributeError:
 
2433
                        # after filtering, contents may no longer be file-like
 
2434
                        pass
 
2435
            count += 1
 
2436
        offset += count
 
2437
    for count, ((trans_id, tree_path), contents) in enumerate(
 
2438
            tree.iter_files_bytes(new_desired_files)):
 
2439
        if wt.supports_content_filtering():
 
2440
            filters = wt._content_filter_stack(tree_path)
 
2441
            contents = filtered_output_bytes(contents, filters,
 
2442
                ContentFilterContext(tree_path, tree))
 
2443
        tt.create_file(contents, trans_id)
 
2444
        pb.update('Adding file contents', count + offset, total)
 
2445
 
 
2446
 
1373
2447
def _reparent_children(tt, old_parent, new_parent):
1374
2448
    for child in tt.iter_tree_children(old_parent):
1375
2449
        tt.adjust_path(tt.final_name(child), new_parent, child)
1376
2450
 
 
2451
def _reparent_transform_children(tt, old_parent, new_parent):
 
2452
    by_parent = tt.by_parent()
 
2453
    for child in by_parent[old_parent]:
 
2454
        tt.adjust_path(tt.final_name(child), new_parent, child)
 
2455
    return by_parent[old_parent]
1377
2456
 
1378
2457
def _content_match(tree, entry, file_id, kind, target_path):
1379
2458
    if entry.kind != kind:
1381
2460
    if entry.kind == "directory":
1382
2461
        return True
1383
2462
    if entry.kind == "file":
1384
 
        if tree.get_file(file_id).read() == file(target_path, 'rb').read():
1385
 
            return True
 
2463
        f = file(target_path, 'rb')
 
2464
        try:
 
2465
            if tree.get_file_text(file_id) == f.read():
 
2466
                return True
 
2467
        finally:
 
2468
            f.close()
1386
2469
    elif entry.kind == "symlink":
1387
2470
        if tree.get_symlink_target(file_id) == os.readlink(target_path):
1388
2471
            return True
1393
2476
    new_conflicts = set()
1394
2477
    for c_type, conflict in ((c[0], c) for c in conflicts):
1395
2478
        # Anything but a 'duplicate' would indicate programmer error
1396
 
        assert c_type == 'duplicate', c_type
 
2479
        if c_type != 'duplicate':
 
2480
            raise AssertionError(c_type)
1397
2481
        # Now figure out which is new and which is old
1398
2482
        if tt.new_contents(conflict[1]):
1399
2483
            new_file = conflict[1]
1425
2509
    if kind == 'file':
1426
2510
        contents = tree.get_file(entry.file_id).readlines()
1427
2511
        executable = tree.is_executable(entry.file_id)
1428
 
        return tt.new_file(name, parent_id, contents, entry.file_id, 
 
2512
        return tt.new_file(name, parent_id, contents, entry.file_id,
1429
2513
                           executable)
1430
2514
    elif kind in ('directory', 'tree-reference'):
1431
2515
        trans_id = tt.new_directory(name, parent_id, entry.file_id)
1432
2516
        if kind == 'tree-reference':
1433
2517
            tt.set_tree_reference(entry.reference_revision, trans_id)
1434
 
        return trans_id 
 
2518
        return trans_id
1435
2519
    elif kind == 'symlink':
1436
2520
        target = tree.get_symlink_target(entry.file_id)
1437
2521
        return tt.new_symlink(name, parent_id, target, entry.file_id)
1438
2522
    else:
1439
2523
        raise errors.BadFileKindError(name, kind)
1440
2524
 
 
2525
 
 
2526
@deprecated_function(deprecated_in((1, 9, 0)))
1441
2527
def create_by_entry(tt, entry, tree, trans_id, lines=None, mode_id=None):
1442
 
    """Create new file contents according to an inventory entry."""
 
2528
    """Create new file contents according to an inventory entry.
 
2529
 
 
2530
    DEPRECATED.  Use create_from_tree instead.
 
2531
    """
1443
2532
    if entry.kind == "file":
1444
2533
        if lines is None:
1445
2534
            lines = tree.get_file(entry.file_id).readlines()
1449
2538
    elif entry.kind == "directory":
1450
2539
        tt.create_directory(trans_id)
1451
2540
 
 
2541
 
 
2542
def create_from_tree(tt, trans_id, tree, file_id, bytes=None,
 
2543
    filter_tree_path=None):
 
2544
    """Create new file contents according to tree contents.
 
2545
    
 
2546
    :param filter_tree_path: the tree path to use to lookup
 
2547
      content filters to apply to the bytes output in the working tree.
 
2548
      This only applies if the working tree supports content filtering.
 
2549
    """
 
2550
    kind = tree.kind(file_id)
 
2551
    if kind == 'directory':
 
2552
        tt.create_directory(trans_id)
 
2553
    elif kind == "file":
 
2554
        if bytes is None:
 
2555
            tree_file = tree.get_file(file_id)
 
2556
            try:
 
2557
                bytes = tree_file.readlines()
 
2558
            finally:
 
2559
                tree_file.close()
 
2560
        wt = tt._tree
 
2561
        if wt.supports_content_filtering() and filter_tree_path is not None:
 
2562
            filters = wt._content_filter_stack(filter_tree_path)
 
2563
            bytes = filtered_output_bytes(bytes, filters,
 
2564
                ContentFilterContext(filter_tree_path, tree))
 
2565
        tt.create_file(bytes, trans_id)
 
2566
    elif kind == "symlink":
 
2567
        tt.create_symlink(tree.get_symlink_target(file_id), trans_id)
 
2568
    else:
 
2569
        raise AssertionError('Unknown kind %r' % kind)
 
2570
 
 
2571
 
1452
2572
def create_entry_executability(tt, entry, trans_id):
1453
2573
    """Set the executability of a trans_id according to an inventory entry"""
1454
2574
    if entry.kind == "file":
1455
2575
        tt.set_executability(entry.executable, trans_id)
1456
2576
 
1457
2577
 
1458
 
@deprecated_function(zero_fifteen)
1459
 
def find_interesting(working_tree, target_tree, filenames):
1460
 
    """Find the ids corresponding to specified filenames.
1461
 
    
1462
 
    Deprecated: Please use tree1.paths2ids(filenames, [tree2]).
1463
 
    """
1464
 
    working_tree.lock_read()
1465
 
    try:
1466
 
        target_tree.lock_read()
1467
 
        try:
1468
 
            return working_tree.paths2ids(filenames, [target_tree])
1469
 
        finally:
1470
 
            target_tree.unlock()
1471
 
    finally:
1472
 
        working_tree.unlock()
1473
 
 
1474
 
 
1475
 
@deprecated_function(zero_ninety)
1476
 
def change_entry(tt, file_id, working_tree, target_tree, 
1477
 
                 trans_id_file_id, backups, trans_id, by_parent):
1478
 
    """Replace a file_id's contents with those from a target tree."""
1479
 
    if file_id is None and target_tree is None:
1480
 
        # skip the logic altogether in the deprecation test
1481
 
        return
1482
 
    e_trans_id = trans_id_file_id(file_id)
1483
 
    entry = target_tree.inventory[file_id]
1484
 
    has_contents, contents_mod, meta_mod, = _entry_changes(file_id, entry, 
1485
 
                                                           working_tree)
1486
 
    if contents_mod:
1487
 
        mode_id = e_trans_id
1488
 
        if has_contents:
1489
 
            if not backups:
1490
 
                tt.delete_contents(e_trans_id)
1491
 
            else:
1492
 
                parent_trans_id = trans_id_file_id(entry.parent_id)
1493
 
                backup_name = get_backup_name(entry, by_parent,
1494
 
                                              parent_trans_id, tt)
1495
 
                tt.adjust_path(backup_name, parent_trans_id, e_trans_id)
1496
 
                tt.unversion_file(e_trans_id)
1497
 
                e_trans_id = tt.create_path(entry.name, parent_trans_id)
1498
 
                tt.version_file(file_id, e_trans_id)
1499
 
                trans_id[file_id] = e_trans_id
1500
 
        create_by_entry(tt, entry, target_tree, e_trans_id, mode_id=mode_id)
1501
 
        create_entry_executability(tt, entry, e_trans_id)
1502
 
 
1503
 
    elif meta_mod:
1504
 
        tt.set_executability(entry.executable, e_trans_id)
1505
 
    if tt.final_name(e_trans_id) != entry.name:
1506
 
        adjust_path  = True
1507
 
    else:
1508
 
        parent_id = tt.final_parent(e_trans_id)
1509
 
        parent_file_id = tt.final_file_id(parent_id)
1510
 
        if parent_file_id != entry.parent_id:
1511
 
            adjust_path = True
1512
 
        else:
1513
 
            adjust_path = False
1514
 
    if adjust_path:
1515
 
        parent_trans_id = trans_id_file_id(entry.parent_id)
1516
 
        tt.adjust_path(entry.name, parent_trans_id, e_trans_id)
1517
 
 
1518
 
 
1519
2578
def get_backup_name(entry, by_parent, parent_trans_id, tt):
1520
2579
    return _get_backup_name(entry.name, by_parent, parent_trans_id, tt)
1521
2580
 
1552
2611
        if entry.kind != working_kind:
1553
2612
            contents_mod, meta_mod = True, False
1554
2613
        else:
1555
 
            cur_entry._read_tree_state(working_tree.id2path(file_id), 
 
2614
            cur_entry._read_tree_state(working_tree.id2path(file_id),
1556
2615
                                       working_tree)
1557
2616
            contents_mod, meta_mod = entry.detect_changes(cur_entry)
1558
2617
            cur_entry._forget_tree_state()
1560
2619
 
1561
2620
 
1562
2621
def revert(working_tree, target_tree, filenames, backups=False,
1563
 
           pb=DummyProgress(), change_reporter=None):
 
2622
           pb=None, change_reporter=None):
1564
2623
    """Revert a working tree's contents to those of a target tree."""
1565
2624
    target_tree.lock_read()
 
2625
    pb = ui.ui_factory.nested_progress_bar()
1566
2626
    tt = TreeTransform(working_tree, pb)
1567
2627
    try:
1568
2628
        pp = ProgressPhase("Revert phase", 3, pb)
1569
 
        pp.next_phase()
1570
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1571
 
        try:
1572
 
            merge_modified = _alter_files(working_tree, target_tree, tt,
1573
 
                                          child_pb, filenames, backups)
1574
 
        finally:
1575
 
            child_pb.finished()
1576
 
        pp.next_phase()
1577
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1578
 
        try:
1579
 
            raw_conflicts = resolve_conflicts(tt, child_pb)
1580
 
        finally:
1581
 
            child_pb.finished()
1582
 
        conflicts = cook_conflicts(raw_conflicts, tt)
 
2629
        conflicts, merge_modified = _prepare_revert_transform(
 
2630
            working_tree, target_tree, tt, filenames, backups, pp)
1583
2631
        if change_reporter:
1584
2632
            change_reporter = delta._ChangeReporter(
1585
2633
                unversioned_filter=working_tree.is_ignored)
1586
 
            delta.report_changes(tt._iter_changes(), change_reporter)
 
2634
            delta.report_changes(tt.iter_changes(), change_reporter)
1587
2635
        for conflict in conflicts:
1588
2636
            warning(conflict)
1589
2637
        pp.next_phase()
1596
2644
    return conflicts
1597
2645
 
1598
2646
 
 
2647
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
 
2648
                              backups, pp, basis_tree=None,
 
2649
                              merge_modified=None):
 
2650
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
2651
    try:
 
2652
        if merge_modified is None:
 
2653
            merge_modified = working_tree.merge_modified()
 
2654
        merge_modified = _alter_files(working_tree, target_tree, tt,
 
2655
                                      child_pb, filenames, backups,
 
2656
                                      merge_modified, basis_tree)
 
2657
    finally:
 
2658
        child_pb.finished()
 
2659
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
2660
    try:
 
2661
        raw_conflicts = resolve_conflicts(tt, child_pb,
 
2662
            lambda t, c: conflict_pass(t, c, target_tree))
 
2663
    finally:
 
2664
        child_pb.finished()
 
2665
    conflicts = cook_conflicts(raw_conflicts, tt)
 
2666
    return conflicts, merge_modified
 
2667
 
 
2668
 
1599
2669
def _alter_files(working_tree, target_tree, tt, pb, specific_files,
1600
 
                 backups):
1601
 
    merge_modified = working_tree.merge_modified()
1602
 
    change_list = target_tree._iter_changes(working_tree,
 
2670
                 backups, merge_modified, basis_tree=None):
 
2671
    if basis_tree is not None:
 
2672
        basis_tree.lock_read()
 
2673
    change_list = target_tree.iter_changes(working_tree,
1603
2674
        specific_files=specific_files, pb=pb)
1604
 
    if target_tree.inventory.root is None:
 
2675
    if target_tree.get_root_id() is None:
1605
2676
        skip_root = True
1606
2677
    else:
1607
2678
        skip_root = False
1608
 
    basis_tree = None
1609
2679
    try:
1610
2680
        deferred_files = []
1611
2681
        for id_num, (file_id, path, changed_content, versioned, parent, name,
1647
2717
                        # contents
1648
2718
                        mode_id = trans_id
1649
2719
                        trans_id = new_trans_id
1650
 
                if kind[1] == 'directory':
 
2720
                if kind[1] in ('directory', 'tree-reference'):
1651
2721
                    tt.create_directory(trans_id)
 
2722
                    if kind[1] == 'tree-reference':
 
2723
                        revision = target_tree.get_reference_revision(file_id,
 
2724
                                                                      path[1])
 
2725
                        tt.set_tree_reference(revision, trans_id)
1652
2726
                elif kind[1] == 'symlink':
1653
2727
                    tt.create_symlink(target_tree.get_symlink_target(file_id),
1654
2728
                                      trans_id)
1668
2742
                    # preserve the execute bit when backing up
1669
2743
                    if keep_content and executable[0] == executable[1]:
1670
2744
                        tt.set_executability(executable[1], trans_id)
1671
 
                else:
1672
 
                    assert kind[1] is None
 
2745
                elif kind[1] is not None:
 
2746
                    raise AssertionError(kind[1])
1673
2747
            if versioned == (False, True):
1674
2748
                tt.version_file(file_id, trans_id)
1675
2749
            if versioned == (True, False):
1676
2750
                tt.unversion_file(trans_id)
1677
 
            if (name[1] is not None and 
 
2751
            if (name[1] is not None and
1678
2752
                (name[0] != name[1] or parent[0] != parent[1])):
1679
 
                tt.adjust_path(
1680
 
                    name[1], tt.trans_id_file_id(parent[1]), trans_id)
 
2753
                if name[1] == '' and parent[1] is None:
 
2754
                    parent_trans = ROOT_PARENT
 
2755
                else:
 
2756
                    parent_trans = tt.trans_id_file_id(parent[1])
 
2757
                if parent[0] is None and versioned[0]:
 
2758
                    tt.adjust_root_path(name[1], parent_trans)
 
2759
                else:
 
2760
                    tt.adjust_path(name[1], parent_trans, trans_id)
1681
2761
            if executable[0] != executable[1] and kind[1] == "file":
1682
2762
                tt.set_executability(executable[1], trans_id)
1683
 
        for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
1684
 
            deferred_files):
1685
 
            tt.create_file(bytes, trans_id, mode_id)
 
2763
        if working_tree.supports_content_filtering():
 
2764
            for index, ((trans_id, mode_id), bytes) in enumerate(
 
2765
                target_tree.iter_files_bytes(deferred_files)):
 
2766
                file_id = deferred_files[index][0]
 
2767
                # We're reverting a tree to the target tree so using the
 
2768
                # target tree to find the file path seems the best choice
 
2769
                # here IMO - Ian C 27/Oct/2009
 
2770
                filter_tree_path = target_tree.id2path(file_id)
 
2771
                filters = working_tree._content_filter_stack(filter_tree_path)
 
2772
                bytes = filtered_output_bytes(bytes, filters,
 
2773
                    ContentFilterContext(filter_tree_path, working_tree))
 
2774
                tt.create_file(bytes, trans_id, mode_id)
 
2775
        else:
 
2776
            for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
 
2777
                deferred_files):
 
2778
                tt.create_file(bytes, trans_id, mode_id)
 
2779
        tt.fixup_new_roots()
1686
2780
    finally:
1687
2781
        if basis_tree is not None:
1688
2782
            basis_tree.unlock()
1689
2783
    return merge_modified
1690
2784
 
1691
2785
 
1692
 
def resolve_conflicts(tt, pb=DummyProgress(), pass_func=None):
 
2786
def resolve_conflicts(tt, pb=None, pass_func=None):
1693
2787
    """Make many conflict-resolution attempts, but die if they fail"""
1694
2788
    if pass_func is None:
1695
2789
        pass_func = conflict_pass
1696
2790
    new_conflicts = set()
 
2791
    pb = ui.ui_factory.nested_progress_bar()
1697
2792
    try:
1698
2793
        for n in range(10):
1699
2794
            pb.update('Resolution pass', n+1, 10)
1703
2798
            new_conflicts.update(pass_func(tt, conflicts))
1704
2799
        raise MalformedTransform(conflicts=conflicts)
1705
2800
    finally:
1706
 
        pb.clear()
 
2801
        pb.finished()
1707
2802
 
1708
2803
 
1709
2804
def conflict_pass(tt, conflicts, path_tree=None):
1721
2816
                               conflict[1], conflict[2], ))
1722
2817
        elif c_type == 'duplicate':
1723
2818
            # files that were renamed take precedence
1724
 
            new_name = tt.final_name(conflict[1])+'.moved'
1725
2819
            final_parent = tt.final_parent(conflict[1])
1726
2820
            if tt.path_changed(conflict[1]):
1727
 
                tt.adjust_path(new_name, final_parent, conflict[2])
1728
 
                new_conflicts.add((c_type, 'Moved existing file to', 
1729
 
                                   conflict[2], conflict[1]))
 
2821
                existing_file, new_file = conflict[2], conflict[1]
1730
2822
            else:
1731
 
                tt.adjust_path(new_name, final_parent, conflict[1])
1732
 
                new_conflicts.add((c_type, 'Moved existing file to', 
1733
 
                                  conflict[1], conflict[2]))
 
2823
                existing_file, new_file = conflict[1], conflict[2]
 
2824
            new_name = tt.final_name(existing_file)+'.moved'
 
2825
            tt.adjust_path(new_name, final_parent, existing_file)
 
2826
            new_conflicts.add((c_type, 'Moved existing file to',
 
2827
                               existing_file, new_file))
1734
2828
        elif c_type == 'parent loop':
1735
2829
            # break the loop by undoing one of the ops that caused the loop
1736
2830
            cur = conflict[1]
1739
2833
            new_conflicts.add((c_type, 'Cancelled move', cur,
1740
2834
                               tt.final_parent(cur),))
1741
2835
            tt.adjust_path(tt.final_name(cur), tt.get_tree_parent(cur), cur)
1742
 
            
 
2836
 
1743
2837
        elif c_type == 'missing parent':
1744
2838
            trans_id = conflict[1]
1745
2839
            try:
1746
2840
                tt.cancel_deletion(trans_id)
1747
 
                new_conflicts.add(('deleting parent', 'Not deleting', 
 
2841
                new_conflicts.add(('deleting parent', 'Not deleting',
1748
2842
                                   trans_id))
1749
2843
            except KeyError:
1750
 
                tt.create_directory(trans_id)
1751
 
                new_conflicts.add((c_type, 'Created directory', trans_id))
 
2844
                create = True
1752
2845
                try:
1753
2846
                    tt.final_name(trans_id)
1754
2847
                except NoFinalPath:
1755
 
                    file_id = tt.final_file_id(trans_id)
1756
 
                    entry = path_tree.inventory[file_id]
1757
 
                    parent_trans_id = tt.trans_id_file_id(entry.parent_id)
1758
 
                    tt.adjust_path(entry.name, parent_trans_id, trans_id)
 
2848
                    if path_tree is not None:
 
2849
                        file_id = tt.final_file_id(trans_id)
 
2850
                        if file_id is None:
 
2851
                            file_id = tt.inactive_file_id(trans_id)
 
2852
                        entry = path_tree.inventory[file_id]
 
2853
                        # special-case the other tree root (move its
 
2854
                        # children to current root)
 
2855
                        if entry.parent_id is None:
 
2856
                            create = False
 
2857
                            moved = _reparent_transform_children(
 
2858
                                tt, trans_id, tt.root)
 
2859
                            for child in moved:
 
2860
                                new_conflicts.add((c_type, 'Moved to root',
 
2861
                                                   child))
 
2862
                        else:
 
2863
                            parent_trans_id = tt.trans_id_file_id(
 
2864
                                entry.parent_id)
 
2865
                            tt.adjust_path(entry.name, parent_trans_id,
 
2866
                                           trans_id)
 
2867
                if create:
 
2868
                    tt.create_directory(trans_id)
 
2869
                    new_conflicts.add((c_type, 'Created directory', trans_id))
1759
2870
        elif c_type == 'unversioned parent':
1760
 
            tt.version_file(tt.inactive_file_id(conflict[1]), conflict[1])
 
2871
            file_id = tt.inactive_file_id(conflict[1])
 
2872
            # special-case the other tree root (move its children instead)
 
2873
            if path_tree and file_id in path_tree:
 
2874
                if path_tree.inventory[file_id].parent_id is None:
 
2875
                    continue
 
2876
            tt.version_file(file_id, conflict[1])
1761
2877
            new_conflicts.add((c_type, 'Versioned directory', conflict[1]))
 
2878
        elif c_type == 'non-directory parent':
 
2879
            parent_id = conflict[1]
 
2880
            parent_parent = tt.final_parent(parent_id)
 
2881
            parent_name = tt.final_name(parent_id)
 
2882
            parent_file_id = tt.final_file_id(parent_id)
 
2883
            new_parent_id = tt.new_directory(parent_name + '.new',
 
2884
                parent_parent, parent_file_id)
 
2885
            _reparent_transform_children(tt, parent_id, new_parent_id)
 
2886
            if parent_file_id is not None:
 
2887
                tt.unversion_file(parent_id)
 
2888
            new_conflicts.add((c_type, 'Created directory', new_parent_id))
 
2889
        elif c_type == 'versioning no contents':
 
2890
            tt.cancel_versioning(conflict[1])
1762
2891
    return new_conflicts
1763
2892
 
1764
2893
 
1780
2909
        if len(conflict) == 3:
1781
2910
            yield Conflict.factory(c_type, action=action, path=modified_path,
1782
2911
                                     file_id=modified_id)
1783
 
             
 
2912
 
1784
2913
        else:
1785
2914
            conflicting_path = fp.get_path(conflict[3])
1786
2915
            conflicting_id = tt.final_file_id(conflict[3])
1787
2916
            yield Conflict.factory(c_type, action=action, path=modified_path,
1788
 
                                   file_id=modified_id, 
 
2917
                                   file_id=modified_id,
1789
2918
                                   conflict_path=conflicting_path,
1790
2919
                                   conflict_file_id=conflicting_id)
1791
2920
 
1798
2927
        self.pending_deletions = []
1799
2928
 
1800
2929
    def rename(self, from_, to):
1801
 
        """Rename a file from one path to another.  Functions like os.rename"""
1802
 
        os.rename(from_, to)
 
2930
        """Rename a file from one path to another."""
 
2931
        try:
 
2932
            osutils.rename(from_, to)
 
2933
        except (IOError, OSError), e:
 
2934
            if e.errno in (errno.EEXIST, errno.ENOTEMPTY):
 
2935
                raise errors.FileExists(to, str(e))
 
2936
            # normal OSError doesn't include filenames so it's hard to see where
 
2937
            # the problem is, see https://bugs.launchpad.net/bzr/+bug/491763
 
2938
            raise errors.TransformRenameFailed(from_, to, str(e), e.errno)
1803
2939
        self.past_renames.append((from_, to))
1804
2940
 
1805
2941
    def pre_delete(self, from_, to):
1815
2951
    def rollback(self):
1816
2952
        """Reverse all renames that have been performed"""
1817
2953
        for from_, to in reversed(self.past_renames):
1818
 
            os.rename(to, from_)
 
2954
            try:
 
2955
                osutils.rename(to, from_)
 
2956
            except (OSError, IOError), e:
 
2957
                raise errors.TransformRenameFailed(to, from_, str(e), e.errno)                
1819
2958
        # after rollback, don't reuse _FileMover
1820
2959
        past_renames = None
1821
2960
        pending_deletions = None