~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transform.py

  • Committer: Florian Dorn
  • Date: 2012-04-03 14:49:22 UTC
  • mto: This revision was merged to the branch mainline in revision 6546.
  • Revision ID: florian.dorn@boku.ac.at-20120403144922-b8y59csy8l1rzs5u
updated developer docs

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2006-2011 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
19
from stat import S_ISREG, S_IEXEC
 
20
import time
20
21
 
21
 
from bzrlib.lazy_import import lazy_import
22
 
lazy_import(globals(), """
 
22
from bzrlib import (
 
23
    errors,
 
24
    lazy_import,
 
25
    registry,
 
26
    trace,
 
27
    tree,
 
28
    )
 
29
lazy_import.lazy_import(globals(), """
23
30
from bzrlib import (
24
31
    annotate,
 
32
    bencode,
25
33
    bzrdir,
 
34
    commit,
26
35
    delta,
27
36
    errors,
28
37
    inventory,
 
38
    multiparent,
29
39
    osutils,
30
40
    revision as _mod_revision,
 
41
    ui,
 
42
    urlutils,
31
43
    )
32
44
""")
33
45
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
34
 
                           ReusingTransform, NotVersionedError, CantMoveRoot,
 
46
                           ReusingTransform, CantMoveRoot,
35
47
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
36
48
                           UnableCreateSymlink)
37
 
from bzrlib.inventory import InventoryEntry
 
49
from bzrlib.filters import filtered_output_bytes, ContentFilterContext
38
50
from bzrlib.osutils import (
39
51
    delete_any,
40
52
    file_kind,
41
53
    has_symlinks,
42
 
    lexists,
43
54
    pathjoin,
 
55
    sha_file,
44
56
    splitpath,
45
57
    supports_executable,
46
 
)
47
 
from bzrlib.progress import DummyProgress, ProgressPhase
 
58
    )
 
59
from bzrlib.progress import ProgressPhase
48
60
from bzrlib.symbol_versioning import (
49
 
        deprecated_function,
50
 
        )
51
 
from bzrlib.trace import mutter, warning
52
 
from bzrlib import tree
53
 
import bzrlib.ui
54
 
import bzrlib.urlutils as urlutils
 
61
    deprecated_function,
 
62
    deprecated_in,
 
63
    deprecated_method,
 
64
    )
55
65
 
56
66
 
57
67
ROOT_PARENT = "root-parent"
58
68
 
59
 
 
60
69
def unique_add(map, key, value):
61
70
    if key in map:
62
71
        raise DuplicateKey(key=key)
63
72
    map[key] = value
64
73
 
65
74
 
 
75
 
66
76
class _TransformResults(object):
67
77
    def __init__(self, modified_paths, rename_count):
68
78
        object.__init__(self)
71
81
 
72
82
 
73
83
class TreeTransformBase(object):
74
 
    """The base class for TreeTransform and TreeTransformBase"""
 
84
    """The base class for TreeTransform and its kin."""
75
85
 
76
 
    def __init__(self, tree, limbodir, pb=DummyProgress(),
 
86
    def __init__(self, tree, pb=None,
77
87
                 case_sensitive=True):
78
88
        """Constructor.
79
89
 
80
90
        :param tree: The tree that will be transformed, but not necessarily
81
91
            the output tree.
82
 
        :param limbodir: A directory where new files can be stored until
83
 
            they are installed in their proper places
84
 
        :param pb: A ProgressBar indicating how much progress is being made
 
92
        :param pb: ignored
85
93
        :param case_sensitive: If True, the target of the transform is
86
94
            case sensitive, not just case preserving.
87
95
        """
88
96
        object.__init__(self)
89
97
        self._tree = tree
90
 
        self._limbodir = limbodir
91
 
        self._deletiondir = None
92
98
        self._id_number = 0
93
99
        # mapping of trans_id -> new basename
94
100
        self._new_name = {}
96
102
        self._new_parent = {}
97
103
        # mapping of trans_id with new contents -> new file_kind
98
104
        self._new_contents = {}
99
 
        # A mapping of transform ids to their limbo filename
100
 
        self._limbo_files = {}
101
 
        # A mapping of transform ids to a set of the transform ids of children
102
 
        # that their limbo directory has
103
 
        self._limbo_children = {}
104
 
        # Map transform ids to maps of child filename to child transform id
105
 
        self._limbo_children_names = {}
106
 
        # List of transform ids that need to be renamed from limbo into place
107
 
        self._needs_rename = set()
 
105
        # mapping of trans_id => (sha1 of content, stat_value)
 
106
        self._observed_sha1s = {}
108
107
        # Set of trans_ids whose contents will be removed
109
108
        self._removed_contents = set()
110
109
        # Mapping of trans_id -> new execute-bit value
117
116
        self._non_present_ids = {}
118
117
        # Mapping of new file_id -> trans_id
119
118
        self._r_new_id = {}
120
 
        # Set of file_ids that will be removed
 
119
        # Set of trans_ids that will be removed
121
120
        self._removed_id = set()
122
121
        # Mapping of path in old tree -> trans_id
123
122
        self._tree_path_ids = {}
124
123
        # Mapping trans_id -> path in old tree
125
124
        self._tree_id_paths = {}
126
 
        # Cache of realpath results, to speed up canonical_path
127
 
        self._realpaths = {}
128
 
        # Cache of relpath results, to speed up canonical_path
129
 
        self._relpaths = {}
130
125
        # The trans_id that will be used as the tree root
131
126
        root_id = tree.get_root_id()
132
127
        if root_id is not None:
133
128
            self._new_root = self.trans_id_tree_file_id(root_id)
134
129
        else:
135
130
            self._new_root = None
136
 
        # Indictor of whether the transform has been applied
 
131
        # Indicator of whether the transform has been applied
137
132
        self._done = False
138
133
        # A progress bar
139
134
        self._pb = pb
142
137
        # A counter of how many files have been renamed
143
138
        self.rename_count = 0
144
139
 
 
140
    def finalize(self):
 
141
        """Release the working tree lock, if held.
 
142
 
 
143
        This is required if apply has not been invoked, but can be invoked
 
144
        even after apply.
 
145
        """
 
146
        if self._tree is None:
 
147
            return
 
148
        self._tree.unlock()
 
149
        self._tree = None
 
150
 
145
151
    def __get_root(self):
146
152
        return self._new_root
147
153
 
148
154
    root = property(__get_root)
149
155
 
150
 
    def finalize(self):
151
 
        """Release the working tree lock, if held, clean up limbo dir.
152
 
 
153
 
        This is required if apply has not been invoked, but can be invoked
154
 
        even after apply.
155
 
        """
156
 
        if self._tree is None:
157
 
            return
158
 
        try:
159
 
            entries = [(self._limbo_name(t), t, k) for t, k in
160
 
                       self._new_contents.iteritems()]
161
 
            entries.sort(reverse=True)
162
 
            for path, trans_id, kind in entries:
163
 
                if kind == "directory":
164
 
                    os.rmdir(path)
165
 
                else:
166
 
                    os.unlink(path)
167
 
            try:
168
 
                os.rmdir(self._limbodir)
169
 
            except OSError:
170
 
                # We don't especially care *why* the dir is immortal.
171
 
                raise ImmortalLimbo(self._limbodir)
172
 
            try:
173
 
                if self._deletiondir is not None:
174
 
                    os.rmdir(self._deletiondir)
175
 
            except OSError:
176
 
                raise errors.ImmortalPendingDeletion(self._deletiondir)
177
 
        finally:
178
 
            self._tree.unlock()
179
 
            self._tree = None
180
 
 
181
156
    def _assign_id(self):
182
157
        """Produce a new tranform id"""
183
158
        new_id = "new-%s" % self._id_number
193
168
 
194
169
    def adjust_path(self, name, parent, trans_id):
195
170
        """Change the path that is assigned to a transaction id."""
 
171
        if parent is None:
 
172
            raise ValueError("Parent trans-id may not be None")
196
173
        if trans_id == self._new_root:
197
174
            raise CantMoveRoot
198
 
        previous_parent = self._new_parent.get(trans_id)
199
 
        previous_name = self._new_name.get(trans_id)
200
175
        self._new_name[trans_id] = name
201
176
        self._new_parent[trans_id] = parent
202
 
        if parent == ROOT_PARENT:
203
 
            if self._new_root is not None:
204
 
                raise ValueError("Cannot have multiple roots.")
205
 
            self._new_root = trans_id
206
 
        if (trans_id in self._limbo_files and
207
 
            trans_id not in self._needs_rename):
208
 
            self._rename_in_limbo([trans_id])
209
 
            self._limbo_children[previous_parent].remove(trans_id)
210
 
            del self._limbo_children_names[previous_parent][previous_name]
211
 
 
212
 
    def _rename_in_limbo(self, trans_ids):
213
 
        """Fix limbo names so that the right final path is produced.
214
 
 
215
 
        This means we outsmarted ourselves-- we tried to avoid renaming
216
 
        these files later by creating them with their final names in their
217
 
        final parents.  But now the previous name or parent is no longer
218
 
        suitable, so we have to rename them.
219
 
 
220
 
        Even for trans_ids that have no new contents, we must remove their
221
 
        entries from _limbo_files, because they are now stale.
222
 
        """
223
 
        for trans_id in trans_ids:
224
 
            old_path = self._limbo_files.pop(trans_id)
225
 
            if trans_id not in self._new_contents:
226
 
                continue
227
 
            new_path = self._limbo_name(trans_id)
228
 
            os.rename(old_path, new_path)
229
177
 
230
178
    def adjust_root_path(self, name, parent):
231
179
        """Emulate moving the root by moving all children, instead.
232
 
        
 
180
 
233
181
        We do this by undoing the association of root's transaction id with the
234
182
        current tree.  This allows us to create a new directory with that
235
 
        transaction id.  We unversion the root directory and version the 
 
183
        transaction id.  We unversion the root directory and version the
236
184
        physically new directory, and hope someone versions the tree root
237
185
        later.
238
186
        """
241
189
        # force moving all children of root
242
190
        for child_id in self.iter_tree_children(old_root):
243
191
            if child_id != parent:
244
 
                self.adjust_path(self.final_name(child_id), 
 
192
                self.adjust_path(self.final_name(child_id),
245
193
                                 self.final_parent(child_id), child_id)
246
194
            file_id = self.final_file_id(child_id)
247
195
            if file_id is not None:
248
196
                self.unversion_file(child_id)
249
197
            self.version_file(file_id, child_id)
250
 
        
 
198
 
251
199
        # the physical root needs a new transaction id
252
200
        self._tree_path_ids.pop("")
253
201
        self._tree_id_paths.pop(old_root)
259
207
        self.version_file(old_root_file_id, old_root)
260
208
        self.unversion_file(self._new_root)
261
209
 
 
210
    def fixup_new_roots(self):
 
211
        """Reinterpret requests to change the root directory
 
212
 
 
213
        Instead of creating a root directory, or moving an existing directory,
 
214
        all the attributes and children of the new root are applied to the
 
215
        existing root directory.
 
216
 
 
217
        This means that the old root trans-id becomes obsolete, so it is
 
218
        recommended only to invoke this after the root trans-id has become
 
219
        irrelevant.
 
220
        """
 
221
        new_roots = [k for k, v in self._new_parent.iteritems() if v is
 
222
                     ROOT_PARENT]
 
223
        if len(new_roots) < 1:
 
224
            return
 
225
        if len(new_roots) != 1:
 
226
            raise ValueError('A tree cannot have two roots!')
 
227
        if self._new_root is None:
 
228
            self._new_root = new_roots[0]
 
229
            return
 
230
        old_new_root = new_roots[0]
 
231
        # TODO: What to do if a old_new_root is present, but self._new_root is
 
232
        #       not listed as being removed? This code explicitly unversions
 
233
        #       the old root and versions it with the new file_id. Though that
 
234
        #       seems like an incomplete delta
 
235
 
 
236
        # unversion the new root's directory.
 
237
        file_id = self.final_file_id(old_new_root)
 
238
        if old_new_root in self._new_id:
 
239
            self.cancel_versioning(old_new_root)
 
240
        else:
 
241
            self.unversion_file(old_new_root)
 
242
        # if, at this stage, root still has an old file_id, zap it so we can
 
243
        # stick a new one in.
 
244
        if (self.tree_file_id(self._new_root) is not None and
 
245
            self._new_root not in self._removed_id):
 
246
            self.unversion_file(self._new_root)
 
247
        self.version_file(file_id, self._new_root)
 
248
 
 
249
        # Now move children of new root into old root directory.
 
250
        # Ensure all children are registered with the transaction, but don't
 
251
        # use directly-- some tree children have new parents
 
252
        list(self.iter_tree_children(old_new_root))
 
253
        # Move all children of new root into old root directory.
 
254
        for child in self.by_parent().get(old_new_root, []):
 
255
            self.adjust_path(self.final_name(child), self._new_root, child)
 
256
 
 
257
        # Ensure old_new_root has no directory.
 
258
        if old_new_root in self._new_contents:
 
259
            self.cancel_creation(old_new_root)
 
260
        else:
 
261
            self.delete_contents(old_new_root)
 
262
 
 
263
        # prevent deletion of root directory.
 
264
        if self._new_root in self._removed_contents:
 
265
            self.cancel_deletion(self._new_root)
 
266
 
 
267
        # destroy path info for old_new_root.
 
268
        del self._new_parent[old_new_root]
 
269
        del self._new_name[old_new_root]
 
270
 
262
271
    def trans_id_tree_file_id(self, inventory_id):
263
272
        """Determine the transaction id of a working tree file.
264
 
        
 
273
 
265
274
        This reflects only files that already exist, not ones that will be
266
275
        added by transactions.
267
276
        """
280
289
            raise ValueError('None is not a valid file id')
281
290
        if file_id in self._r_new_id and self._r_new_id[file_id] is not None:
282
291
            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
 
292
        else:
 
293
            try:
 
294
                self._tree.iter_entries_by_dir([file_id]).next()
 
295
            except StopIteration:
 
296
                if file_id in self._non_present_ids:
 
297
                    return self._non_present_ids[file_id]
 
298
                else:
 
299
                    trans_id = self._assign_id()
 
300
                    self._non_present_ids[file_id] = trans_id
 
301
                    return trans_id
 
302
            else:
 
303
                return self.trans_id_tree_file_id(file_id)
310
304
 
311
305
    def trans_id_tree_path(self, path):
312
306
        """Determine (and maybe set) the transaction ID for a tree path."""
323
317
            return ROOT_PARENT
324
318
        return self.trans_id_tree_path(os.path.dirname(path))
325
319
 
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 in (errno.ENOENT, errno.ENOTDIR):
370
 
                # Either old_path doesn't exist, or the parent of the
371
 
                # target is not a directory (but will be one eventually)
372
 
                # Either way, we know it doesn't exist *right now*
373
 
                # See also bug #248448
374
 
                return
375
 
            else:
376
 
                raise
377
 
        if typefunc(mode):
378
 
            os.chmod(self._limbo_name(trans_id), mode)
379
 
 
380
 
    def create_hardlink(self, path, trans_id):
381
 
        """Schedule creation of a hard link"""
382
 
        name = self._limbo_name(trans_id)
383
 
        try:
384
 
            os.link(path, name)
385
 
        except OSError, e:
386
 
            if e.errno != errno.EPERM:
387
 
                raise
388
 
            raise errors.HardLinkNotSupported(path)
389
 
        try:
390
 
            unique_add(self._new_contents, trans_id, 'file')
391
 
        except:
392
 
            # Clean up the file, it never got registered so
393
 
            # TreeTransform.finalize() won't clean it up.
394
 
            os.unlink(name)
395
 
            raise
396
 
 
397
 
    def create_directory(self, trans_id):
398
 
        """Schedule creation of a new directory.
399
 
        
400
 
        See also new_directory.
401
 
        """
402
 
        os.mkdir(self._limbo_name(trans_id))
403
 
        unique_add(self._new_contents, trans_id, 'directory')
404
 
 
405
 
    def create_symlink(self, target, trans_id):
406
 
        """Schedule creation of a new symbolic link.
407
 
 
408
 
        target is a bytestring.
409
 
        See also new_symlink.
410
 
        """
411
 
        if has_symlinks():
412
 
            os.symlink(target, self._limbo_name(trans_id))
413
 
            unique_add(self._new_contents, trans_id, 'symlink')
414
 
        else:
415
 
            try:
416
 
                path = FinalPaths(self).get_path(trans_id)
417
 
            except KeyError:
418
 
                path = None
419
 
            raise UnableCreateSymlink(path=path)
420
 
 
421
 
    def cancel_creation(self, trans_id):
422
 
        """Cancel the creation of new file contents."""
423
 
        del self._new_contents[trans_id]
424
 
        children = self._limbo_children.get(trans_id)
425
 
        # if this is a limbo directory with children, move them before removing
426
 
        # the directory
427
 
        if children is not None:
428
 
            self._rename_in_limbo(children)
429
 
            del self._limbo_children[trans_id]
430
 
            del self._limbo_children_names[trans_id]
431
 
        delete_any(self._limbo_name(trans_id))
432
 
 
433
320
    def delete_contents(self, trans_id):
434
321
        """Schedule the contents of a path entry for deletion"""
435
 
        self.tree_kind(trans_id)
436
 
        self._removed_contents.add(trans_id)
 
322
        kind = self.tree_kind(trans_id)
 
323
        if kind is not None:
 
324
            self._removed_contents.add(trans_id)
437
325
 
438
326
    def cancel_deletion(self, trans_id):
439
327
        """Cancel a scheduled deletion"""
504
392
        changed_kind = set(self._removed_contents)
505
393
        changed_kind.intersection_update(self._new_contents)
506
394
        changed_kind.difference_update(new_ids)
507
 
        changed_kind = (t for t in changed_kind if self.tree_kind(t) !=
508
 
                        self.final_kind(t))
 
395
        changed_kind = (t for t in changed_kind
 
396
                        if self.tree_kind(t) != self.final_kind(t))
509
397
        new_ids.update(changed_kind)
510
398
        return sorted(FinalPaths(self).get_paths(new_ids))
511
399
 
512
 
    def tree_kind(self, trans_id):
513
 
        """Determine the file kind in the working tree.
514
 
 
515
 
        Raises NoSuchFile if the file does not exist
516
 
        """
517
 
        path = self._tree_id_paths.get(trans_id)
518
 
        if path is None:
519
 
            raise NoSuchFile(None)
520
 
        try:
521
 
            return file_kind(self._tree.abspath(path))
522
 
        except OSError, e:
523
 
            if e.errno != errno.ENOENT:
524
 
                raise
525
 
            else:
526
 
                raise NoSuchFile(path)
527
 
 
528
400
    def final_kind(self, trans_id):
529
401
        """Determine the final file kind, after any changes applied.
530
 
        
531
 
        Raises NoSuchFile if the file does not exist/has no contents.
532
 
        (It is conceivable that a path would be created without the
533
 
        corresponding contents insertion command)
 
402
 
 
403
        :return: None if the file does not exist/has no contents.  (It is
 
404
            conceivable that a path would be created without the corresponding
 
405
            contents insertion command)
534
406
        """
535
407
        if trans_id in self._new_contents:
536
408
            return self._new_contents[trans_id]
537
409
        elif trans_id in self._removed_contents:
538
 
            raise NoSuchFile(None)
 
410
            return None
539
411
        else:
540
412
            return self.tree_kind(trans_id)
541
413
 
549
421
        # the file is old; the old id is still valid
550
422
        if self._new_root == trans_id:
551
423
            return self._tree.get_root_id()
552
 
        return self._tree.inventory.path2id(path)
 
424
        return self._tree.path2id(path)
553
425
 
554
426
    def final_file_id(self, trans_id):
555
427
        """Determine the file id after any changes are applied, or None.
556
 
        
 
428
 
557
429
        None indicates that the file will not be versioned after changes are
558
430
        applied.
559
431
        """
598
470
 
599
471
    def by_parent(self):
600
472
        """Return a map of parent: children for known parents.
601
 
        
 
473
 
602
474
        Only new paths and parents of tree files with assigned ids are used.
603
475
        """
604
476
        by_parent = {}
605
477
        items = list(self._new_parent.iteritems())
606
 
        items.extend((t, self.final_parent(t)) for t in 
 
478
        items.extend((t, self.final_parent(t)) for t in
607
479
                      self._tree_id_paths.keys())
608
480
        for trans_id, parent_id in items:
609
481
            if parent_id not in by_parent:
637
509
        conflicts.extend(self._overwrite_conflicts())
638
510
        return conflicts
639
511
 
 
512
    def _check_malformed(self):
 
513
        conflicts = self.find_conflicts()
 
514
        if len(conflicts) != 0:
 
515
            raise MalformedTransform(conflicts=conflicts)
 
516
 
640
517
    def _add_tree_children(self):
641
518
        """Add all the children of all active parents to the known paths.
642
519
 
644
521
        removed.  This is a necessary first step in detecting conflicts.
645
522
        """
646
523
        parents = self.by_parent().keys()
647
 
        parents.extend([t for t in self._removed_contents if 
 
524
        parents.extend([t for t in self._removed_contents if
648
525
                        self.tree_kind(t) == 'directory'])
649
526
        for trans_id in self._removed_id:
650
527
            file_id = self.tree_file_id(trans_id)
651
528
            if file_id is not None:
 
529
                # XXX: This seems like something that should go via a different
 
530
                #      indirection.
652
531
                if self._tree.inventory[file_id].kind == 'directory':
653
532
                    parents.append(trans_id)
654
533
            elif self.tree_kind(trans_id) == 'directory':
658
537
            # ensure that all children are registered with the transaction
659
538
            list(self.iter_tree_children(parent_id))
660
539
 
661
 
    def iter_tree_children(self, parent_id):
662
 
        """Iterate through the entry's tree children, if any"""
663
 
        try:
664
 
            path = self._tree_id_paths[parent_id]
665
 
        except KeyError:
666
 
            return
667
 
        try:
668
 
            children = os.listdir(self._tree.abspath(path))
669
 
        except OSError, e:
670
 
            if not (osutils._is_error_enotdir(e)
671
 
                    or e.errno in (errno.ENOENT, errno.ESRCH)):
672
 
                raise
673
 
            return
674
 
 
675
 
        for child in children:
676
 
            childpath = joinpath(path, child)
677
 
            if self._tree.is_control_filename(childpath):
678
 
                continue
679
 
            yield self.trans_id_tree_path(childpath)
680
 
 
 
540
    @deprecated_method(deprecated_in((2, 3, 0)))
681
541
    def has_named_child(self, by_parent, parent_id, name):
682
 
        try:
683
 
            children = by_parent[parent_id]
684
 
        except KeyError:
685
 
            children = []
686
 
        for child in children:
 
542
        return self._has_named_child(
 
543
            name, parent_id, known_children=by_parent.get(parent_id, []))
 
544
 
 
545
    def _has_named_child(self, name, parent_id, known_children):
 
546
        """Does a parent already have a name child.
 
547
 
 
548
        :param name: The searched for name.
 
549
 
 
550
        :param parent_id: The parent for which the check is made.
 
551
 
 
552
        :param known_children: The already known children. This should have
 
553
            been recently obtained from `self.by_parent.get(parent_id)`
 
554
            (or will be if None is passed).
 
555
        """
 
556
        if known_children is None:
 
557
            known_children = self.by_parent().get(parent_id, [])
 
558
        for child in known_children:
687
559
            if self.final_name(child) == name:
688
560
                return True
689
 
        try:
690
 
            path = self._tree_id_paths[parent_id]
691
 
        except KeyError:
 
561
        parent_path = self._tree_id_paths.get(parent_id, None)
 
562
        if parent_path is None:
 
563
            # No parent... no children
692
564
            return False
693
 
        childpath = joinpath(path, name)
694
 
        child_id = self._tree_path_ids.get(childpath)
 
565
        child_path = joinpath(parent_path, name)
 
566
        child_id = self._tree_path_ids.get(child_path, None)
695
567
        if child_id is None:
696
 
            return lexists(self._tree.abspath(childpath))
 
568
            # Not known by the tree transform yet, check the filesystem
 
569
            return osutils.lexists(self._tree.abspath(child_path))
697
570
        else:
698
 
            if self.final_parent(child_id) != parent_id:
699
 
                return False
700
 
            if child_id in self._removed_contents:
701
 
                # XXX What about dangling file-ids?
702
 
                return False
703
 
            else:
704
 
                return True
 
571
            raise AssertionError('child_id is missing: %s, %s, %s'
 
572
                                 % (name, parent_id, child_id))
 
573
 
 
574
    def _available_backup_name(self, name, target_id):
 
575
        """Find an available backup name.
 
576
 
 
577
        :param name: The basename of the file.
 
578
 
 
579
        :param target_id: The directory trans_id where the backup should 
 
580
            be placed.
 
581
        """
 
582
        known_children = self.by_parent().get(target_id, [])
 
583
        return osutils.available_backup_name(
 
584
            name,
 
585
            lambda base: self._has_named_child(
 
586
                base, target_id, known_children))
705
587
 
706
588
    def _parent_loops(self):
707
589
        """No entry should be its own ancestor"""
737
619
 
738
620
    def _improper_versioning(self):
739
621
        """Cannot version a file with no contents, or a bad type.
740
 
        
 
622
 
741
623
        However, existing entries with no contents are okay.
742
624
        """
743
625
        conflicts = []
744
626
        for trans_id in self._new_id.iterkeys():
745
 
            try:
746
 
                kind = self.final_kind(trans_id)
747
 
            except NoSuchFile:
 
627
            kind = self.final_kind(trans_id)
 
628
            if kind is None:
748
629
                conflicts.append(('versioning no contents', trans_id))
749
630
                continue
750
 
            if not InventoryEntry.versionable_kind(kind):
 
631
            if not inventory.InventoryEntry.versionable_kind(kind):
751
632
                conflicts.append(('versioning bad kind', trans_id, kind))
752
633
        return conflicts
753
634
 
754
635
    def _executability_conflicts(self):
755
636
        """Check for bad executability changes.
756
 
        
 
637
 
757
638
        Only versioned files may have their executability set, because
758
639
        1. only versioned entries can have executability under windows
759
640
        2. only files can be executable.  (The execute bit on a directory
764
645
            if self.final_file_id(trans_id) is None:
765
646
                conflicts.append(('unversioned executability', trans_id))
766
647
            else:
767
 
                try:
768
 
                    non_file = self.final_kind(trans_id) != "file"
769
 
                except NoSuchFile:
770
 
                    non_file = True
771
 
                if non_file is True:
 
648
                if self.final_kind(trans_id) != "file":
772
649
                    conflicts.append(('non-file executability', trans_id))
773
650
        return conflicts
774
651
 
776
653
        """Check for overwrites (not permitted on Win32)"""
777
654
        conflicts = []
778
655
        for trans_id in self._new_contents:
779
 
            try:
780
 
                self.tree_kind(trans_id)
781
 
            except NoSuchFile:
 
656
            if self.tree_kind(trans_id) is None:
782
657
                continue
783
658
            if trans_id not in self._removed_contents:
784
659
                conflicts.append(('overwrite', trans_id,
791
666
        if (self._new_name, self._new_parent) == ({}, {}):
792
667
            return conflicts
793
668
        for children in by_parent.itervalues():
794
 
            name_ids = [(self.final_name(t), t) for t in children]
795
 
            if not self._case_sensitive_target:
796
 
                name_ids = [(n.lower(), t) for n, t in name_ids]
 
669
            name_ids = []
 
670
            for child_tid in children:
 
671
                name = self.final_name(child_tid)
 
672
                if name is not None:
 
673
                    # Keep children only if they still exist in the end
 
674
                    if not self._case_sensitive_target:
 
675
                        name = name.lower()
 
676
                    name_ids.append((name, child_tid))
797
677
            name_ids.sort()
798
678
            last_name = None
799
679
            last_trans_id = None
800
680
            for name, trans_id in name_ids:
801
 
                try:
802
 
                    kind = self.final_kind(trans_id)
803
 
                except NoSuchFile:
804
 
                    kind = None
 
681
                kind = self.final_kind(trans_id)
805
682
                file_id = self.final_file_id(trans_id)
806
683
                if kind is None and file_id is None:
807
684
                    continue
826
703
        return conflicts
827
704
 
828
705
    def _parent_type_conflicts(self, by_parent):
829
 
        """parents must have directory 'contents'."""
 
706
        """Children must have a directory parent"""
830
707
        conflicts = []
831
708
        for parent_id, children in by_parent.iteritems():
832
709
            if parent_id is ROOT_PARENT:
833
710
                continue
834
 
            if not self._any_contents(children):
 
711
            no_children = True
 
712
            for child_id in children:
 
713
                if self.final_kind(child_id) is not None:
 
714
                    no_children = False
 
715
                    break
 
716
            if no_children:
835
717
                continue
836
 
            for child in children:
837
 
                try:
838
 
                    self.final_kind(child)
839
 
                except NoSuchFile:
840
 
                    continue
841
 
            try:
842
 
                kind = self.final_kind(parent_id)
843
 
            except NoSuchFile:
844
 
                kind = None
 
718
            # There is at least a child, so we need an existing directory to
 
719
            # contain it.
 
720
            kind = self.final_kind(parent_id)
845
721
            if kind is None:
 
722
                # The directory will be deleted
846
723
                conflicts.append(('missing parent', parent_id))
847
724
            elif kind != "directory":
 
725
                # Meh, we need a *directory* to put something in it
848
726
                conflicts.append(('non-directory parent', parent_id))
849
727
        return conflicts
850
728
 
851
 
    def _any_contents(self, trans_ids):
852
 
        """Return true if any of the trans_ids, will have contents."""
853
 
        for trans_id in trans_ids:
854
 
            try:
855
 
                kind = self.final_kind(trans_id)
856
 
            except NoSuchFile:
857
 
                continue
858
 
            return True
859
 
        return False
860
 
 
861
 
    def _limbo_name(self, trans_id):
862
 
        """Generate the limbo name of a file"""
863
 
        limbo_name = self._limbo_files.get(trans_id)
864
 
        if limbo_name is not None:
865
 
            return limbo_name
866
 
        parent = self._new_parent.get(trans_id)
867
 
        # if the parent directory is already in limbo (e.g. when building a
868
 
        # tree), choose a limbo name inside the parent, to reduce further
869
 
        # renames.
870
 
        use_direct_path = False
871
 
        if self._new_contents.get(parent) == 'directory':
872
 
            filename = self._new_name.get(trans_id)
873
 
            if filename is not None:
874
 
                if parent not in self._limbo_children:
875
 
                    self._limbo_children[parent] = set()
876
 
                    self._limbo_children_names[parent] = {}
877
 
                    use_direct_path = True
878
 
                # the direct path can only be used if no other file has
879
 
                # already taken this pathname, i.e. if the name is unused, or
880
 
                # if it is already associated with this trans_id.
881
 
                elif self._case_sensitive_target:
882
 
                    if (self._limbo_children_names[parent].get(filename)
883
 
                        in (trans_id, None)):
884
 
                        use_direct_path = True
885
 
                else:
886
 
                    for l_filename, l_trans_id in\
887
 
                        self._limbo_children_names[parent].iteritems():
888
 
                        if l_trans_id == trans_id:
889
 
                            continue
890
 
                        if l_filename.lower() == filename.lower():
891
 
                            break
892
 
                    else:
893
 
                        use_direct_path = True
894
 
 
895
 
        if use_direct_path:
896
 
            limbo_name = pathjoin(self._limbo_files[parent], filename)
897
 
            self._limbo_children[parent].add(trans_id)
898
 
            self._limbo_children_names[parent][filename] = trans_id
899
 
        else:
900
 
            limbo_name = pathjoin(self._limbodir, trans_id)
901
 
            self._needs_rename.add(trans_id)
902
 
        self._limbo_files[trans_id] = limbo_name
903
 
        return limbo_name
904
 
 
905
729
    def _set_executability(self, path, trans_id):
906
730
        """Set the executability of versioned files """
907
731
        if supports_executable():
928
752
            self.version_file(file_id, trans_id)
929
753
        return trans_id
930
754
 
931
 
    def new_file(self, name, parent_id, contents, file_id=None, 
932
 
                 executable=None):
 
755
    def new_file(self, name, parent_id, contents, file_id=None,
 
756
                 executable=None, sha1=None):
933
757
        """Convenience method to create files.
934
 
        
 
758
 
935
759
        name is the name of the file to create.
936
760
        parent_id is the transaction id of the parent directory of the file.
937
761
        contents is an iterator of bytestrings, which will be used to produce
942
766
        trans_id = self._new_entry(name, parent_id, file_id)
943
767
        # TODO: rather than scheduling a set_executable call,
944
768
        # have create_file create the file with the right mode.
945
 
        self.create_file(contents, trans_id)
 
769
        self.create_file(contents, trans_id, sha1=sha1)
946
770
        if executable is not None:
947
771
            self.set_executability(executable, trans_id)
948
772
        return trans_id
957
781
        """
958
782
        trans_id = self._new_entry(name, parent_id, file_id)
959
783
        self.create_directory(trans_id)
960
 
        return trans_id 
 
784
        return trans_id
961
785
 
962
786
    def new_symlink(self, name, parent_id, target, file_id=None):
963
787
        """Convenience method to create symbolic link.
964
 
        
 
788
 
965
789
        name is the name of the symlink to create.
966
790
        parent_id is the transaction id of the parent directory of the symlink.
967
791
        target is a bytestring of the target of the symlink.
971
795
        self.create_symlink(target, trans_id)
972
796
        return trans_id
973
797
 
 
798
    def new_orphan(self, trans_id, parent_id):
 
799
        """Schedule an item to be orphaned.
 
800
 
 
801
        When a directory is about to be removed, its children, if they are not
 
802
        versioned are moved out of the way: they don't have a parent anymore.
 
803
 
 
804
        :param trans_id: The trans_id of the existing item.
 
805
        :param parent_id: The parent trans_id of the item.
 
806
        """
 
807
        raise NotImplementedError(self.new_orphan)
 
808
 
 
809
    def _get_potential_orphans(self, dir_id):
 
810
        """Find the potential orphans in a directory.
 
811
 
 
812
        A directory can't be safely deleted if there are versioned files in it.
 
813
        If all the contained files are unversioned then they can be orphaned.
 
814
 
 
815
        The 'None' return value means that the directory contains at least one
 
816
        versioned file and should not be deleted.
 
817
 
 
818
        :param dir_id: The directory trans id.
 
819
 
 
820
        :return: A list of the orphan trans ids or None if at least one
 
821
             versioned file is present.
 
822
        """
 
823
        orphans = []
 
824
        # Find the potential orphans, stop if one item should be kept
 
825
        for child_tid in self.by_parent()[dir_id]:
 
826
            if child_tid in self._removed_contents:
 
827
                # The child is removed as part of the transform. Since it was
 
828
                # versioned before, it's not an orphan
 
829
                continue
 
830
            elif self.final_file_id(child_tid) is None:
 
831
                # The child is not versioned
 
832
                orphans.append(child_tid)
 
833
            else:
 
834
                # We have a versioned file here, searching for orphans is
 
835
                # meaningless.
 
836
                orphans = None
 
837
                break
 
838
        return orphans
 
839
 
974
840
    def _affected_ids(self):
975
841
        """Return the set of transform ids affected by the transform"""
976
842
        trans_ids = set(self._removed_id)
1006
872
        from_path = self._tree_id_paths.get(from_trans_id)
1007
873
        if from_versioned:
1008
874
            # get data from working tree if versioned
1009
 
            from_entry = self._tree.inventory[file_id]
 
875
            from_entry = self._tree.iter_entries_by_dir([file_id]).next()[1]
1010
876
            from_name = from_entry.name
1011
877
            from_parent = from_entry.parent_id
1012
878
        else:
1035
901
        Return a (name, parent, kind, executable) tuple
1036
902
        """
1037
903
        to_name = self.final_name(to_trans_id)
1038
 
        try:
1039
 
            to_kind = self.final_kind(to_trans_id)
1040
 
        except NoSuchFile:
1041
 
            to_kind = None
 
904
        to_kind = self.final_kind(to_trans_id)
1042
905
        to_parent = self.final_file_id(self.final_parent(to_trans_id))
1043
906
        if to_trans_id in self._new_executability:
1044
907
            to_executable = self._new_executability[to_trans_id]
1113
976
    def get_preview_tree(self):
1114
977
        """Return a tree representing the result of the transform.
1115
978
 
1116
 
        This tree only supports the subset of Tree functionality required
1117
 
        by show_diff_trees.  It must only be compared to tt._tree.
 
979
        The tree is a snapshot, and altering the TreeTransform will invalidate
 
980
        it.
1118
981
        """
1119
982
        return _PreviewTree(self)
1120
983
 
1121
 
 
1122
 
class TreeTransform(TreeTransformBase):
 
984
    def commit(self, branch, message, merge_parents=None, strict=False,
 
985
               timestamp=None, timezone=None, committer=None, authors=None,
 
986
               revprops=None, revision_id=None):
 
987
        """Commit the result of this TreeTransform to a branch.
 
988
 
 
989
        :param branch: The branch to commit to.
 
990
        :param message: The message to attach to the commit.
 
991
        :param merge_parents: Additional parent revision-ids specified by
 
992
            pending merges.
 
993
        :param strict: If True, abort the commit if there are unversioned
 
994
            files.
 
995
        :param timestamp: if not None, seconds-since-epoch for the time and
 
996
            date.  (May be a float.)
 
997
        :param timezone: Optional timezone for timestamp, as an offset in
 
998
            seconds.
 
999
        :param committer: Optional committer in email-id format.
 
1000
            (e.g. "J Random Hacker <jrandom@example.com>")
 
1001
        :param authors: Optional list of authors in email-id format.
 
1002
        :param revprops: Optional dictionary of revision properties.
 
1003
        :param revision_id: Optional revision id.  (Specifying a revision-id
 
1004
            may reduce performance for some non-native formats.)
 
1005
        :return: The revision_id of the revision committed.
 
1006
        """
 
1007
        self._check_malformed()
 
1008
        if strict:
 
1009
            unversioned = set(self._new_contents).difference(set(self._new_id))
 
1010
            for trans_id in unversioned:
 
1011
                if self.final_file_id(trans_id) is None:
 
1012
                    raise errors.StrictCommitFailed()
 
1013
 
 
1014
        revno, last_rev_id = branch.last_revision_info()
 
1015
        if last_rev_id == _mod_revision.NULL_REVISION:
 
1016
            if merge_parents is not None:
 
1017
                raise ValueError('Cannot supply merge parents for first'
 
1018
                                 ' commit.')
 
1019
            parent_ids = []
 
1020
        else:
 
1021
            parent_ids = [last_rev_id]
 
1022
            if merge_parents is not None:
 
1023
                parent_ids.extend(merge_parents)
 
1024
        if self._tree.get_revision_id() != last_rev_id:
 
1025
            raise ValueError('TreeTransform not based on branch basis: %s' %
 
1026
                             self._tree.get_revision_id())
 
1027
        revprops = commit.Commit.update_revprops(revprops, branch, authors)
 
1028
        builder = branch.get_commit_builder(parent_ids,
 
1029
                                            timestamp=timestamp,
 
1030
                                            timezone=timezone,
 
1031
                                            committer=committer,
 
1032
                                            revprops=revprops,
 
1033
                                            revision_id=revision_id)
 
1034
        preview = self.get_preview_tree()
 
1035
        list(builder.record_iter_changes(preview, last_rev_id,
 
1036
                                         self.iter_changes()))
 
1037
        builder.finish_inventory()
 
1038
        revision_id = builder.commit(message)
 
1039
        branch.set_last_revision_info(revno + 1, revision_id)
 
1040
        return revision_id
 
1041
 
 
1042
    def _text_parent(self, trans_id):
 
1043
        file_id = self.tree_file_id(trans_id)
 
1044
        try:
 
1045
            if file_id is None or self._tree.kind(file_id) != 'file':
 
1046
                return None
 
1047
        except errors.NoSuchFile:
 
1048
            return None
 
1049
        return file_id
 
1050
 
 
1051
    def _get_parents_texts(self, trans_id):
 
1052
        """Get texts for compression parents of this file."""
 
1053
        file_id = self._text_parent(trans_id)
 
1054
        if file_id is None:
 
1055
            return ()
 
1056
        return (self._tree.get_file_text(file_id),)
 
1057
 
 
1058
    def _get_parents_lines(self, trans_id):
 
1059
        """Get lines for compression parents of this file."""
 
1060
        file_id = self._text_parent(trans_id)
 
1061
        if file_id is None:
 
1062
            return ()
 
1063
        return (self._tree.get_file_lines(file_id),)
 
1064
 
 
1065
    def serialize(self, serializer):
 
1066
        """Serialize this TreeTransform.
 
1067
 
 
1068
        :param serializer: A Serialiser like pack.ContainerSerializer.
 
1069
        """
 
1070
        new_name = dict((k, v.encode('utf-8')) for k, v in
 
1071
                        self._new_name.items())
 
1072
        new_executability = dict((k, int(v)) for k, v in
 
1073
                                 self._new_executability.items())
 
1074
        tree_path_ids = dict((k.encode('utf-8'), v)
 
1075
                             for k, v in self._tree_path_ids.items())
 
1076
        attribs = {
 
1077
            '_id_number': self._id_number,
 
1078
            '_new_name': new_name,
 
1079
            '_new_parent': self._new_parent,
 
1080
            '_new_executability': new_executability,
 
1081
            '_new_id': self._new_id,
 
1082
            '_tree_path_ids': tree_path_ids,
 
1083
            '_removed_id': list(self._removed_id),
 
1084
            '_removed_contents': list(self._removed_contents),
 
1085
            '_non_present_ids': self._non_present_ids,
 
1086
            }
 
1087
        yield serializer.bytes_record(bencode.bencode(attribs),
 
1088
                                      (('attribs',),))
 
1089
        for trans_id, kind in self._new_contents.items():
 
1090
            if kind == 'file':
 
1091
                lines = osutils.chunks_to_lines(
 
1092
                    self._read_file_chunks(trans_id))
 
1093
                parents = self._get_parents_lines(trans_id)
 
1094
                mpdiff = multiparent.MultiParent.from_lines(lines, parents)
 
1095
                content = ''.join(mpdiff.to_patch())
 
1096
            if kind == 'directory':
 
1097
                content = ''
 
1098
            if kind == 'symlink':
 
1099
                content = self._read_symlink_target(trans_id)
 
1100
            yield serializer.bytes_record(content, ((trans_id, kind),))
 
1101
 
 
1102
    def deserialize(self, records):
 
1103
        """Deserialize a stored TreeTransform.
 
1104
 
 
1105
        :param records: An iterable of (names, content) tuples, as per
 
1106
            pack.ContainerPushParser.
 
1107
        """
 
1108
        names, content = records.next()
 
1109
        attribs = bencode.bdecode(content)
 
1110
        self._id_number = attribs['_id_number']
 
1111
        self._new_name = dict((k, v.decode('utf-8'))
 
1112
                            for k, v in attribs['_new_name'].items())
 
1113
        self._new_parent = attribs['_new_parent']
 
1114
        self._new_executability = dict((k, bool(v)) for k, v in
 
1115
            attribs['_new_executability'].items())
 
1116
        self._new_id = attribs['_new_id']
 
1117
        self._r_new_id = dict((v, k) for k, v in self._new_id.items())
 
1118
        self._tree_path_ids = {}
 
1119
        self._tree_id_paths = {}
 
1120
        for bytepath, trans_id in attribs['_tree_path_ids'].items():
 
1121
            path = bytepath.decode('utf-8')
 
1122
            self._tree_path_ids[path] = trans_id
 
1123
            self._tree_id_paths[trans_id] = path
 
1124
        self._removed_id = set(attribs['_removed_id'])
 
1125
        self._removed_contents = set(attribs['_removed_contents'])
 
1126
        self._non_present_ids = attribs['_non_present_ids']
 
1127
        for ((trans_id, kind),), content in records:
 
1128
            if kind == 'file':
 
1129
                mpdiff = multiparent.MultiParent.from_patch(content)
 
1130
                lines = mpdiff.to_lines(self._get_parents_texts(trans_id))
 
1131
                self.create_file(lines, trans_id)
 
1132
            if kind == 'directory':
 
1133
                self.create_directory(trans_id)
 
1134
            if kind == 'symlink':
 
1135
                self.create_symlink(content.decode('utf-8'), trans_id)
 
1136
 
 
1137
 
 
1138
class DiskTreeTransform(TreeTransformBase):
 
1139
    """Tree transform storing its contents on disk."""
 
1140
 
 
1141
    def __init__(self, tree, limbodir, pb=None,
 
1142
                 case_sensitive=True):
 
1143
        """Constructor.
 
1144
        :param tree: The tree that will be transformed, but not necessarily
 
1145
            the output tree.
 
1146
        :param limbodir: A directory where new files can be stored until
 
1147
            they are installed in their proper places
 
1148
        :param pb: ignored
 
1149
        :param case_sensitive: If True, the target of the transform is
 
1150
            case sensitive, not just case preserving.
 
1151
        """
 
1152
        TreeTransformBase.__init__(self, tree, pb, case_sensitive)
 
1153
        self._limbodir = limbodir
 
1154
        self._deletiondir = None
 
1155
        # A mapping of transform ids to their limbo filename
 
1156
        self._limbo_files = {}
 
1157
        # A mapping of transform ids to a set of the transform ids of children
 
1158
        # that their limbo directory has
 
1159
        self._limbo_children = {}
 
1160
        # Map transform ids to maps of child filename to child transform id
 
1161
        self._limbo_children_names = {}
 
1162
        # List of transform ids that need to be renamed from limbo into place
 
1163
        self._needs_rename = set()
 
1164
        self._creation_mtime = None
 
1165
 
 
1166
    def finalize(self):
 
1167
        """Release the working tree lock, if held, clean up limbo dir.
 
1168
 
 
1169
        This is required if apply has not been invoked, but can be invoked
 
1170
        even after apply.
 
1171
        """
 
1172
        if self._tree is None:
 
1173
            return
 
1174
        try:
 
1175
            entries = [(self._limbo_name(t), t, k) for t, k in
 
1176
                       self._new_contents.iteritems()]
 
1177
            entries.sort(reverse=True)
 
1178
            for path, trans_id, kind in entries:
 
1179
                delete_any(path)
 
1180
            try:
 
1181
                delete_any(self._limbodir)
 
1182
            except OSError:
 
1183
                # We don't especially care *why* the dir is immortal.
 
1184
                raise ImmortalLimbo(self._limbodir)
 
1185
            try:
 
1186
                if self._deletiondir is not None:
 
1187
                    delete_any(self._deletiondir)
 
1188
            except OSError:
 
1189
                raise errors.ImmortalPendingDeletion(self._deletiondir)
 
1190
        finally:
 
1191
            TreeTransformBase.finalize(self)
 
1192
 
 
1193
    def _limbo_name(self, trans_id):
 
1194
        """Generate the limbo name of a file"""
 
1195
        limbo_name = self._limbo_files.get(trans_id)
 
1196
        if limbo_name is None:
 
1197
            limbo_name = self._generate_limbo_path(trans_id)
 
1198
            self._limbo_files[trans_id] = limbo_name
 
1199
        return limbo_name
 
1200
 
 
1201
    def _generate_limbo_path(self, trans_id):
 
1202
        """Generate a limbo path using the trans_id as the relative path.
 
1203
 
 
1204
        This is suitable as a fallback, and when the transform should not be
 
1205
        sensitive to the path encoding of the limbo directory.
 
1206
        """
 
1207
        self._needs_rename.add(trans_id)
 
1208
        return pathjoin(self._limbodir, trans_id)
 
1209
 
 
1210
    def adjust_path(self, name, parent, trans_id):
 
1211
        previous_parent = self._new_parent.get(trans_id)
 
1212
        previous_name = self._new_name.get(trans_id)
 
1213
        TreeTransformBase.adjust_path(self, name, parent, trans_id)
 
1214
        if (trans_id in self._limbo_files and
 
1215
            trans_id not in self._needs_rename):
 
1216
            self._rename_in_limbo([trans_id])
 
1217
            if previous_parent != parent:
 
1218
                self._limbo_children[previous_parent].remove(trans_id)
 
1219
            if previous_parent != parent or previous_name != name:
 
1220
                del self._limbo_children_names[previous_parent][previous_name]
 
1221
 
 
1222
    def _rename_in_limbo(self, trans_ids):
 
1223
        """Fix limbo names so that the right final path is produced.
 
1224
 
 
1225
        This means we outsmarted ourselves-- we tried to avoid renaming
 
1226
        these files later by creating them with their final names in their
 
1227
        final parents.  But now the previous name or parent is no longer
 
1228
        suitable, so we have to rename them.
 
1229
 
 
1230
        Even for trans_ids that have no new contents, we must remove their
 
1231
        entries from _limbo_files, because they are now stale.
 
1232
        """
 
1233
        for trans_id in trans_ids:
 
1234
            old_path = self._limbo_files.pop(trans_id)
 
1235
            if trans_id not in self._new_contents:
 
1236
                continue
 
1237
            new_path = self._limbo_name(trans_id)
 
1238
            os.rename(old_path, new_path)
 
1239
            for descendant in self._limbo_descendants(trans_id):
 
1240
                desc_path = self._limbo_files[descendant]
 
1241
                desc_path = new_path + desc_path[len(old_path):]
 
1242
                self._limbo_files[descendant] = desc_path
 
1243
 
 
1244
    def _limbo_descendants(self, trans_id):
 
1245
        """Return the set of trans_ids whose limbo paths descend from this."""
 
1246
        descendants = set(self._limbo_children.get(trans_id, []))
 
1247
        for descendant in list(descendants):
 
1248
            descendants.update(self._limbo_descendants(descendant))
 
1249
        return descendants
 
1250
 
 
1251
    def create_file(self, contents, trans_id, mode_id=None, sha1=None):
 
1252
        """Schedule creation of a new file.
 
1253
 
 
1254
        :seealso: new_file.
 
1255
 
 
1256
        :param contents: an iterator of strings, all of which will be written
 
1257
            to the target destination.
 
1258
        :param trans_id: TreeTransform handle
 
1259
        :param mode_id: If not None, force the mode of the target file to match
 
1260
            the mode of the object referenced by mode_id.
 
1261
            Otherwise, we will try to preserve mode bits of an existing file.
 
1262
        :param sha1: If the sha1 of this content is already known, pass it in.
 
1263
            We can use it to prevent future sha1 computations.
 
1264
        """
 
1265
        name = self._limbo_name(trans_id)
 
1266
        f = open(name, 'wb')
 
1267
        try:
 
1268
            try:
 
1269
                unique_add(self._new_contents, trans_id, 'file')
 
1270
            except:
 
1271
                # Clean up the file, it never got registered so
 
1272
                # TreeTransform.finalize() won't clean it up.
 
1273
                f.close()
 
1274
                os.unlink(name)
 
1275
                raise
 
1276
            f.writelines(contents)
 
1277
        finally:
 
1278
            f.close()
 
1279
        self._set_mtime(name)
 
1280
        self._set_mode(trans_id, mode_id, S_ISREG)
 
1281
        # It is unfortunate we have to use lstat instead of fstat, but we just
 
1282
        # used utime and chmod on the file, so we need the accurate final
 
1283
        # details.
 
1284
        if sha1 is not None:
 
1285
            self._observed_sha1s[trans_id] = (sha1, osutils.lstat(name))
 
1286
 
 
1287
    def _read_file_chunks(self, trans_id):
 
1288
        cur_file = open(self._limbo_name(trans_id), 'rb')
 
1289
        try:
 
1290
            return cur_file.readlines()
 
1291
        finally:
 
1292
            cur_file.close()
 
1293
 
 
1294
    def _read_symlink_target(self, trans_id):
 
1295
        return os.readlink(self._limbo_name(trans_id))
 
1296
 
 
1297
    def _set_mtime(self, path):
 
1298
        """All files that are created get the same mtime.
 
1299
 
 
1300
        This time is set by the first object to be created.
 
1301
        """
 
1302
        if self._creation_mtime is None:
 
1303
            self._creation_mtime = time.time()
 
1304
        os.utime(path, (self._creation_mtime, self._creation_mtime))
 
1305
 
 
1306
    def create_hardlink(self, path, trans_id):
 
1307
        """Schedule creation of a hard link"""
 
1308
        name = self._limbo_name(trans_id)
 
1309
        try:
 
1310
            os.link(path, name)
 
1311
        except OSError, e:
 
1312
            if e.errno != errno.EPERM:
 
1313
                raise
 
1314
            raise errors.HardLinkNotSupported(path)
 
1315
        try:
 
1316
            unique_add(self._new_contents, trans_id, 'file')
 
1317
        except:
 
1318
            # Clean up the file, it never got registered so
 
1319
            # TreeTransform.finalize() won't clean it up.
 
1320
            os.unlink(name)
 
1321
            raise
 
1322
 
 
1323
    def create_directory(self, trans_id):
 
1324
        """Schedule creation of a new directory.
 
1325
 
 
1326
        See also new_directory.
 
1327
        """
 
1328
        os.mkdir(self._limbo_name(trans_id))
 
1329
        unique_add(self._new_contents, trans_id, 'directory')
 
1330
 
 
1331
    def create_symlink(self, target, trans_id):
 
1332
        """Schedule creation of a new symbolic link.
 
1333
 
 
1334
        target is a bytestring.
 
1335
        See also new_symlink.
 
1336
        """
 
1337
        if has_symlinks():
 
1338
            os.symlink(target, self._limbo_name(trans_id))
 
1339
            unique_add(self._new_contents, trans_id, 'symlink')
 
1340
        else:
 
1341
            try:
 
1342
                path = FinalPaths(self).get_path(trans_id)
 
1343
            except KeyError:
 
1344
                path = None
 
1345
            raise UnableCreateSymlink(path=path)
 
1346
 
 
1347
    def cancel_creation(self, trans_id):
 
1348
        """Cancel the creation of new file contents."""
 
1349
        del self._new_contents[trans_id]
 
1350
        if trans_id in self._observed_sha1s:
 
1351
            del self._observed_sha1s[trans_id]
 
1352
        children = self._limbo_children.get(trans_id)
 
1353
        # if this is a limbo directory with children, move them before removing
 
1354
        # the directory
 
1355
        if children is not None:
 
1356
            self._rename_in_limbo(children)
 
1357
            del self._limbo_children[trans_id]
 
1358
            del self._limbo_children_names[trans_id]
 
1359
        delete_any(self._limbo_name(trans_id))
 
1360
 
 
1361
    def new_orphan(self, trans_id, parent_id):
 
1362
        # FIXME: There is no tree config, so we use the branch one (it's weird
 
1363
        # to define it this way as orphaning can only occur in a working tree,
 
1364
        # but that's all we have (for now). It will find the option in
 
1365
        # locations.conf or bazaar.conf though) -- vila 20100916
 
1366
        conf = self._tree.branch.get_config()
 
1367
        conf_var_name = 'bzr.transform.orphan_policy'
 
1368
        orphan_policy = conf.get_user_option(conf_var_name)
 
1369
        default_policy = orphaning_registry.default_key
 
1370
        if orphan_policy is None:
 
1371
            orphan_policy = default_policy
 
1372
        if orphan_policy not in orphaning_registry:
 
1373
            trace.warning('%s (from %s) is not a known policy, defaulting '
 
1374
                'to %s' % (orphan_policy, conf_var_name, default_policy))
 
1375
            orphan_policy = default_policy
 
1376
        handle_orphan = orphaning_registry.get(orphan_policy)
 
1377
        handle_orphan(self, trans_id, parent_id)
 
1378
 
 
1379
 
 
1380
class OrphaningError(errors.BzrError):
 
1381
 
 
1382
    # Only bugs could lead to such exception being seen by the user
 
1383
    internal_error = True
 
1384
    _fmt = "Error while orphaning %s in %s directory"
 
1385
 
 
1386
    def __init__(self, orphan, parent):
 
1387
        errors.BzrError.__init__(self)
 
1388
        self.orphan = orphan
 
1389
        self.parent = parent
 
1390
 
 
1391
 
 
1392
class OrphaningForbidden(OrphaningError):
 
1393
 
 
1394
    _fmt = "Policy: %s doesn't allow creating orphans."
 
1395
 
 
1396
    def __init__(self, policy):
 
1397
        errors.BzrError.__init__(self)
 
1398
        self.policy = policy
 
1399
 
 
1400
 
 
1401
def move_orphan(tt, orphan_id, parent_id):
 
1402
    """See TreeTransformBase.new_orphan.
 
1403
 
 
1404
    This creates a new orphan in the `bzr-orphans` dir at the root of the
 
1405
    `TreeTransform`.
 
1406
 
 
1407
    :param tt: The TreeTransform orphaning `trans_id`.
 
1408
 
 
1409
    :param orphan_id: The trans id that should be orphaned.
 
1410
 
 
1411
    :param parent_id: The orphan parent trans id.
 
1412
    """
 
1413
    # Add the orphan dir if it doesn't exist
 
1414
    orphan_dir_basename = 'bzr-orphans'
 
1415
    od_id = tt.trans_id_tree_path(orphan_dir_basename)
 
1416
    if tt.final_kind(od_id) is None:
 
1417
        tt.create_directory(od_id)
 
1418
    parent_path = tt._tree_id_paths[parent_id]
 
1419
    # Find a name that doesn't exist yet in the orphan dir
 
1420
    actual_name = tt.final_name(orphan_id)
 
1421
    new_name = tt._available_backup_name(actual_name, od_id)
 
1422
    tt.adjust_path(new_name, od_id, orphan_id)
 
1423
    trace.warning('%s has been orphaned in %s'
 
1424
                  % (joinpath(parent_path, actual_name), orphan_dir_basename))
 
1425
 
 
1426
 
 
1427
def refuse_orphan(tt, orphan_id, parent_id):
 
1428
    """See TreeTransformBase.new_orphan.
 
1429
 
 
1430
    This refuses to create orphan, letting the caller handle the conflict.
 
1431
    """
 
1432
    raise OrphaningForbidden('never')
 
1433
 
 
1434
 
 
1435
orphaning_registry = registry.Registry()
 
1436
orphaning_registry.register(
 
1437
    'conflict', refuse_orphan,
 
1438
    'Leave orphans in place and create a conflict on the directory.')
 
1439
orphaning_registry.register(
 
1440
    'move', move_orphan,
 
1441
    'Move orphans into the bzr-orphans directory.')
 
1442
orphaning_registry._set_default_key('conflict')
 
1443
 
 
1444
 
 
1445
class TreeTransform(DiskTreeTransform):
1123
1446
    """Represent a tree transformation.
1124
1447
 
1125
1448
    This object is designed to support incremental generation of the transform,
1184
1507
    FileMover does not delete files until it is sure that a rollback will not
1185
1508
    happen.
1186
1509
    """
1187
 
    def __init__(self, tree, pb=DummyProgress()):
 
1510
    def __init__(self, tree, pb=None):
1188
1511
        """Note: a tree_write lock is taken on the tree.
1189
1512
 
1190
1513
        Use TreeTransform.finalize() to release the lock (can be omitted if
1211
1534
            tree.unlock()
1212
1535
            raise
1213
1536
 
1214
 
        TreeTransformBase.__init__(self, tree, limbodir, pb,
 
1537
        # Cache of realpath results, to speed up canonical_path
 
1538
        self._realpaths = {}
 
1539
        # Cache of relpath results, to speed up canonical_path
 
1540
        self._relpaths = {}
 
1541
        DiskTreeTransform.__init__(self, tree, limbodir, pb,
1215
1542
                                   tree.case_sensitive)
1216
1543
        self._deletiondir = deletiondir
1217
1544
 
 
1545
    def canonical_path(self, path):
 
1546
        """Get the canonical tree-relative path"""
 
1547
        # don't follow final symlinks
 
1548
        abs = self._tree.abspath(path)
 
1549
        if abs in self._relpaths:
 
1550
            return self._relpaths[abs]
 
1551
        dirname, basename = os.path.split(abs)
 
1552
        if dirname not in self._realpaths:
 
1553
            self._realpaths[dirname] = os.path.realpath(dirname)
 
1554
        dirname = self._realpaths[dirname]
 
1555
        abs = pathjoin(dirname, basename)
 
1556
        if dirname in self._relpaths:
 
1557
            relpath = pathjoin(self._relpaths[dirname], basename)
 
1558
            relpath = relpath.rstrip('/\\')
 
1559
        else:
 
1560
            relpath = self._tree.relpath(abs)
 
1561
        self._relpaths[abs] = relpath
 
1562
        return relpath
 
1563
 
 
1564
    def tree_kind(self, trans_id):
 
1565
        """Determine the file kind in the working tree.
 
1566
 
 
1567
        :returns: The file kind or None if the file does not exist
 
1568
        """
 
1569
        path = self._tree_id_paths.get(trans_id)
 
1570
        if path is None:
 
1571
            return None
 
1572
        try:
 
1573
            return file_kind(self._tree.abspath(path))
 
1574
        except errors.NoSuchFile:
 
1575
            return None
 
1576
 
 
1577
    def _set_mode(self, trans_id, mode_id, typefunc):
 
1578
        """Set the mode of new file contents.
 
1579
        The mode_id is the existing file to get the mode from (often the same
 
1580
        as trans_id).  The operation is only performed if there's a mode match
 
1581
        according to typefunc.
 
1582
        """
 
1583
        if mode_id is None:
 
1584
            mode_id = trans_id
 
1585
        try:
 
1586
            old_path = self._tree_id_paths[mode_id]
 
1587
        except KeyError:
 
1588
            return
 
1589
        try:
 
1590
            mode = os.stat(self._tree.abspath(old_path)).st_mode
 
1591
        except OSError, e:
 
1592
            if e.errno in (errno.ENOENT, errno.ENOTDIR):
 
1593
                # Either old_path doesn't exist, or the parent of the
 
1594
                # target is not a directory (but will be one eventually)
 
1595
                # Either way, we know it doesn't exist *right now*
 
1596
                # See also bug #248448
 
1597
                return
 
1598
            else:
 
1599
                raise
 
1600
        if typefunc(mode):
 
1601
            os.chmod(self._limbo_name(trans_id), mode)
 
1602
 
 
1603
    def iter_tree_children(self, parent_id):
 
1604
        """Iterate through the entry's tree children, if any"""
 
1605
        try:
 
1606
            path = self._tree_id_paths[parent_id]
 
1607
        except KeyError:
 
1608
            return
 
1609
        try:
 
1610
            children = os.listdir(self._tree.abspath(path))
 
1611
        except OSError, e:
 
1612
            if not (osutils._is_error_enotdir(e)
 
1613
                    or e.errno in (errno.ENOENT, errno.ESRCH)):
 
1614
                raise
 
1615
            return
 
1616
 
 
1617
        for child in children:
 
1618
            childpath = joinpath(path, child)
 
1619
            if self._tree.is_control_filename(childpath):
 
1620
                continue
 
1621
            yield self.trans_id_tree_path(childpath)
 
1622
 
 
1623
    def _generate_limbo_path(self, trans_id):
 
1624
        """Generate a limbo path using the final path if possible.
 
1625
 
 
1626
        This optimizes the performance of applying the tree transform by
 
1627
        avoiding renames.  These renames can be avoided only when the parent
 
1628
        directory is already scheduled for creation.
 
1629
 
 
1630
        If the final path cannot be used, falls back to using the trans_id as
 
1631
        the relpath.
 
1632
        """
 
1633
        parent = self._new_parent.get(trans_id)
 
1634
        # if the parent directory is already in limbo (e.g. when building a
 
1635
        # tree), choose a limbo name inside the parent, to reduce further
 
1636
        # renames.
 
1637
        use_direct_path = False
 
1638
        if self._new_contents.get(parent) == 'directory':
 
1639
            filename = self._new_name.get(trans_id)
 
1640
            if filename is not None:
 
1641
                if parent not in self._limbo_children:
 
1642
                    self._limbo_children[parent] = set()
 
1643
                    self._limbo_children_names[parent] = {}
 
1644
                    use_direct_path = True
 
1645
                # the direct path can only be used if no other file has
 
1646
                # already taken this pathname, i.e. if the name is unused, or
 
1647
                # if it is already associated with this trans_id.
 
1648
                elif self._case_sensitive_target:
 
1649
                    if (self._limbo_children_names[parent].get(filename)
 
1650
                        in (trans_id, None)):
 
1651
                        use_direct_path = True
 
1652
                else:
 
1653
                    for l_filename, l_trans_id in\
 
1654
                        self._limbo_children_names[parent].iteritems():
 
1655
                        if l_trans_id == trans_id:
 
1656
                            continue
 
1657
                        if l_filename.lower() == filename.lower():
 
1658
                            break
 
1659
                    else:
 
1660
                        use_direct_path = True
 
1661
 
 
1662
        if not use_direct_path:
 
1663
            return DiskTreeTransform._generate_limbo_path(self, trans_id)
 
1664
 
 
1665
        limbo_name = pathjoin(self._limbo_files[parent], filename)
 
1666
        self._limbo_children[parent].add(trans_id)
 
1667
        self._limbo_children_names[parent][filename] = trans_id
 
1668
        return limbo_name
 
1669
 
 
1670
 
1218
1671
    def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
1219
1672
        """Apply all changes to the inventory and filesystem.
1220
1673
 
1230
1683
        :param _mover: Supply an alternate FileMover, for testing
1231
1684
        """
1232
1685
        if not no_conflicts:
1233
 
            conflicts = self.find_conflicts()
1234
 
            if len(conflicts) != 0:
1235
 
                raise MalformedTransform(conflicts=conflicts)
1236
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1686
            self._check_malformed()
 
1687
        child_pb = ui.ui_factory.nested_progress_bar()
1237
1688
        try:
1238
1689
            if precomputed_delta is None:
1239
1690
                child_pb.update('Apply phase', 0, 2)
1259
1710
        finally:
1260
1711
            child_pb.finished()
1261
1712
        self._tree.apply_inventory_delta(inventory_delta)
 
1713
        self._apply_observed_sha1s()
1262
1714
        self._done = True
1263
1715
        self.finalize()
1264
1716
        return _TransformResults(modified_paths, self.rename_count)
1266
1718
    def _generate_inventory_delta(self):
1267
1719
        """Generate an inventory delta for the current transform."""
1268
1720
        inventory_delta = []
1269
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1721
        child_pb = ui.ui_factory.nested_progress_bar()
1270
1722
        new_paths = self._inventory_altered()
1271
1723
        total_entries = len(new_paths) + len(self._removed_id)
1272
1724
        try:
1296
1748
                if file_id is None:
1297
1749
                    continue
1298
1750
                needs_entry = False
1299
 
                try:
1300
 
                    kind = self.final_kind(trans_id)
1301
 
                except NoSuchFile:
 
1751
                kind = self.final_kind(trans_id)
 
1752
                if kind is None:
1302
1753
                    kind = self._tree.stored_kind(file_id)
1303
1754
                parent_trans_id = self.final_parent(trans_id)
1304
1755
                parent_file_id = new_path_file_ids.get(parent_trans_id)
1335
1786
        """
1336
1787
        tree_paths = list(self._tree_path_ids.iteritems())
1337
1788
        tree_paths.sort(reverse=True)
1338
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1789
        child_pb = ui.ui_factory.nested_progress_bar()
1339
1790
        try:
1340
1791
            for num, data in enumerate(tree_paths):
1341
1792
                path, trans_id = data
1342
1793
                child_pb.update('removing file', num, len(tree_paths))
1343
1794
                full_path = self._tree.abspath(path)
1344
1795
                if trans_id in self._removed_contents:
1345
 
                    mover.pre_delete(full_path, os.path.join(self._deletiondir,
1346
 
                                     trans_id))
1347
 
                elif trans_id in self._new_name or trans_id in \
1348
 
                    self._new_parent:
 
1796
                    delete_path = os.path.join(self._deletiondir, trans_id)
 
1797
                    mover.pre_delete(full_path, delete_path)
 
1798
                elif (trans_id in self._new_name
 
1799
                      or trans_id in self._new_parent):
1349
1800
                    try:
1350
1801
                        mover.rename(full_path, self._limbo_name(trans_id))
1351
 
                    except OSError, e:
 
1802
                    except errors.TransformRenameFailed, e:
1352
1803
                        if e.errno != errno.ENOENT:
1353
1804
                            raise
1354
1805
                    else:
1370
1821
        modified_paths = []
1371
1822
        new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1372
1823
                                 new_paths)
1373
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1824
        child_pb = ui.ui_factory.nested_progress_bar()
1374
1825
        try:
1375
1826
            for num, (path, trans_id) in enumerate(new_paths):
1376
1827
                if (num % 10) == 0:
1379
1830
                if trans_id in self._needs_rename:
1380
1831
                    try:
1381
1832
                        mover.rename(self._limbo_name(trans_id), full_path)
1382
 
                    except OSError, e:
 
1833
                    except errors.TransformRenameFailed, e:
1383
1834
                        # We may be renaming a dangling inventory id
1384
1835
                        if e.errno != errno.ENOENT:
1385
1836
                            raise
1386
1837
                    else:
1387
1838
                        self.rename_count += 1
 
1839
                    # TODO: if trans_id in self._observed_sha1s, we should
 
1840
                    #       re-stat the final target, since ctime will be
 
1841
                    #       updated by the change.
1388
1842
                if (trans_id in self._new_contents or
1389
1843
                    self.path_changed(trans_id)):
1390
1844
                    if trans_id in self._new_contents:
1391
1845
                        modified_paths.append(full_path)
1392
1846
                if trans_id in self._new_executability:
1393
1847
                    self._set_executability(path, trans_id)
 
1848
                if trans_id in self._observed_sha1s:
 
1849
                    o_sha1, o_st_val = self._observed_sha1s[trans_id]
 
1850
                    st = osutils.lstat(full_path)
 
1851
                    self._observed_sha1s[trans_id] = (o_sha1, st)
1394
1852
        finally:
1395
1853
            child_pb.finished()
1396
1854
        self._new_contents.clear()
1397
1855
        return modified_paths
1398
1856
 
1399
 
 
1400
 
class TransformPreview(TreeTransformBase):
 
1857
    def _apply_observed_sha1s(self):
 
1858
        """After we have finished renaming everything, update observed sha1s
 
1859
 
 
1860
        This has to be done after self._tree.apply_inventory_delta, otherwise
 
1861
        it doesn't know anything about the files we are updating. Also, we want
 
1862
        to do this as late as possible, so that most entries end up cached.
 
1863
        """
 
1864
        # TODO: this doesn't update the stat information for directories. So
 
1865
        #       the first 'bzr status' will still need to rewrite
 
1866
        #       .bzr/checkout/dirstate. However, we at least don't need to
 
1867
        #       re-read all of the files.
 
1868
        # TODO: If the operation took a while, we could do a time.sleep(3) here
 
1869
        #       to allow the clock to tick over and ensure we won't have any
 
1870
        #       problems. (we could observe start time, and finish time, and if
 
1871
        #       it is less than eg 10% overhead, add a sleep call.)
 
1872
        paths = FinalPaths(self)
 
1873
        for trans_id, observed in self._observed_sha1s.iteritems():
 
1874
            path = paths.get_path(trans_id)
 
1875
            # We could get the file_id, but dirstate prefers to use the path
 
1876
            # anyway, and it is 'cheaper' to determine.
 
1877
            # file_id = self._new_id[trans_id]
 
1878
            self._tree._observed_sha1(None, path, observed)
 
1879
 
 
1880
 
 
1881
class TransformPreview(DiskTreeTransform):
1401
1882
    """A TreeTransform for generating preview trees.
1402
1883
 
1403
1884
    Unlike TreeTransform, this version works when the input tree is a
1405
1886
    unversioned files in the input tree.
1406
1887
    """
1407
1888
 
1408
 
    def __init__(self, tree, pb=DummyProgress(), case_sensitive=True):
 
1889
    def __init__(self, tree, pb=None, case_sensitive=True):
1409
1890
        tree.lock_read()
1410
1891
        limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
1411
 
        TreeTransformBase.__init__(self, tree, limbodir, pb, case_sensitive)
 
1892
        DiskTreeTransform.__init__(self, tree, limbodir, pb, case_sensitive)
1412
1893
 
1413
1894
    def canonical_path(self, path):
1414
1895
        return path
1416
1897
    def tree_kind(self, trans_id):
1417
1898
        path = self._tree_id_paths.get(trans_id)
1418
1899
        if path is None:
1419
 
            raise NoSuchFile(None)
1420
 
        file_id = self._tree.path2id(path)
1421
 
        return self._tree.kind(file_id)
 
1900
            return None
 
1901
        kind = self._tree.path_content_summary(path)[0]
 
1902
        if kind == 'missing':
 
1903
            kind = None
 
1904
        return kind
1422
1905
 
1423
1906
    def _set_mode(self, trans_id, mode_id, typefunc):
1424
1907
        """Set the mode of new file contents.
1438
1921
        file_id = self.tree_file_id(parent_id)
1439
1922
        if file_id is None:
1440
1923
            return
1441
 
        children = getattr(self._tree.inventory[file_id], 'children', {})
 
1924
        entry = self._tree.iter_entries_by_dir([file_id]).next()[1]
 
1925
        children = getattr(entry, 'children', {})
1442
1926
        for child in children:
1443
1927
            childpath = joinpath(path, child)
1444
1928
            yield self.trans_id_tree_path(childpath)
1445
1929
 
1446
 
 
1447
 
class _PreviewTree(tree.Tree):
 
1930
    def new_orphan(self, trans_id, parent_id):
 
1931
        raise NotImplementedError(self.new_orphan)
 
1932
 
 
1933
 
 
1934
class _PreviewTree(tree.InventoryTree):
1448
1935
    """Partial implementation of Tree to support show_diff_trees"""
1449
1936
 
1450
1937
    def __init__(self, transform):
1452
1939
        self._final_paths = FinalPaths(transform)
1453
1940
        self.__by_parent = None
1454
1941
        self._parent_ids = []
1455
 
 
1456
 
    def _changes(self, file_id):
1457
 
        for changes in self._transform.iter_changes():
1458
 
            if changes[0] == file_id:
1459
 
                return changes
 
1942
        self._all_children_cache = {}
 
1943
        self._path2trans_id_cache = {}
 
1944
        self._final_name_cache = {}
 
1945
        self._iter_changes_cache = dict((c[0], c) for c in
 
1946
                                        self._transform.iter_changes())
1460
1947
 
1461
1948
    def _content_change(self, file_id):
1462
1949
        """Return True if the content of this file changed"""
1463
 
        changes = self._changes(file_id)
 
1950
        changes = self._iter_changes_cache.get(file_id)
1464
1951
        # changes[2] is true if the file content changed.  See
1465
1952
        # InterTree.iter_changes.
1466
1953
        return (changes is not None and changes[2])
1479
1966
                yield self._get_repository().revision_tree(revision_id)
1480
1967
 
1481
1968
    def _get_file_revision(self, file_id, vf, tree_revision):
1482
 
        parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
 
1969
        parent_keys = [(file_id, t.get_file_revision(file_id)) for t in
1483
1970
                       self._iter_parent_trees()]
1484
1971
        vf.add_lines((file_id, tree_revision), parent_keys,
1485
 
                     self.get_file(file_id).readlines())
 
1972
                     self.get_file_lines(file_id))
1486
1973
        repo = self._get_repository()
1487
1974
        base_vf = repo.texts
1488
1975
        if base_vf not in vf.fallback_versionedfiles:
1489
1976
            vf.fallback_versionedfiles.append(base_vf)
1490
1977
        return tree_revision
1491
1978
 
1492
 
    def _stat_limbo_file(self, file_id):
1493
 
        trans_id = self._transform.trans_id_file_id(file_id)
 
1979
    def _stat_limbo_file(self, file_id=None, trans_id=None):
 
1980
        if trans_id is None:
 
1981
            trans_id = self._transform.trans_id_file_id(file_id)
1494
1982
        name = self._transform._limbo_name(trans_id)
1495
1983
        return os.lstat(name)
1496
1984
 
1500
1988
            self.__by_parent = self._transform.by_parent()
1501
1989
        return self.__by_parent
1502
1990
 
 
1991
    def _comparison_data(self, entry, path):
 
1992
        kind, size, executable, link_or_sha1 = self.path_content_summary(path)
 
1993
        if kind == 'missing':
 
1994
            kind = None
 
1995
            executable = False
 
1996
        else:
 
1997
            file_id = self._transform.final_file_id(self._path2trans_id(path))
 
1998
            executable = self.is_executable(file_id, path)
 
1999
        return kind, executable, None
 
2000
 
 
2001
    def is_locked(self):
 
2002
        return False
 
2003
 
1503
2004
    def lock_read(self):
1504
2005
        # Perhaps in theory, this should lock the TreeTransform?
1505
 
        pass
 
2006
        return self
1506
2007
 
1507
2008
    def unlock(self):
1508
2009
        pass
1525
2026
    def __iter__(self):
1526
2027
        return iter(self.all_file_ids())
1527
2028
 
1528
 
    def paths2ids(self, specific_files, trees=None, require_versioned=False):
1529
 
        """See Tree.paths2ids"""
1530
 
        to_find = set(specific_files)
1531
 
        result = set()
1532
 
        for (file_id, paths, changed, versioned, parent, name, kind,
1533
 
             executable) in self._transform.iter_changes():
1534
 
            if paths[1] in to_find:
1535
 
                result.add(file_id)
1536
 
                to_find.remove(paths[1])
1537
 
        result.update(self._transform._tree.paths2ids(to_find,
1538
 
                      trees=[], require_versioned=require_versioned))
1539
 
        return result
 
2029
    def _has_id(self, file_id, fallback_check):
 
2030
        if file_id in self._transform._r_new_id:
 
2031
            return True
 
2032
        elif file_id in set([self._transform.tree_file_id(trans_id) for
 
2033
            trans_id in self._transform._removed_id]):
 
2034
            return False
 
2035
        else:
 
2036
            return fallback_check(file_id)
 
2037
 
 
2038
    def has_id(self, file_id):
 
2039
        return self._has_id(file_id, self._transform._tree.has_id)
 
2040
 
 
2041
    def has_or_had_id(self, file_id):
 
2042
        return self._has_id(file_id, self._transform._tree.has_or_had_id)
1540
2043
 
1541
2044
    def _path2trans_id(self, path):
 
2045
        # We must not use None here, because that is a valid value to store.
 
2046
        trans_id = self._path2trans_id_cache.get(path, object)
 
2047
        if trans_id is not object:
 
2048
            return trans_id
1542
2049
        segments = splitpath(path)
1543
2050
        cur_parent = self._transform.root
1544
2051
        for cur_segment in segments:
1545
2052
            for child in self._all_children(cur_parent):
1546
 
                if self._transform.final_name(child) == cur_segment:
 
2053
                final_name = self._final_name_cache.get(child)
 
2054
                if final_name is None:
 
2055
                    final_name = self._transform.final_name(child)
 
2056
                    self._final_name_cache[child] = final_name
 
2057
                if final_name == cur_segment:
1547
2058
                    cur_parent = child
1548
2059
                    break
1549
2060
            else:
 
2061
                self._path2trans_id_cache[path] = None
1550
2062
                return None
 
2063
        self._path2trans_id_cache[path] = cur_parent
1551
2064
        return cur_parent
1552
2065
 
1553
2066
    def path2id(self, path):
1561
2074
            raise errors.NoSuchId(self, file_id)
1562
2075
 
1563
2076
    def _all_children(self, trans_id):
 
2077
        children = self._all_children_cache.get(trans_id)
 
2078
        if children is not None:
 
2079
            return children
1564
2080
        children = set(self._transform.iter_tree_children(trans_id))
1565
2081
        # children in the _new_parent set are provided by _by_parent.
1566
2082
        children.difference_update(self._transform._new_parent.keys())
1567
2083
        children.update(self._by_parent.get(trans_id, []))
 
2084
        self._all_children_cache[trans_id] = children
1568
2085
        return children
1569
2086
 
1570
 
    def _make_inv_entries(self, ordered_entries, specific_file_ids):
 
2087
    def iter_children(self, file_id):
 
2088
        trans_id = self._transform.trans_id_file_id(file_id)
 
2089
        for child_trans_id in self._all_children(trans_id):
 
2090
            yield self._transform.final_file_id(child_trans_id)
 
2091
 
 
2092
    def extras(self):
 
2093
        possible_extras = set(self._transform.trans_id_tree_path(p) for p
 
2094
                              in self._transform._tree.extras())
 
2095
        possible_extras.update(self._transform._new_contents)
 
2096
        possible_extras.update(self._transform._removed_id)
 
2097
        for trans_id in possible_extras:
 
2098
            if self._transform.final_file_id(trans_id) is None:
 
2099
                yield self._final_paths._determine_path(trans_id)
 
2100
 
 
2101
    def _make_inv_entries(self, ordered_entries, specific_file_ids=None,
 
2102
        yield_parents=False):
1571
2103
        for trans_id, parent_file_id in ordered_entries:
1572
2104
            file_id = self._transform.final_file_id(trans_id)
1573
2105
            if file_id is None:
1575
2107
            if (specific_file_ids is not None
1576
2108
                and file_id not in specific_file_ids):
1577
2109
                continue
1578
 
            try:
1579
 
                kind = self._transform.final_kind(trans_id)
1580
 
            except NoSuchFile:
 
2110
            kind = self._transform.final_kind(trans_id)
 
2111
            if kind is None:
1581
2112
                kind = self._transform._tree.stored_kind(file_id)
1582
2113
            new_entry = inventory.make_entry(
1583
2114
                kind,
1599
2130
                ordered_ids.append((trans_id, parent_file_id))
1600
2131
        return ordered_ids
1601
2132
 
1602
 
    def iter_entries_by_dir(self, specific_file_ids=None):
 
2133
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
1603
2134
        # This may not be a maximally efficient implementation, but it is
1604
2135
        # reasonably straightforward.  An implementation that grafts the
1605
2136
        # TreeTransform changes onto the tree's iter_entries_by_dir results
1607
2138
        # position.
1608
2139
        ordered_ids = self._list_files_by_dir()
1609
2140
        for entry, trans_id in self._make_inv_entries(ordered_ids,
1610
 
                                                      specific_file_ids):
1611
 
            yield unicode(self._final_paths.get_path(trans_id)), entry
1612
 
 
1613
 
    def list_files(self, include_root=False):
1614
 
        """See Tree.list_files."""
 
2141
            specific_file_ids, yield_parents=yield_parents):
 
2142
            yield unicode(self._final_paths.get_path(trans_id)), entry
 
2143
 
 
2144
    def _iter_entries_for_dir(self, dir_path):
 
2145
        """Return path, entry for items in a directory without recursing down."""
 
2146
        dir_file_id = self.path2id(dir_path)
 
2147
        ordered_ids = []
 
2148
        for file_id in self.iter_children(dir_file_id):
 
2149
            trans_id = self._transform.trans_id_file_id(file_id)
 
2150
            ordered_ids.append((trans_id, file_id))
 
2151
        for entry, trans_id in self._make_inv_entries(ordered_ids):
 
2152
            yield unicode(self._final_paths.get_path(trans_id)), entry
 
2153
 
 
2154
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
2155
        """See WorkingTree.list_files."""
1615
2156
        # XXX This should behave like WorkingTree.list_files, but is really
1616
2157
        # more like RevisionTree.list_files.
1617
 
        for path, entry in self.iter_entries_by_dir():
1618
 
            if entry.name == '' and not include_root:
1619
 
                continue
1620
 
            yield path, 'V', entry.kind, entry.file_id, entry
 
2158
        if recursive:
 
2159
            prefix = None
 
2160
            if from_dir:
 
2161
                prefix = from_dir + '/'
 
2162
            entries = self.iter_entries_by_dir()
 
2163
            for path, entry in entries:
 
2164
                if entry.name == '' and not include_root:
 
2165
                    continue
 
2166
                if prefix:
 
2167
                    if not path.startswith(prefix):
 
2168
                        continue
 
2169
                    path = path[len(prefix):]
 
2170
                yield path, 'V', entry.kind, entry.file_id, entry
 
2171
        else:
 
2172
            if from_dir is None and include_root is True:
 
2173
                root_entry = inventory.make_entry('directory', '',
 
2174
                    ROOT_PARENT, self.get_root_id())
 
2175
                yield '', 'V', 'directory', root_entry.file_id, root_entry
 
2176
            entries = self._iter_entries_for_dir(from_dir or '')
 
2177
            for path, entry in entries:
 
2178
                yield path, 'V', entry.kind, entry.file_id, entry
1621
2179
 
1622
2180
    def kind(self, file_id):
1623
2181
        trans_id = self._transform.trans_id_file_id(file_id)
1633
2191
    def get_file_mtime(self, file_id, path=None):
1634
2192
        """See Tree.get_file_mtime"""
1635
2193
        if not self._content_change(file_id):
1636
 
            return self._transform._tree.get_file_mtime(file_id, path)
 
2194
            return self._transform._tree.get_file_mtime(file_id)
1637
2195
        return self._stat_limbo_file(file_id).st_mtime
1638
2196
 
 
2197
    def _file_size(self, entry, stat_value):
 
2198
        return self.get_file_size(entry.file_id)
 
2199
 
1639
2200
    def get_file_size(self, file_id):
1640
2201
        """See Tree.get_file_size"""
 
2202
        trans_id = self._transform.trans_id_file_id(file_id)
 
2203
        kind = self._transform.final_kind(trans_id)
 
2204
        if kind != 'file':
 
2205
            return None
 
2206
        if trans_id in self._transform._new_contents:
 
2207
            return self._stat_limbo_file(trans_id=trans_id).st_size
1641
2208
        if self.kind(file_id) == 'file':
1642
2209
            return self._transform._tree.get_file_size(file_id)
1643
2210
        else:
1644
2211
            return None
1645
2212
 
1646
2213
    def get_file_sha1(self, file_id, path=None, stat_value=None):
1647
 
        return self._transform._tree.get_file_sha1(file_id)
 
2214
        trans_id = self._transform.trans_id_file_id(file_id)
 
2215
        kind = self._transform._new_contents.get(trans_id)
 
2216
        if kind is None:
 
2217
            return self._transform._tree.get_file_sha1(file_id)
 
2218
        if kind == 'file':
 
2219
            fileobj = self.get_file(file_id)
 
2220
            try:
 
2221
                return sha_file(fileobj)
 
2222
            finally:
 
2223
                fileobj.close()
1648
2224
 
1649
2225
    def is_executable(self, file_id, path=None):
 
2226
        if file_id is None:
 
2227
            return False
1650
2228
        trans_id = self._transform.trans_id_file_id(file_id)
1651
2229
        try:
1652
2230
            return self._transform._new_executability[trans_id]
1653
2231
        except KeyError:
1654
 
            return self._transform._tree.is_executable(file_id, path)
 
2232
            try:
 
2233
                return self._transform._tree.is_executable(file_id, path)
 
2234
            except OSError, e:
 
2235
                if e.errno == errno.ENOENT:
 
2236
                    return False
 
2237
                raise
 
2238
            except errors.NoSuchId:
 
2239
                return False
 
2240
 
 
2241
    def has_filename(self, path):
 
2242
        trans_id = self._path2trans_id(path)
 
2243
        if trans_id in self._transform._new_contents:
 
2244
            return True
 
2245
        elif trans_id in self._transform._removed_contents:
 
2246
            return False
 
2247
        else:
 
2248
            return self._transform._tree.has_filename(path)
1655
2249
 
1656
2250
    def path_content_summary(self, path):
1657
2251
        trans_id = self._path2trans_id(path)
1672
2266
                statval = os.lstat(limbo_name)
1673
2267
                size = statval.st_size
1674
2268
                if not supports_executable():
1675
 
                    executable = None
 
2269
                    executable = False
1676
2270
                else:
1677
2271
                    executable = statval.st_mode & S_IEXEC
1678
2272
            else:
1679
2273
                size = None
1680
2274
                executable = None
1681
2275
            if kind == 'symlink':
1682
 
                link_or_sha1 = os.readlink(limbo_name)
1683
 
        if supports_executable():
1684
 
            executable = tt._new_executability.get(trans_id, executable)
 
2276
                link_or_sha1 = os.readlink(limbo_name).decode(osutils._fs_enc)
 
2277
        executable = tt._new_executability.get(trans_id, executable)
1685
2278
        return kind, size, executable, link_or_sha1
1686
2279
 
1687
2280
    def iter_changes(self, from_tree, include_unchanged=False,
1689
2282
                      require_versioned=True, want_unversioned=False):
1690
2283
        """See InterTree.iter_changes.
1691
2284
 
1692
 
        This implementation does not support include_unchanged, specific_files,
1693
 
        or want_unversioned.  extra_trees, require_versioned, and pb are
1694
 
        ignored.
 
2285
        This has a fast path that is only used when the from_tree matches
 
2286
        the transform tree, and no fancy options are supplied.
1695
2287
        """
1696
 
        if from_tree is not self._transform._tree:
1697
 
            raise ValueError('from_tree must be transform source tree.')
1698
 
        if include_unchanged:
1699
 
            raise ValueError('include_unchanged is not supported')
1700
 
        if specific_files is not None:
1701
 
            raise ValueError('specific_files is not supported')
 
2288
        if (from_tree is not self._transform._tree or include_unchanged or
 
2289
            specific_files or want_unversioned):
 
2290
            return tree.InterTree(from_tree, self).iter_changes(
 
2291
                include_unchanged=include_unchanged,
 
2292
                specific_files=specific_files,
 
2293
                pb=pb,
 
2294
                extra_trees=extra_trees,
 
2295
                require_versioned=require_versioned,
 
2296
                want_unversioned=want_unversioned)
1702
2297
        if want_unversioned:
1703
2298
            raise ValueError('want_unversioned is not supported')
1704
2299
        return self._transform.iter_changes()
1711
2306
        name = self._transform._limbo_name(trans_id)
1712
2307
        return open(name, 'rb')
1713
2308
 
1714
 
    def get_file_text(self, file_id):
1715
 
        text_file = self.get_file(file_id)
1716
 
        try:
1717
 
            return text_file.read()
1718
 
        finally:
1719
 
            text_file.close()
 
2309
    def get_file_with_stat(self, file_id, path=None):
 
2310
        return self.get_file(file_id, path), None
1720
2311
 
1721
2312
    def annotate_iter(self, file_id,
1722
2313
                      default_revision=_mod_revision.CURRENT_REVISION):
1723
 
        changes = self._changes(file_id)
 
2314
        changes = self._iter_changes_cache.get(file_id)
1724
2315
        if changes is None:
1725
2316
            get_old = True
1726
2317
        else:
1738
2329
            return old_annotation
1739
2330
        if not changed_content:
1740
2331
            return old_annotation
 
2332
        # TODO: This is doing something similar to what WT.annotate_iter is
 
2333
        #       doing, however it fails slightly because it doesn't know what
 
2334
        #       the *other* revision_id is, so it doesn't know how to give the
 
2335
        #       other as the origin for some lines, they all get
 
2336
        #       'default_revision'
 
2337
        #       It would be nice to be able to use the new Annotator based
 
2338
        #       approach, as well.
1741
2339
        return annotate.reannotate([old_annotation],
1742
2340
                                   self.get_file(file_id).readlines(),
1743
2341
                                   default_revision)
1744
2342
 
1745
 
    def get_symlink_target(self, file_id):
 
2343
    def get_symlink_target(self, file_id, path=None):
1746
2344
        """See Tree.get_symlink_target"""
1747
2345
        if not self._content_change(file_id):
1748
2346
            return self._transform._tree.get_symlink_target(file_id)
1749
2347
        trans_id = self._transform.trans_id_file_id(file_id)
1750
2348
        name = self._transform._limbo_name(trans_id)
1751
 
        return os.readlink(name)
 
2349
        return osutils.readlink(name)
1752
2350
 
1753
2351
    def walkdirs(self, prefix=''):
1754
2352
        pending = [self._transform.root]
1763
2361
                path_from_root = self._final_paths.get_path(child_id)
1764
2362
                basename = self._transform.final_name(child_id)
1765
2363
                file_id = self._transform.final_file_id(child_id)
1766
 
                try:
1767
 
                    kind = self._transform.final_kind(child_id)
 
2364
                kind  = self._transform.final_kind(child_id)
 
2365
                if kind is not None:
1768
2366
                    versioned_kind = kind
1769
 
                except NoSuchFile:
 
2367
                else:
1770
2368
                    kind = 'unknown'
1771
2369
                    versioned_kind = self._transform._tree.stored_kind(file_id)
1772
2370
                if versioned_kind == 'directory':
1809
2407
        self.transform = transform
1810
2408
 
1811
2409
    def _determine_path(self, trans_id):
1812
 
        if trans_id == self.transform.root:
 
2410
        if (trans_id == self.transform.root or trans_id == ROOT_PARENT):
1813
2411
            return ""
1814
2412
        name = self.transform.final_name(trans_id)
1815
2413
        parent_id = self.transform.final_parent(trans_id)
1839
2437
def build_tree(tree, wt, accelerator_tree=None, hardlink=False,
1840
2438
               delta_from_tree=False):
1841
2439
    """Create working tree for a branch, using a TreeTransform.
1842
 
    
 
2440
 
1843
2441
    This function should be used on empty trees, having a tree root at most.
1844
2442
    (see merge and revert functionality for working with existing trees)
1845
2443
 
1846
2444
    Existing files are handled like so:
1847
 
    
 
2445
 
1848
2446
    - Existing bzrdirs take precedence over creating new items.  They are
1849
2447
      created as '%s.diverted' % name.
1850
2448
    - Otherwise, if the content on disk matches the content we are building,
1885
2483
    for num, _unused in enumerate(wt.all_file_ids()):
1886
2484
        if num > 0:  # more than just a root
1887
2485
            raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
1888
 
    existing_files = set()
1889
 
    for dir, files in wt.walkdirs():
1890
 
        existing_files.update(f[0] for f in files)
1891
2486
    file_trans_id = {}
1892
 
    top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
2487
    top_pb = ui.ui_factory.nested_progress_bar()
1893
2488
    pp = ProgressPhase("Build phase", 2, top_pb)
1894
2489
    if tree.inventory.root is not None:
1895
2490
        # This is kind of a hack: we should be altering the root
1908
2503
        pp.next_phase()
1909
2504
        file_trans_id[wt.get_root_id()] = \
1910
2505
            tt.trans_id_tree_file_id(wt.get_root_id())
1911
 
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
2506
        pb = ui.ui_factory.nested_progress_bar()
1912
2507
        try:
1913
2508
            deferred_contents = []
1914
2509
            num = 0
1917
2512
                precomputed_delta = []
1918
2513
            else:
1919
2514
                precomputed_delta = None
 
2515
            # Check if tree inventory has content. If so, we populate
 
2516
            # existing_files with the directory content. If there are no
 
2517
            # entries we skip populating existing_files as its not used.
 
2518
            # This improves performance and unncessary work on large
 
2519
            # directory trees. (#501307)
 
2520
            if total > 0:
 
2521
                existing_files = set()
 
2522
                for dir, files in wt.walkdirs():
 
2523
                    existing_files.update(f[0] for f in files)
1920
2524
            for num, (tree_path, entry) in \
1921
2525
                enumerate(tree.inventory.iter_entries_by_dir()):
1922
2526
                pb.update("Building tree", num - len(deferred_contents), total)
1952
2556
                    executable = tree.is_executable(file_id, tree_path)
1953
2557
                    if executable:
1954
2558
                        tt.set_executability(executable, trans_id)
1955
 
                    deferred_contents.append((file_id, trans_id))
 
2559
                    trans_data = (trans_id, tree_path, entry.text_sha1)
 
2560
                    deferred_contents.append((file_id, trans_data))
1956
2561
                else:
1957
2562
                    file_trans_id[file_id] = new_by_entry(tt, entry, parent_id,
1958
2563
                                                          tree)
1973
2578
            precomputed_delta = None
1974
2579
        conflicts = cook_conflicts(raw_conflicts, tt)
1975
2580
        for conflict in conflicts:
1976
 
            warning(conflict)
 
2581
            trace.warning(unicode(conflict))
1977
2582
        try:
1978
2583
            wt.add_conflicts(conflicts)
1979
2584
        except errors.UnsupportedOperation:
1989
2594
def _create_files(tt, tree, desired_files, pb, offset, accelerator_tree,
1990
2595
                  hardlink):
1991
2596
    total = len(desired_files) + offset
 
2597
    wt = tt._tree
1992
2598
    if accelerator_tree is None:
1993
2599
        new_desired_files = desired_files
1994
2600
    else:
1995
2601
        iter = accelerator_tree.iter_changes(tree, include_unchanged=True)
1996
 
        unchanged = dict((f, p[1]) for (f, p, c, v, d, n, k, e)
1997
 
                         in iter if not (c or e[0] != e[1]))
 
2602
        unchanged = [(f, p[1]) for (f, p, c, v, d, n, k, e)
 
2603
                     in iter if not (c or e[0] != e[1])]
 
2604
        if accelerator_tree.supports_content_filtering():
 
2605
            unchanged = [(f, p) for (f, p) in unchanged
 
2606
                         if not accelerator_tree.iter_search_rules([p]).next()]
 
2607
        unchanged = dict(unchanged)
1998
2608
        new_desired_files = []
1999
2609
        count = 0
2000
 
        for file_id, trans_id in desired_files:
 
2610
        for file_id, (trans_id, tree_path, text_sha1) in desired_files:
2001
2611
            accelerator_path = unchanged.get(file_id)
2002
2612
            if accelerator_path is None:
2003
 
                new_desired_files.append((file_id, trans_id))
 
2613
                new_desired_files.append((file_id,
 
2614
                    (trans_id, tree_path, text_sha1)))
2004
2615
                continue
2005
2616
            pb.update('Adding file contents', count + offset, total)
2006
2617
            if hardlink:
2008
2619
                                   trans_id)
2009
2620
            else:
2010
2621
                contents = accelerator_tree.get_file(file_id, accelerator_path)
 
2622
                if wt.supports_content_filtering():
 
2623
                    filters = wt._content_filter_stack(tree_path)
 
2624
                    contents = filtered_output_bytes(contents, filters,
 
2625
                        ContentFilterContext(tree_path, tree))
2011
2626
                try:
2012
 
                    tt.create_file(contents, trans_id)
 
2627
                    tt.create_file(contents, trans_id, sha1=text_sha1)
2013
2628
                finally:
2014
 
                    contents.close()
 
2629
                    try:
 
2630
                        contents.close()
 
2631
                    except AttributeError:
 
2632
                        # after filtering, contents may no longer be file-like
 
2633
                        pass
2015
2634
            count += 1
2016
2635
        offset += count
2017
 
    for count, (trans_id, contents) in enumerate(tree.iter_files_bytes(
2018
 
                                                 new_desired_files)):
2019
 
        tt.create_file(contents, trans_id)
 
2636
    for count, ((trans_id, tree_path, text_sha1), contents) in enumerate(
 
2637
            tree.iter_files_bytes(new_desired_files)):
 
2638
        if wt.supports_content_filtering():
 
2639
            filters = wt._content_filter_stack(tree_path)
 
2640
            contents = filtered_output_bytes(contents, filters,
 
2641
                ContentFilterContext(tree_path, tree))
 
2642
        tt.create_file(contents, trans_id, sha1=text_sha1)
2020
2643
        pb.update('Adding file contents', count + offset, total)
2021
2644
 
2022
2645
 
2024
2647
    for child in tt.iter_tree_children(old_parent):
2025
2648
        tt.adjust_path(tt.final_name(child), new_parent, child)
2026
2649
 
 
2650
 
2027
2651
def _reparent_transform_children(tt, old_parent, new_parent):
2028
2652
    by_parent = tt.by_parent()
2029
2653
    for child in by_parent[old_parent]:
2030
2654
        tt.adjust_path(tt.final_name(child), new_parent, child)
2031
2655
    return by_parent[old_parent]
2032
2656
 
 
2657
 
2033
2658
def _content_match(tree, entry, file_id, kind, target_path):
2034
2659
    if entry.kind != kind:
2035
2660
        return False
2036
2661
    if entry.kind == "directory":
2037
2662
        return True
2038
2663
    if entry.kind == "file":
2039
 
        if tree.get_file(file_id).read() == file(target_path, 'rb').read():
2040
 
            return True
 
2664
        f = file(target_path, 'rb')
 
2665
        try:
 
2666
            if tree.get_file_text(file_id) == f.read():
 
2667
                return True
 
2668
        finally:
 
2669
            f.close()
2041
2670
    elif entry.kind == "symlink":
2042
2671
        if tree.get_symlink_target(file_id) == os.readlink(target_path):
2043
2672
            return True
2081
2710
    if kind == 'file':
2082
2711
        contents = tree.get_file(entry.file_id).readlines()
2083
2712
        executable = tree.is_executable(entry.file_id)
2084
 
        return tt.new_file(name, parent_id, contents, entry.file_id, 
 
2713
        return tt.new_file(name, parent_id, contents, entry.file_id,
2085
2714
                           executable)
2086
2715
    elif kind in ('directory', 'tree-reference'):
2087
2716
        trans_id = tt.new_directory(name, parent_id, entry.file_id)
2088
2717
        if kind == 'tree-reference':
2089
2718
            tt.set_tree_reference(entry.reference_revision, trans_id)
2090
 
        return trans_id 
 
2719
        return trans_id
2091
2720
    elif kind == 'symlink':
2092
2721
        target = tree.get_symlink_target(entry.file_id)
2093
2722
        return tt.new_symlink(name, parent_id, target, entry.file_id)
2095
2724
        raise errors.BadFileKindError(name, kind)
2096
2725
 
2097
2726
 
2098
 
def create_by_entry(tt, entry, tree, trans_id, lines=None, mode_id=None):
2099
 
    """Create new file contents according to an inventory entry."""
2100
 
    if entry.kind == "file":
2101
 
        if lines is None:
2102
 
            lines = tree.get_file(entry.file_id).readlines()
2103
 
        tt.create_file(lines, trans_id, mode_id=mode_id)
2104
 
    elif entry.kind == "symlink":
2105
 
        tt.create_symlink(tree.get_symlink_target(entry.file_id), trans_id)
2106
 
    elif entry.kind == "directory":
 
2727
def create_from_tree(tt, trans_id, tree, file_id, bytes=None,
 
2728
    filter_tree_path=None):
 
2729
    """Create new file contents according to tree contents.
 
2730
    
 
2731
    :param filter_tree_path: the tree path to use to lookup
 
2732
      content filters to apply to the bytes output in the working tree.
 
2733
      This only applies if the working tree supports content filtering.
 
2734
    """
 
2735
    kind = tree.kind(file_id)
 
2736
    if kind == 'directory':
2107
2737
        tt.create_directory(trans_id)
 
2738
    elif kind == "file":
 
2739
        if bytes is None:
 
2740
            tree_file = tree.get_file(file_id)
 
2741
            try:
 
2742
                bytes = tree_file.readlines()
 
2743
            finally:
 
2744
                tree_file.close()
 
2745
        wt = tt._tree
 
2746
        if wt.supports_content_filtering() and filter_tree_path is not None:
 
2747
            filters = wt._content_filter_stack(filter_tree_path)
 
2748
            bytes = filtered_output_bytes(bytes, filters,
 
2749
                ContentFilterContext(filter_tree_path, tree))
 
2750
        tt.create_file(bytes, trans_id)
 
2751
    elif kind == "symlink":
 
2752
        tt.create_symlink(tree.get_symlink_target(file_id), trans_id)
 
2753
    else:
 
2754
        raise AssertionError('Unknown kind %r' % kind)
2108
2755
 
2109
2756
 
2110
2757
def create_entry_executability(tt, entry, trans_id):
2113
2760
        tt.set_executability(entry.executable, trans_id)
2114
2761
 
2115
2762
 
 
2763
@deprecated_function(deprecated_in((2, 3, 0)))
2116
2764
def get_backup_name(entry, by_parent, parent_trans_id, tt):
2117
2765
    return _get_backup_name(entry.name, by_parent, parent_trans_id, tt)
2118
2766
 
2119
2767
 
 
2768
@deprecated_function(deprecated_in((2, 3, 0)))
2120
2769
def _get_backup_name(name, by_parent, parent_trans_id, tt):
2121
2770
    """Produce a backup-style name that appears to be available"""
2122
2771
    def name_gen():
2149
2798
        if entry.kind != working_kind:
2150
2799
            contents_mod, meta_mod = True, False
2151
2800
        else:
2152
 
            cur_entry._read_tree_state(working_tree.id2path(file_id), 
 
2801
            cur_entry._read_tree_state(working_tree.id2path(file_id),
2153
2802
                                       working_tree)
2154
2803
            contents_mod, meta_mod = entry.detect_changes(cur_entry)
2155
2804
            cur_entry._forget_tree_state()
2157
2806
 
2158
2807
 
2159
2808
def revert(working_tree, target_tree, filenames, backups=False,
2160
 
           pb=DummyProgress(), change_reporter=None):
 
2809
           pb=None, change_reporter=None):
2161
2810
    """Revert a working tree's contents to those of a target tree."""
2162
2811
    target_tree.lock_read()
 
2812
    pb = ui.ui_factory.nested_progress_bar()
2163
2813
    tt = TreeTransform(working_tree, pb)
2164
2814
    try:
2165
2815
        pp = ProgressPhase("Revert phase", 3, pb)
2170
2820
                unversioned_filter=working_tree.is_ignored)
2171
2821
            delta.report_changes(tt.iter_changes(), change_reporter)
2172
2822
        for conflict in conflicts:
2173
 
            warning(conflict)
 
2823
            trace.warning(unicode(conflict))
2174
2824
        pp.next_phase()
2175
2825
        tt.apply()
2176
2826
        working_tree.set_merge_modified(merge_modified)
2184
2834
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
2185
2835
                              backups, pp, basis_tree=None,
2186
2836
                              merge_modified=None):
2187
 
    pp.next_phase()
2188
 
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
2837
    child_pb = ui.ui_factory.nested_progress_bar()
2189
2838
    try:
2190
2839
        if merge_modified is None:
2191
2840
            merge_modified = working_tree.merge_modified()
2194
2843
                                      merge_modified, basis_tree)
2195
2844
    finally:
2196
2845
        child_pb.finished()
2197
 
    pp.next_phase()
2198
 
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
2846
    child_pb = ui.ui_factory.nested_progress_bar()
2199
2847
    try:
2200
2848
        raw_conflicts = resolve_conflicts(tt, child_pb,
2201
2849
            lambda t, c: conflict_pass(t, c, target_tree))
2209
2857
                 backups, merge_modified, basis_tree=None):
2210
2858
    if basis_tree is not None:
2211
2859
        basis_tree.lock_read()
2212
 
    change_list = target_tree.iter_changes(working_tree,
 
2860
    # We ask the working_tree for its changes relative to the target, rather
 
2861
    # than the target changes relative to the working tree. Because WT4 has an
 
2862
    # optimizer to compare itself to a target, but no optimizer for the
 
2863
    # reverse.
 
2864
    change_list = working_tree.iter_changes(target_tree,
2213
2865
        specific_files=specific_files, pb=pb)
2214
2866
    if target_tree.get_root_id() is None:
2215
2867
        skip_root = True
2219
2871
        deferred_files = []
2220
2872
        for id_num, (file_id, path, changed_content, versioned, parent, name,
2221
2873
                kind, executable) in enumerate(change_list):
2222
 
            if skip_root and file_id[0] is not None and parent[0] is None:
 
2874
            target_path, wt_path = path
 
2875
            target_versioned, wt_versioned = versioned
 
2876
            target_parent, wt_parent = parent
 
2877
            target_name, wt_name = name
 
2878
            target_kind, wt_kind = kind
 
2879
            target_executable, wt_executable = executable
 
2880
            if skip_root and wt_parent is None:
2223
2881
                continue
2224
2882
            trans_id = tt.trans_id_file_id(file_id)
2225
2883
            mode_id = None
2226
2884
            if changed_content:
2227
2885
                keep_content = False
2228
 
                if kind[0] == 'file' and (backups or kind[1] is None):
 
2886
                if wt_kind == 'file' and (backups or target_kind is None):
2229
2887
                    wt_sha1 = working_tree.get_file_sha1(file_id)
2230
2888
                    if merge_modified.get(file_id) != wt_sha1:
2231
2889
                        # acquire the basis tree lazily to prevent the
2237
2895
                        if file_id in basis_tree:
2238
2896
                            if wt_sha1 != basis_tree.get_file_sha1(file_id):
2239
2897
                                keep_content = True
2240
 
                        elif kind[1] is None and not versioned[1]:
 
2898
                        elif target_kind is None and not target_versioned:
2241
2899
                            keep_content = True
2242
 
                if kind[0] is not None:
 
2900
                if wt_kind is not None:
2243
2901
                    if not keep_content:
2244
2902
                        tt.delete_contents(trans_id)
2245
 
                    elif kind[1] is not None:
2246
 
                        parent_trans_id = tt.trans_id_file_id(parent[0])
2247
 
                        by_parent = tt.by_parent()
2248
 
                        backup_name = _get_backup_name(name[0], by_parent,
2249
 
                                                       parent_trans_id, tt)
 
2903
                    elif target_kind is not None:
 
2904
                        parent_trans_id = tt.trans_id_file_id(wt_parent)
 
2905
                        backup_name = tt._available_backup_name(
 
2906
                            wt_name, parent_trans_id)
2250
2907
                        tt.adjust_path(backup_name, parent_trans_id, trans_id)
2251
 
                        new_trans_id = tt.create_path(name[0], parent_trans_id)
2252
 
                        if versioned == (True, True):
 
2908
                        new_trans_id = tt.create_path(wt_name, parent_trans_id)
 
2909
                        if wt_versioned and target_versioned:
2253
2910
                            tt.unversion_file(trans_id)
2254
2911
                            tt.version_file(file_id, new_trans_id)
2255
2912
                        # New contents should have the same unix perms as old
2256
2913
                        # contents
2257
2914
                        mode_id = trans_id
2258
2915
                        trans_id = new_trans_id
2259
 
                if kind[1] in ('directory', 'tree-reference'):
 
2916
                if target_kind in ('directory', 'tree-reference'):
2260
2917
                    tt.create_directory(trans_id)
2261
 
                    if kind[1] == 'tree-reference':
 
2918
                    if target_kind == 'tree-reference':
2262
2919
                        revision = target_tree.get_reference_revision(file_id,
2263
 
                                                                      path[1])
 
2920
                                                                      target_path)
2264
2921
                        tt.set_tree_reference(revision, trans_id)
2265
 
                elif kind[1] == 'symlink':
 
2922
                elif target_kind == 'symlink':
2266
2923
                    tt.create_symlink(target_tree.get_symlink_target(file_id),
2267
2924
                                      trans_id)
2268
 
                elif kind[1] == 'file':
 
2925
                elif target_kind == 'file':
2269
2926
                    deferred_files.append((file_id, (trans_id, mode_id)))
2270
2927
                    if basis_tree is None:
2271
2928
                        basis_tree = working_tree.basis_tree()
2279
2936
                        merge_modified[file_id] = new_sha1
2280
2937
 
2281
2938
                    # preserve the execute bit when backing up
2282
 
                    if keep_content and executable[0] == executable[1]:
2283
 
                        tt.set_executability(executable[1], trans_id)
2284
 
                elif kind[1] is not None:
2285
 
                    raise AssertionError(kind[1])
2286
 
            if versioned == (False, True):
 
2939
                    if keep_content and wt_executable == target_executable:
 
2940
                        tt.set_executability(target_executable, trans_id)
 
2941
                elif target_kind is not None:
 
2942
                    raise AssertionError(target_kind)
 
2943
            if not wt_versioned and target_versioned:
2287
2944
                tt.version_file(file_id, trans_id)
2288
 
            if versioned == (True, False):
 
2945
            if wt_versioned and not target_versioned:
2289
2946
                tt.unversion_file(trans_id)
2290
 
            if (name[1] is not None and
2291
 
                (name[0] != name[1] or parent[0] != parent[1])):
2292
 
                if name[1] == '' and parent[1] is None:
 
2947
            if (target_name is not None and
 
2948
                (wt_name != target_name or wt_parent != target_parent)):
 
2949
                if target_name == '' and target_parent is None:
2293
2950
                    parent_trans = ROOT_PARENT
2294
2951
                else:
2295
 
                    parent_trans = tt.trans_id_file_id(parent[1])
2296
 
                tt.adjust_path(name[1], parent_trans, trans_id)
2297
 
            if executable[0] != executable[1] and kind[1] == "file":
2298
 
                tt.set_executability(executable[1], trans_id)
2299
 
        for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
2300
 
            deferred_files):
2301
 
            tt.create_file(bytes, trans_id, mode_id)
 
2952
                    parent_trans = tt.trans_id_file_id(target_parent)
 
2953
                if wt_parent is None and wt_versioned:
 
2954
                    tt.adjust_root_path(target_name, parent_trans)
 
2955
                else:
 
2956
                    tt.adjust_path(target_name, parent_trans, trans_id)
 
2957
            if wt_executable != target_executable and target_kind == "file":
 
2958
                tt.set_executability(target_executable, trans_id)
 
2959
        if working_tree.supports_content_filtering():
 
2960
            for index, ((trans_id, mode_id), bytes) in enumerate(
 
2961
                target_tree.iter_files_bytes(deferred_files)):
 
2962
                file_id = deferred_files[index][0]
 
2963
                # We're reverting a tree to the target tree so using the
 
2964
                # target tree to find the file path seems the best choice
 
2965
                # here IMO - Ian C 27/Oct/2009
 
2966
                filter_tree_path = target_tree.id2path(file_id)
 
2967
                filters = working_tree._content_filter_stack(filter_tree_path)
 
2968
                bytes = filtered_output_bytes(bytes, filters,
 
2969
                    ContentFilterContext(filter_tree_path, working_tree))
 
2970
                tt.create_file(bytes, trans_id, mode_id)
 
2971
        else:
 
2972
            for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
 
2973
                deferred_files):
 
2974
                tt.create_file(bytes, trans_id, mode_id)
 
2975
        tt.fixup_new_roots()
2302
2976
    finally:
2303
2977
        if basis_tree is not None:
2304
2978
            basis_tree.unlock()
2305
2979
    return merge_modified
2306
2980
 
2307
2981
 
2308
 
def resolve_conflicts(tt, pb=DummyProgress(), pass_func=None):
 
2982
def resolve_conflicts(tt, pb=None, pass_func=None):
2309
2983
    """Make many conflict-resolution attempts, but die if they fail"""
2310
2984
    if pass_func is None:
2311
2985
        pass_func = conflict_pass
2312
2986
    new_conflicts = set()
 
2987
    pb = ui.ui_factory.nested_progress_bar()
2313
2988
    try:
2314
2989
        for n in range(10):
2315
2990
            pb.update('Resolution pass', n+1, 10)
2319
2994
            new_conflicts.update(pass_func(tt, conflicts))
2320
2995
        raise MalformedTransform(conflicts=conflicts)
2321
2996
    finally:
2322
 
        pb.clear()
 
2997
        pb.finished()
2323
2998
 
2324
2999
 
2325
3000
def conflict_pass(tt, conflicts, path_tree=None):
2344
3019
                existing_file, new_file = conflict[1], conflict[2]
2345
3020
            new_name = tt.final_name(existing_file)+'.moved'
2346
3021
            tt.adjust_path(new_name, final_parent, existing_file)
2347
 
            new_conflicts.add((c_type, 'Moved existing file to', 
 
3022
            new_conflicts.add((c_type, 'Moved existing file to',
2348
3023
                               existing_file, new_file))
2349
3024
        elif c_type == 'parent loop':
2350
3025
            # break the loop by undoing one of the ops that caused the loop
2354
3029
            new_conflicts.add((c_type, 'Cancelled move', cur,
2355
3030
                               tt.final_parent(cur),))
2356
3031
            tt.adjust_path(tt.final_name(cur), tt.get_tree_parent(cur), cur)
2357
 
            
 
3032
 
2358
3033
        elif c_type == 'missing parent':
2359
3034
            trans_id = conflict[1]
2360
 
            try:
2361
 
                tt.cancel_deletion(trans_id)
2362
 
                new_conflicts.add(('deleting parent', 'Not deleting', 
2363
 
                                   trans_id))
2364
 
            except KeyError:
 
3035
            if trans_id in tt._removed_contents:
 
3036
                cancel_deletion = True
 
3037
                orphans = tt._get_potential_orphans(trans_id)
 
3038
                if orphans:
 
3039
                    cancel_deletion = False
 
3040
                    # All children are orphans
 
3041
                    for o in orphans:
 
3042
                        try:
 
3043
                            tt.new_orphan(o, trans_id)
 
3044
                        except OrphaningError:
 
3045
                            # Something bad happened so we cancel the directory
 
3046
                            # deletion which will leave it in place with a
 
3047
                            # conflict. The user can deal with it from there.
 
3048
                            # Note that this also catch the case where we don't
 
3049
                            # want to create orphans and leave the directory in
 
3050
                            # place.
 
3051
                            cancel_deletion = True
 
3052
                            break
 
3053
                if cancel_deletion:
 
3054
                    # Cancel the directory deletion
 
3055
                    tt.cancel_deletion(trans_id)
 
3056
                    new_conflicts.add(('deleting parent', 'Not deleting',
 
3057
                                       trans_id))
 
3058
            else:
2365
3059
                create = True
2366
3060
                try:
2367
3061
                    tt.final_name(trans_id)
2370
3064
                        file_id = tt.final_file_id(trans_id)
2371
3065
                        if file_id is None:
2372
3066
                            file_id = tt.inactive_file_id(trans_id)
2373
 
                        entry = path_tree.inventory[file_id]
 
3067
                        _, entry = path_tree.iter_entries_by_dir(
 
3068
                            [file_id]).next()
2374
3069
                        # special-case the other tree root (move its
2375
3070
                        # children to current root)
2376
3071
                        if entry.parent_id is None:
2377
 
                            create=False
 
3072
                            create = False
2378
3073
                            moved = _reparent_transform_children(
2379
3074
                                tt, trans_id, tt.root)
2380
3075
                            for child in moved:
2392
3087
            file_id = tt.inactive_file_id(conflict[1])
2393
3088
            # special-case the other tree root (move its children instead)
2394
3089
            if path_tree and file_id in path_tree:
2395
 
                if path_tree.inventory[file_id].parent_id is None:
 
3090
                if path_tree.path2id('') == file_id:
 
3091
                    # This is the root entry, skip it
2396
3092
                    continue
2397
3093
            tt.version_file(file_id, conflict[1])
2398
3094
            new_conflicts.add((c_type, 'Versioned directory', conflict[1]))
2430
3126
        if len(conflict) == 3:
2431
3127
            yield Conflict.factory(c_type, action=action, path=modified_path,
2432
3128
                                     file_id=modified_id)
2433
 
             
 
3129
 
2434
3130
        else:
2435
3131
            conflicting_path = fp.get_path(conflict[3])
2436
3132
            conflicting_id = tt.final_file_id(conflict[3])
2437
3133
            yield Conflict.factory(c_type, action=action, path=modified_path,
2438
 
                                   file_id=modified_id, 
 
3134
                                   file_id=modified_id,
2439
3135
                                   conflict_path=conflicting_path,
2440
3136
                                   conflict_file_id=conflicting_id)
2441
3137
 
2448
3144
        self.pending_deletions = []
2449
3145
 
2450
3146
    def rename(self, from_, to):
2451
 
        """Rename a file from one path to another.  Functions like os.rename"""
 
3147
        """Rename a file from one path to another."""
2452
3148
        try:
2453
3149
            os.rename(from_, to)
2454
3150
        except OSError, e:
2455
3151
            if e.errno in (errno.EEXIST, errno.ENOTEMPTY):
2456
3152
                raise errors.FileExists(to, str(e))
2457
 
            raise
 
3153
            # normal OSError doesn't include filenames so it's hard to see where
 
3154
            # the problem is, see https://bugs.launchpad.net/bzr/+bug/491763
 
3155
            raise errors.TransformRenameFailed(from_, to, str(e), e.errno)
2458
3156
        self.past_renames.append((from_, to))
2459
3157
 
2460
3158
    def pre_delete(self, from_, to):
2470
3168
    def rollback(self):
2471
3169
        """Reverse all renames that have been performed"""
2472
3170
        for from_, to in reversed(self.past_renames):
2473
 
            os.rename(to, from_)
 
3171
            try:
 
3172
                os.rename(to, from_)
 
3173
            except OSError, e:
 
3174
                raise errors.TransformRenameFailed(to, from_, str(e), e.errno)
2474
3175
        # after rollback, don't reuse _FileMover
2475
3176
        past_renames = None
2476
3177
        pending_deletions = None