~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transform.py

  • Committer: Andrew Bennetts
  • Date: 2010-06-25 06:47:40 UTC
  • mto: (5050.3.16 2.2)
  • mto: This revision was merged to the branch mainline in revision 5365.
  • Revision ID: andrew.bennetts@canonical.com-20100625064740-k93ngat248kdcqdm
Remove merge_into_helper for now, as it currently has no callers.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2006-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
import os
18
18
import errno
19
19
from stat import S_ISREG, S_IEXEC
 
20
import time
20
21
 
21
22
from bzrlib.lazy_import import lazy_import
22
23
lazy_import(globals(), """
23
24
from bzrlib import (
24
25
    annotate,
 
26
    bencode,
25
27
    bzrdir,
 
28
    commit,
26
29
    delta,
27
30
    errors,
28
31
    inventory,
29
32
    multiparent,
30
33
    osutils,
31
34
    revision as _mod_revision,
 
35
    ui,
32
36
    )
33
 
from bzrlib.util import bencode
34
37
""")
35
38
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
36
 
                           ReusingTransform, NotVersionedError, CantMoveRoot,
 
39
                           ReusingTransform, CantMoveRoot,
37
40
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
38
41
                           UnableCreateSymlink)
 
42
from bzrlib.filters import filtered_output_bytes, ContentFilterContext
39
43
from bzrlib.inventory import InventoryEntry
40
44
from bzrlib.osutils import (
41
45
    delete_any,
47
51
    splitpath,
48
52
    supports_executable,
49
53
)
50
 
from bzrlib.progress import DummyProgress, ProgressPhase
 
54
from bzrlib.progress import ProgressPhase
51
55
from bzrlib.symbol_versioning import (
52
56
        deprecated_function,
53
57
        deprecated_in,
75
79
 
76
80
 
77
81
class TreeTransformBase(object):
78
 
    """The base class for TreeTransform and TreeTransformBase"""
 
82
    """The base class for TreeTransform and its kin."""
79
83
 
80
 
    def __init__(self, tree, limbodir, pb=DummyProgress(),
 
84
    def __init__(self, tree, pb=None,
81
85
                 case_sensitive=True):
82
86
        """Constructor.
83
87
 
84
88
        :param tree: The tree that will be transformed, but not necessarily
85
89
            the output tree.
86
 
        :param limbodir: A directory where new files can be stored until
87
 
            they are installed in their proper places
88
 
        :param pb: A ProgressBar indicating how much progress is being made
 
90
        :param pb: ignored
89
91
        :param case_sensitive: If True, the target of the transform is
90
92
            case sensitive, not just case preserving.
91
93
        """
92
94
        object.__init__(self)
93
95
        self._tree = tree
94
 
        self._limbodir = limbodir
95
 
        self._deletiondir = None
96
96
        self._id_number = 0
97
97
        # mapping of trans_id -> new basename
98
98
        self._new_name = {}
100
100
        self._new_parent = {}
101
101
        # mapping of trans_id with new contents -> new file_kind
102
102
        self._new_contents = {}
103
 
        # A mapping of transform ids to their limbo filename
104
 
        self._limbo_files = {}
105
 
        # A mapping of transform ids to a set of the transform ids of children
106
 
        # that their limbo directory has
107
 
        self._limbo_children = {}
108
 
        # Map transform ids to maps of child filename to child transform id
109
 
        self._limbo_children_names = {}
110
 
        # List of transform ids that need to be renamed from limbo into place
111
 
        self._needs_rename = set()
112
103
        # Set of trans_ids whose contents will be removed
113
104
        self._removed_contents = set()
114
105
        # Mapping of trans_id -> new execute-bit value
127
118
        self._tree_path_ids = {}
128
119
        # Mapping trans_id -> path in old tree
129
120
        self._tree_id_paths = {}
130
 
        # Cache of realpath results, to speed up canonical_path
131
 
        self._realpaths = {}
132
 
        # Cache of relpath results, to speed up canonical_path
133
 
        self._relpaths = {}
134
121
        # The trans_id that will be used as the tree root
135
122
        root_id = tree.get_root_id()
136
123
        if root_id is not None:
146
133
        # A counter of how many files have been renamed
147
134
        self.rename_count = 0
148
135
 
 
136
    def finalize(self):
 
137
        """Release the working tree lock, if held.
 
138
 
 
139
        This is required if apply has not been invoked, but can be invoked
 
140
        even after apply.
 
141
        """
 
142
        if self._tree is None:
 
143
            return
 
144
        self._tree.unlock()
 
145
        self._tree = None
 
146
 
149
147
    def __get_root(self):
150
148
        return self._new_root
151
149
 
152
150
    root = property(__get_root)
153
151
 
154
 
    def finalize(self):
155
 
        """Release the working tree lock, if held, clean up limbo dir.
156
 
 
157
 
        This is required if apply has not been invoked, but can be invoked
158
 
        even after apply.
159
 
        """
160
 
        if self._tree is None:
161
 
            return
162
 
        try:
163
 
            entries = [(self._limbo_name(t), t, k) for t, k in
164
 
                       self._new_contents.iteritems()]
165
 
            entries.sort(reverse=True)
166
 
            for path, trans_id, kind in entries:
167
 
                if kind == "directory":
168
 
                    os.rmdir(path)
169
 
                else:
170
 
                    os.unlink(path)
171
 
            try:
172
 
                os.rmdir(self._limbodir)
173
 
            except OSError:
174
 
                # We don't especially care *why* the dir is immortal.
175
 
                raise ImmortalLimbo(self._limbodir)
176
 
            try:
177
 
                if self._deletiondir is not None:
178
 
                    os.rmdir(self._deletiondir)
179
 
            except OSError:
180
 
                raise errors.ImmortalPendingDeletion(self._deletiondir)
181
 
        finally:
182
 
            self._tree.unlock()
183
 
            self._tree = None
184
 
 
185
152
    def _assign_id(self):
186
153
        """Produce a new tranform id"""
187
154
        new_id = "new-%s" % self._id_number
197
164
 
198
165
    def adjust_path(self, name, parent, trans_id):
199
166
        """Change the path that is assigned to a transaction id."""
 
167
        if parent is None:
 
168
            raise ValueError("Parent trans-id may not be None")
200
169
        if trans_id == self._new_root:
201
170
            raise CantMoveRoot
202
 
        previous_parent = self._new_parent.get(trans_id)
203
 
        previous_name = self._new_name.get(trans_id)
204
171
        self._new_name[trans_id] = name
205
172
        self._new_parent[trans_id] = parent
206
 
        if parent == ROOT_PARENT:
207
 
            if self._new_root is not None:
208
 
                raise ValueError("Cannot have multiple roots.")
209
 
            self._new_root = trans_id
210
 
        if (trans_id in self._limbo_files and
211
 
            trans_id not in self._needs_rename):
212
 
            self._rename_in_limbo([trans_id])
213
 
            self._limbo_children[previous_parent].remove(trans_id)
214
 
            del self._limbo_children_names[previous_parent][previous_name]
215
 
 
216
 
    def _rename_in_limbo(self, trans_ids):
217
 
        """Fix limbo names so that the right final path is produced.
218
 
 
219
 
        This means we outsmarted ourselves-- we tried to avoid renaming
220
 
        these files later by creating them with their final names in their
221
 
        final parents.  But now the previous name or parent is no longer
222
 
        suitable, so we have to rename them.
223
 
 
224
 
        Even for trans_ids that have no new contents, we must remove their
225
 
        entries from _limbo_files, because they are now stale.
226
 
        """
227
 
        for trans_id in trans_ids:
228
 
            old_path = self._limbo_files.pop(trans_id)
229
 
            if trans_id not in self._new_contents:
230
 
                continue
231
 
            new_path = self._limbo_name(trans_id)
232
 
            os.rename(old_path, new_path)
233
173
 
234
174
    def adjust_root_path(self, name, parent):
235
175
        """Emulate moving the root by moving all children, instead.
236
 
        
 
176
 
237
177
        We do this by undoing the association of root's transaction id with the
238
178
        current tree.  This allows us to create a new directory with that
239
 
        transaction id.  We unversion the root directory and version the 
 
179
        transaction id.  We unversion the root directory and version the
240
180
        physically new directory, and hope someone versions the tree root
241
181
        later.
242
182
        """
245
185
        # force moving all children of root
246
186
        for child_id in self.iter_tree_children(old_root):
247
187
            if child_id != parent:
248
 
                self.adjust_path(self.final_name(child_id), 
 
188
                self.adjust_path(self.final_name(child_id),
249
189
                                 self.final_parent(child_id), child_id)
250
190
            file_id = self.final_file_id(child_id)
251
191
            if file_id is not None:
252
192
                self.unversion_file(child_id)
253
193
            self.version_file(file_id, child_id)
254
 
        
 
194
 
255
195
        # the physical root needs a new transaction id
256
196
        self._tree_path_ids.pop("")
257
197
        self._tree_id_paths.pop(old_root)
263
203
        self.version_file(old_root_file_id, old_root)
264
204
        self.unversion_file(self._new_root)
265
205
 
 
206
    def fixup_new_roots(self):
 
207
        """Reinterpret requests to change the root directory
 
208
 
 
209
        Instead of creating a root directory, or moving an existing directory,
 
210
        all the attributes and children of the new root are applied to the
 
211
        existing root directory.
 
212
 
 
213
        This means that the old root trans-id becomes obsolete, so it is
 
214
        recommended only to invoke this after the root trans-id has become
 
215
        irrelevant.
 
216
        """
 
217
        new_roots = [k for k, v in self._new_parent.iteritems() if v is
 
218
                     ROOT_PARENT]
 
219
        if len(new_roots) < 1:
 
220
            return
 
221
        if len(new_roots) != 1:
 
222
            raise ValueError('A tree cannot have two roots!')
 
223
        if self._new_root is None:
 
224
            self._new_root = new_roots[0]
 
225
            return
 
226
        old_new_root = new_roots[0]
 
227
        # TODO: What to do if a old_new_root is present, but self._new_root is
 
228
        #       not listed as being removed? This code explicitly unversions
 
229
        #       the old root and versions it with the new file_id. Though that
 
230
        #       seems like an incomplete delta
 
231
 
 
232
        # unversion the new root's directory.
 
233
        file_id = self.final_file_id(old_new_root)
 
234
        if old_new_root in self._new_id:
 
235
            self.cancel_versioning(old_new_root)
 
236
        else:
 
237
            self.unversion_file(old_new_root)
 
238
        # if, at this stage, root still has an old file_id, zap it so we can
 
239
        # stick a new one in.
 
240
        if (self.tree_file_id(self._new_root) is not None and
 
241
            self._new_root not in self._removed_id):
 
242
            self.unversion_file(self._new_root)
 
243
        self.version_file(file_id, self._new_root)
 
244
 
 
245
        # Now move children of new root into old root directory.
 
246
        # Ensure all children are registered with the transaction, but don't
 
247
        # use directly-- some tree children have new parents
 
248
        list(self.iter_tree_children(old_new_root))
 
249
        # Move all children of new root into old root directory.
 
250
        for child in self.by_parent().get(old_new_root, []):
 
251
            self.adjust_path(self.final_name(child), self._new_root, child)
 
252
 
 
253
        # Ensure old_new_root has no directory.
 
254
        if old_new_root in self._new_contents:
 
255
            self.cancel_creation(old_new_root)
 
256
        else:
 
257
            self.delete_contents(old_new_root)
 
258
 
 
259
        # prevent deletion of root directory.
 
260
        if self._new_root in self._removed_contents:
 
261
            self.cancel_deletion(self._new_root)
 
262
 
 
263
        # destroy path info for old_new_root.
 
264
        del self._new_parent[old_new_root]
 
265
        del self._new_name[old_new_root]
 
266
 
266
267
    def trans_id_tree_file_id(self, inventory_id):
267
268
        """Determine the transaction id of a working tree file.
268
 
        
 
269
 
269
270
        This reflects only files that already exist, not ones that will be
270
271
        added by transactions.
271
272
        """
297
298
            else:
298
299
                return self.trans_id_tree_file_id(file_id)
299
300
 
300
 
    def canonical_path(self, path):
301
 
        """Get the canonical tree-relative path"""
302
 
        # don't follow final symlinks
303
 
        abs = self._tree.abspath(path)
304
 
        if abs in self._relpaths:
305
 
            return self._relpaths[abs]
306
 
        dirname, basename = os.path.split(abs)
307
 
        if dirname not in self._realpaths:
308
 
            self._realpaths[dirname] = os.path.realpath(dirname)
309
 
        dirname = self._realpaths[dirname]
310
 
        abs = pathjoin(dirname, basename)
311
 
        if dirname in self._relpaths:
312
 
            relpath = pathjoin(self._relpaths[dirname], basename)
313
 
            relpath = relpath.rstrip('/\\')
314
 
        else:
315
 
            relpath = self._tree.relpath(abs)
316
 
        self._relpaths[abs] = relpath
317
 
        return relpath
318
 
 
319
301
    def trans_id_tree_path(self, path):
320
302
        """Determine (and maybe set) the transaction ID for a tree path."""
321
303
        path = self.canonical_path(path)
331
313
            return ROOT_PARENT
332
314
        return self.trans_id_tree_path(os.path.dirname(path))
333
315
 
334
 
    def create_file(self, contents, trans_id, mode_id=None):
335
 
        """Schedule creation of a new file.
336
 
 
337
 
        See also new_file.
338
 
        
339
 
        Contents is an iterator of strings, all of which will be written
340
 
        to the target destination.
341
 
 
342
 
        New file takes the permissions of any existing file with that id,
343
 
        unless mode_id is specified.
344
 
        """
345
 
        name = self._limbo_name(trans_id)
346
 
        f = open(name, 'wb')
347
 
        try:
348
 
            try:
349
 
                unique_add(self._new_contents, trans_id, 'file')
350
 
            except:
351
 
                # Clean up the file, it never got registered so
352
 
                # TreeTransform.finalize() won't clean it up.
353
 
                f.close()
354
 
                os.unlink(name)
355
 
                raise
356
 
 
357
 
            f.writelines(contents)
358
 
        finally:
359
 
            f.close()
360
 
        self._set_mode(trans_id, mode_id, S_ISREG)
361
 
 
362
 
    def _set_mode(self, trans_id, mode_id, typefunc):
363
 
        """Set the mode of new file contents.
364
 
        The mode_id is the existing file to get the mode from (often the same
365
 
        as trans_id).  The operation is only performed if there's a mode match
366
 
        according to typefunc.
367
 
        """
368
 
        if mode_id is None:
369
 
            mode_id = trans_id
370
 
        try:
371
 
            old_path = self._tree_id_paths[mode_id]
372
 
        except KeyError:
373
 
            return
374
 
        try:
375
 
            mode = os.stat(self._tree.abspath(old_path)).st_mode
376
 
        except OSError, e:
377
 
            if e.errno in (errno.ENOENT, errno.ENOTDIR):
378
 
                # Either old_path doesn't exist, or the parent of the
379
 
                # target is not a directory (but will be one eventually)
380
 
                # Either way, we know it doesn't exist *right now*
381
 
                # See also bug #248448
382
 
                return
383
 
            else:
384
 
                raise
385
 
        if typefunc(mode):
386
 
            os.chmod(self._limbo_name(trans_id), mode)
387
 
 
388
 
    def create_hardlink(self, path, trans_id):
389
 
        """Schedule creation of a hard link"""
390
 
        name = self._limbo_name(trans_id)
391
 
        try:
392
 
            os.link(path, name)
393
 
        except OSError, e:
394
 
            if e.errno != errno.EPERM:
395
 
                raise
396
 
            raise errors.HardLinkNotSupported(path)
397
 
        try:
398
 
            unique_add(self._new_contents, trans_id, 'file')
399
 
        except:
400
 
            # Clean up the file, it never got registered so
401
 
            # TreeTransform.finalize() won't clean it up.
402
 
            os.unlink(name)
403
 
            raise
404
 
 
405
 
    def create_directory(self, trans_id):
406
 
        """Schedule creation of a new directory.
407
 
        
408
 
        See also new_directory.
409
 
        """
410
 
        os.mkdir(self._limbo_name(trans_id))
411
 
        unique_add(self._new_contents, trans_id, 'directory')
412
 
 
413
 
    def create_symlink(self, target, trans_id):
414
 
        """Schedule creation of a new symbolic link.
415
 
 
416
 
        target is a bytestring.
417
 
        See also new_symlink.
418
 
        """
419
 
        if has_symlinks():
420
 
            os.symlink(target, self._limbo_name(trans_id))
421
 
            unique_add(self._new_contents, trans_id, 'symlink')
422
 
        else:
423
 
            try:
424
 
                path = FinalPaths(self).get_path(trans_id)
425
 
            except KeyError:
426
 
                path = None
427
 
            raise UnableCreateSymlink(path=path)
428
 
 
429
 
    def cancel_creation(self, trans_id):
430
 
        """Cancel the creation of new file contents."""
431
 
        del self._new_contents[trans_id]
432
 
        children = self._limbo_children.get(trans_id)
433
 
        # if this is a limbo directory with children, move them before removing
434
 
        # the directory
435
 
        if children is not None:
436
 
            self._rename_in_limbo(children)
437
 
            del self._limbo_children[trans_id]
438
 
            del self._limbo_children_names[trans_id]
439
 
        delete_any(self._limbo_name(trans_id))
440
 
 
441
316
    def delete_contents(self, trans_id):
442
317
        """Schedule the contents of a path entry for deletion"""
 
318
        # Ensure that the object exists in the WorkingTree, this will raise an
 
319
        # exception if there is a problem
443
320
        self.tree_kind(trans_id)
444
321
        self._removed_contents.add(trans_id)
445
322
 
517
394
        new_ids.update(changed_kind)
518
395
        return sorted(FinalPaths(self).get_paths(new_ids))
519
396
 
520
 
    def tree_kind(self, trans_id):
521
 
        """Determine the file kind in the working tree.
522
 
 
523
 
        Raises NoSuchFile if the file does not exist
524
 
        """
525
 
        path = self._tree_id_paths.get(trans_id)
526
 
        if path is None:
527
 
            raise NoSuchFile(None)
528
 
        try:
529
 
            return file_kind(self._tree.abspath(path))
530
 
        except OSError, e:
531
 
            if e.errno != errno.ENOENT:
532
 
                raise
533
 
            else:
534
 
                raise NoSuchFile(path)
535
 
 
536
397
    def final_kind(self, trans_id):
537
398
        """Determine the final file kind, after any changes applied.
538
 
        
 
399
 
539
400
        Raises NoSuchFile if the file does not exist/has no contents.
540
401
        (It is conceivable that a path would be created without the
541
402
        corresponding contents insertion command)
561
422
 
562
423
    def final_file_id(self, trans_id):
563
424
        """Determine the file id after any changes are applied, or None.
564
 
        
 
425
 
565
426
        None indicates that the file will not be versioned after changes are
566
427
        applied.
567
428
        """
606
467
 
607
468
    def by_parent(self):
608
469
        """Return a map of parent: children for known parents.
609
 
        
 
470
 
610
471
        Only new paths and parents of tree files with assigned ids are used.
611
472
        """
612
473
        by_parent = {}
613
474
        items = list(self._new_parent.iteritems())
614
 
        items.extend((t, self.final_parent(t)) for t in 
 
475
        items.extend((t, self.final_parent(t)) for t in
615
476
                      self._tree_id_paths.keys())
616
477
        for trans_id, parent_id in items:
617
478
            if parent_id not in by_parent:
645
506
        conflicts.extend(self._overwrite_conflicts())
646
507
        return conflicts
647
508
 
 
509
    def _check_malformed(self):
 
510
        conflicts = self.find_conflicts()
 
511
        if len(conflicts) != 0:
 
512
            raise MalformedTransform(conflicts=conflicts)
 
513
 
648
514
    def _add_tree_children(self):
649
515
        """Add all the children of all active parents to the known paths.
650
516
 
652
518
        removed.  This is a necessary first step in detecting conflicts.
653
519
        """
654
520
        parents = self.by_parent().keys()
655
 
        parents.extend([t for t in self._removed_contents if 
 
521
        parents.extend([t for t in self._removed_contents if
656
522
                        self.tree_kind(t) == 'directory'])
657
523
        for trans_id in self._removed_id:
658
524
            file_id = self.tree_file_id(trans_id)
666
532
            # ensure that all children are registered with the transaction
667
533
            list(self.iter_tree_children(parent_id))
668
534
 
669
 
    def iter_tree_children(self, parent_id):
670
 
        """Iterate through the entry's tree children, if any"""
671
 
        try:
672
 
            path = self._tree_id_paths[parent_id]
673
 
        except KeyError:
674
 
            return
675
 
        try:
676
 
            children = os.listdir(self._tree.abspath(path))
677
 
        except OSError, e:
678
 
            if not (osutils._is_error_enotdir(e)
679
 
                    or e.errno in (errno.ENOENT, errno.ESRCH)):
680
 
                raise
681
 
            return
682
 
 
683
 
        for child in children:
684
 
            childpath = joinpath(path, child)
685
 
            if self._tree.is_control_filename(childpath):
686
 
                continue
687
 
            yield self.trans_id_tree_path(childpath)
688
 
 
689
535
    def has_named_child(self, by_parent, parent_id, name):
690
536
        try:
691
537
            children = by_parent[parent_id]
745
591
 
746
592
    def _improper_versioning(self):
747
593
        """Cannot version a file with no contents, or a bad type.
748
 
        
 
594
 
749
595
        However, existing entries with no contents are okay.
750
596
        """
751
597
        conflicts = []
761
607
 
762
608
    def _executability_conflicts(self):
763
609
        """Check for bad executability changes.
764
 
        
 
610
 
765
611
        Only versioned files may have their executability set, because
766
612
        1. only versioned entries can have executability under windows
767
613
        2. only files can be executable.  (The execute bit on a directory
866
712
            return True
867
713
        return False
868
714
 
869
 
    def _limbo_name(self, trans_id):
870
 
        """Generate the limbo name of a file"""
871
 
        limbo_name = self._limbo_files.get(trans_id)
872
 
        if limbo_name is not None:
873
 
            return limbo_name
874
 
        parent = self._new_parent.get(trans_id)
875
 
        # if the parent directory is already in limbo (e.g. when building a
876
 
        # tree), choose a limbo name inside the parent, to reduce further
877
 
        # renames.
878
 
        use_direct_path = False
879
 
        if self._new_contents.get(parent) == 'directory':
880
 
            filename = self._new_name.get(trans_id)
881
 
            if filename is not None:
882
 
                if parent not in self._limbo_children:
883
 
                    self._limbo_children[parent] = set()
884
 
                    self._limbo_children_names[parent] = {}
885
 
                    use_direct_path = True
886
 
                # the direct path can only be used if no other file has
887
 
                # already taken this pathname, i.e. if the name is unused, or
888
 
                # if it is already associated with this trans_id.
889
 
                elif self._case_sensitive_target:
890
 
                    if (self._limbo_children_names[parent].get(filename)
891
 
                        in (trans_id, None)):
892
 
                        use_direct_path = True
893
 
                else:
894
 
                    for l_filename, l_trans_id in\
895
 
                        self._limbo_children_names[parent].iteritems():
896
 
                        if l_trans_id == trans_id:
897
 
                            continue
898
 
                        if l_filename.lower() == filename.lower():
899
 
                            break
900
 
                    else:
901
 
                        use_direct_path = True
902
 
 
903
 
        if use_direct_path:
904
 
            limbo_name = pathjoin(self._limbo_files[parent], filename)
905
 
            self._limbo_children[parent].add(trans_id)
906
 
            self._limbo_children_names[parent][filename] = trans_id
907
 
        else:
908
 
            limbo_name = pathjoin(self._limbodir, trans_id)
909
 
            self._needs_rename.add(trans_id)
910
 
        self._limbo_files[trans_id] = limbo_name
911
 
        return limbo_name
912
 
 
913
715
    def _set_executability(self, path, trans_id):
914
716
        """Set the executability of versioned files """
915
717
        if supports_executable():
936
738
            self.version_file(file_id, trans_id)
937
739
        return trans_id
938
740
 
939
 
    def new_file(self, name, parent_id, contents, file_id=None, 
 
741
    def new_file(self, name, parent_id, contents, file_id=None,
940
742
                 executable=None):
941
743
        """Convenience method to create files.
942
 
        
 
744
 
943
745
        name is the name of the file to create.
944
746
        parent_id is the transaction id of the parent directory of the file.
945
747
        contents is an iterator of bytestrings, which will be used to produce
965
767
        """
966
768
        trans_id = self._new_entry(name, parent_id, file_id)
967
769
        self.create_directory(trans_id)
968
 
        return trans_id 
 
770
        return trans_id
969
771
 
970
772
    def new_symlink(self, name, parent_id, target, file_id=None):
971
773
        """Convenience method to create symbolic link.
972
 
        
 
774
 
973
775
        name is the name of the symlink to create.
974
776
        parent_id is the transaction id of the parent directory of the symlink.
975
777
        target is a bytestring of the target of the symlink.
1121
923
    def get_preview_tree(self):
1122
924
        """Return a tree representing the result of the transform.
1123
925
 
1124
 
        This tree only supports the subset of Tree functionality required
1125
 
        by show_diff_trees.  It must only be compared to tt._tree.
 
926
        The tree is a snapshot, and altering the TreeTransform will invalidate
 
927
        it.
1126
928
        """
1127
929
        return _PreviewTree(self)
1128
930
 
 
931
    def commit(self, branch, message, merge_parents=None, strict=False,
 
932
               timestamp=None, timezone=None, committer=None, authors=None,
 
933
               revprops=None, revision_id=None):
 
934
        """Commit the result of this TreeTransform to a branch.
 
935
 
 
936
        :param branch: The branch to commit to.
 
937
        :param message: The message to attach to the commit.
 
938
        :param merge_parents: Additional parent revision-ids specified by
 
939
            pending merges.
 
940
        :param strict: If True, abort the commit if there are unversioned
 
941
            files.
 
942
        :param timestamp: if not None, seconds-since-epoch for the time and
 
943
            date.  (May be a float.)
 
944
        :param timezone: Optional timezone for timestamp, as an offset in
 
945
            seconds.
 
946
        :param committer: Optional committer in email-id format.
 
947
            (e.g. "J Random Hacker <jrandom@example.com>")
 
948
        :param authors: Optional list of authors in email-id format.
 
949
        :param revprops: Optional dictionary of revision properties.
 
950
        :param revision_id: Optional revision id.  (Specifying a revision-id
 
951
            may reduce performance for some non-native formats.)
 
952
        :return: The revision_id of the revision committed.
 
953
        """
 
954
        self._check_malformed()
 
955
        if strict:
 
956
            unversioned = set(self._new_contents).difference(set(self._new_id))
 
957
            for trans_id in unversioned:
 
958
                if self.final_file_id(trans_id) is None:
 
959
                    raise errors.StrictCommitFailed()
 
960
 
 
961
        revno, last_rev_id = branch.last_revision_info()
 
962
        if last_rev_id == _mod_revision.NULL_REVISION:
 
963
            if merge_parents is not None:
 
964
                raise ValueError('Cannot supply merge parents for first'
 
965
                                 ' commit.')
 
966
            parent_ids = []
 
967
        else:
 
968
            parent_ids = [last_rev_id]
 
969
            if merge_parents is not None:
 
970
                parent_ids.extend(merge_parents)
 
971
        if self._tree.get_revision_id() != last_rev_id:
 
972
            raise ValueError('TreeTransform not based on branch basis: %s' %
 
973
                             self._tree.get_revision_id())
 
974
        revprops = commit.Commit.update_revprops(revprops, branch, authors)
 
975
        builder = branch.get_commit_builder(parent_ids,
 
976
                                            timestamp=timestamp,
 
977
                                            timezone=timezone,
 
978
                                            committer=committer,
 
979
                                            revprops=revprops,
 
980
                                            revision_id=revision_id)
 
981
        preview = self.get_preview_tree()
 
982
        list(builder.record_iter_changes(preview, last_rev_id,
 
983
                                         self.iter_changes()))
 
984
        builder.finish_inventory()
 
985
        revision_id = builder.commit(message)
 
986
        branch.set_last_revision_info(revno + 1, revision_id)
 
987
        return revision_id
 
988
 
1129
989
    def _text_parent(self, trans_id):
1130
990
        file_id = self.tree_file_id(trans_id)
1131
991
        try:
1175
1035
                                      (('attribs',),))
1176
1036
        for trans_id, kind in self._new_contents.items():
1177
1037
            if kind == 'file':
1178
 
                cur_file = open(self._limbo_name(trans_id), 'rb')
1179
 
                try:
1180
 
                    lines = osutils.chunks_to_lines(cur_file.readlines())
1181
 
                finally:
1182
 
                    cur_file.close()
 
1038
                lines = osutils.chunks_to_lines(
 
1039
                    self._read_file_chunks(trans_id))
1183
1040
                parents = self._get_parents_lines(trans_id)
1184
1041
                mpdiff = multiparent.MultiParent.from_lines(lines, parents)
1185
1042
                content = ''.join(mpdiff.to_patch())
1186
1043
            if kind == 'directory':
1187
1044
                content = ''
1188
1045
            if kind == 'symlink':
1189
 
                content = os.readlink(self._limbo_name(trans_id))
 
1046
                content = self._read_symlink_target(trans_id)
1190
1047
            yield serializer.bytes_record(content, ((trans_id, kind),))
1191
1048
 
1192
 
 
1193
1049
    def deserialize(self, records):
1194
1050
        """Deserialize a stored TreeTransform.
1195
1051
 
1226
1082
                self.create_symlink(content.decode('utf-8'), trans_id)
1227
1083
 
1228
1084
 
1229
 
class TreeTransform(TreeTransformBase):
 
1085
class DiskTreeTransform(TreeTransformBase):
 
1086
    """Tree transform storing its contents on disk."""
 
1087
 
 
1088
    def __init__(self, tree, limbodir, pb=None,
 
1089
                 case_sensitive=True):
 
1090
        """Constructor.
 
1091
        :param tree: The tree that will be transformed, but not necessarily
 
1092
            the output tree.
 
1093
        :param limbodir: A directory where new files can be stored until
 
1094
            they are installed in their proper places
 
1095
        :param pb: ignored
 
1096
        :param case_sensitive: If True, the target of the transform is
 
1097
            case sensitive, not just case preserving.
 
1098
        """
 
1099
        TreeTransformBase.__init__(self, tree, pb, case_sensitive)
 
1100
        self._limbodir = limbodir
 
1101
        self._deletiondir = None
 
1102
        # A mapping of transform ids to their limbo filename
 
1103
        self._limbo_files = {}
 
1104
        # A mapping of transform ids to a set of the transform ids of children
 
1105
        # that their limbo directory has
 
1106
        self._limbo_children = {}
 
1107
        # Map transform ids to maps of child filename to child transform id
 
1108
        self._limbo_children_names = {}
 
1109
        # List of transform ids that need to be renamed from limbo into place
 
1110
        self._needs_rename = set()
 
1111
        self._creation_mtime = None
 
1112
 
 
1113
    def finalize(self):
 
1114
        """Release the working tree lock, if held, clean up limbo dir.
 
1115
 
 
1116
        This is required if apply has not been invoked, but can be invoked
 
1117
        even after apply.
 
1118
        """
 
1119
        if self._tree is None:
 
1120
            return
 
1121
        try:
 
1122
            entries = [(self._limbo_name(t), t, k) for t, k in
 
1123
                       self._new_contents.iteritems()]
 
1124
            entries.sort(reverse=True)
 
1125
            for path, trans_id, kind in entries:
 
1126
                delete_any(path)
 
1127
            try:
 
1128
                delete_any(self._limbodir)
 
1129
            except OSError:
 
1130
                # We don't especially care *why* the dir is immortal.
 
1131
                raise ImmortalLimbo(self._limbodir)
 
1132
            try:
 
1133
                if self._deletiondir is not None:
 
1134
                    delete_any(self._deletiondir)
 
1135
            except OSError:
 
1136
                raise errors.ImmortalPendingDeletion(self._deletiondir)
 
1137
        finally:
 
1138
            TreeTransformBase.finalize(self)
 
1139
 
 
1140
    def _limbo_name(self, trans_id):
 
1141
        """Generate the limbo name of a file"""
 
1142
        limbo_name = self._limbo_files.get(trans_id)
 
1143
        if limbo_name is None:
 
1144
            limbo_name = self._generate_limbo_path(trans_id)
 
1145
            self._limbo_files[trans_id] = limbo_name
 
1146
        return limbo_name
 
1147
 
 
1148
    def _generate_limbo_path(self, trans_id):
 
1149
        """Generate a limbo path using the trans_id as the relative path.
 
1150
 
 
1151
        This is suitable as a fallback, and when the transform should not be
 
1152
        sensitive to the path encoding of the limbo directory.
 
1153
        """
 
1154
        self._needs_rename.add(trans_id)
 
1155
        return pathjoin(self._limbodir, trans_id)
 
1156
 
 
1157
    def adjust_path(self, name, parent, trans_id):
 
1158
        previous_parent = self._new_parent.get(trans_id)
 
1159
        previous_name = self._new_name.get(trans_id)
 
1160
        TreeTransformBase.adjust_path(self, name, parent, trans_id)
 
1161
        if (trans_id in self._limbo_files and
 
1162
            trans_id not in self._needs_rename):
 
1163
            self._rename_in_limbo([trans_id])
 
1164
            if previous_parent != parent:
 
1165
                self._limbo_children[previous_parent].remove(trans_id)
 
1166
            if previous_parent != parent or previous_name != name:
 
1167
                del self._limbo_children_names[previous_parent][previous_name]
 
1168
 
 
1169
    def _rename_in_limbo(self, trans_ids):
 
1170
        """Fix limbo names so that the right final path is produced.
 
1171
 
 
1172
        This means we outsmarted ourselves-- we tried to avoid renaming
 
1173
        these files later by creating them with their final names in their
 
1174
        final parents.  But now the previous name or parent is no longer
 
1175
        suitable, so we have to rename them.
 
1176
 
 
1177
        Even for trans_ids that have no new contents, we must remove their
 
1178
        entries from _limbo_files, because they are now stale.
 
1179
        """
 
1180
        for trans_id in trans_ids:
 
1181
            old_path = self._limbo_files.pop(trans_id)
 
1182
            if trans_id not in self._new_contents:
 
1183
                continue
 
1184
            new_path = self._limbo_name(trans_id)
 
1185
            osutils.rename(old_path, new_path)
 
1186
            for descendant in self._limbo_descendants(trans_id):
 
1187
                desc_path = self._limbo_files[descendant]
 
1188
                desc_path = new_path + desc_path[len(old_path):]
 
1189
                self._limbo_files[descendant] = desc_path
 
1190
 
 
1191
    def _limbo_descendants(self, trans_id):
 
1192
        """Return the set of trans_ids whose limbo paths descend from this."""
 
1193
        descendants = set(self._limbo_children.get(trans_id, []))
 
1194
        for descendant in list(descendants):
 
1195
            descendants.update(self._limbo_descendants(descendant))
 
1196
        return descendants
 
1197
 
 
1198
    def create_file(self, contents, trans_id, mode_id=None):
 
1199
        """Schedule creation of a new file.
 
1200
 
 
1201
        See also new_file.
 
1202
 
 
1203
        Contents is an iterator of strings, all of which will be written
 
1204
        to the target destination.
 
1205
 
 
1206
        New file takes the permissions of any existing file with that id,
 
1207
        unless mode_id is specified.
 
1208
        """
 
1209
        name = self._limbo_name(trans_id)
 
1210
        f = open(name, 'wb')
 
1211
        try:
 
1212
            try:
 
1213
                unique_add(self._new_contents, trans_id, 'file')
 
1214
            except:
 
1215
                # Clean up the file, it never got registered so
 
1216
                # TreeTransform.finalize() won't clean it up.
 
1217
                f.close()
 
1218
                os.unlink(name)
 
1219
                raise
 
1220
 
 
1221
            f.writelines(contents)
 
1222
        finally:
 
1223
            f.close()
 
1224
        self._set_mtime(name)
 
1225
        self._set_mode(trans_id, mode_id, S_ISREG)
 
1226
 
 
1227
    def _read_file_chunks(self, trans_id):
 
1228
        cur_file = open(self._limbo_name(trans_id), 'rb')
 
1229
        try:
 
1230
            return cur_file.readlines()
 
1231
        finally:
 
1232
            cur_file.close()
 
1233
 
 
1234
    def _read_symlink_target(self, trans_id):
 
1235
        return os.readlink(self._limbo_name(trans_id))
 
1236
 
 
1237
    def _set_mtime(self, path):
 
1238
        """All files that are created get the same mtime.
 
1239
 
 
1240
        This time is set by the first object to be created.
 
1241
        """
 
1242
        if self._creation_mtime is None:
 
1243
            self._creation_mtime = time.time()
 
1244
        os.utime(path, (self._creation_mtime, self._creation_mtime))
 
1245
 
 
1246
    def create_hardlink(self, path, trans_id):
 
1247
        """Schedule creation of a hard link"""
 
1248
        name = self._limbo_name(trans_id)
 
1249
        try:
 
1250
            os.link(path, name)
 
1251
        except OSError, e:
 
1252
            if e.errno != errno.EPERM:
 
1253
                raise
 
1254
            raise errors.HardLinkNotSupported(path)
 
1255
        try:
 
1256
            unique_add(self._new_contents, trans_id, 'file')
 
1257
        except:
 
1258
            # Clean up the file, it never got registered so
 
1259
            # TreeTransform.finalize() won't clean it up.
 
1260
            os.unlink(name)
 
1261
            raise
 
1262
 
 
1263
    def create_directory(self, trans_id):
 
1264
        """Schedule creation of a new directory.
 
1265
 
 
1266
        See also new_directory.
 
1267
        """
 
1268
        os.mkdir(self._limbo_name(trans_id))
 
1269
        unique_add(self._new_contents, trans_id, 'directory')
 
1270
 
 
1271
    def create_symlink(self, target, trans_id):
 
1272
        """Schedule creation of a new symbolic link.
 
1273
 
 
1274
        target is a bytestring.
 
1275
        See also new_symlink.
 
1276
        """
 
1277
        if has_symlinks():
 
1278
            os.symlink(target, self._limbo_name(trans_id))
 
1279
            unique_add(self._new_contents, trans_id, 'symlink')
 
1280
        else:
 
1281
            try:
 
1282
                path = FinalPaths(self).get_path(trans_id)
 
1283
            except KeyError:
 
1284
                path = None
 
1285
            raise UnableCreateSymlink(path=path)
 
1286
 
 
1287
    def cancel_creation(self, trans_id):
 
1288
        """Cancel the creation of new file contents."""
 
1289
        del self._new_contents[trans_id]
 
1290
        children = self._limbo_children.get(trans_id)
 
1291
        # if this is a limbo directory with children, move them before removing
 
1292
        # the directory
 
1293
        if children is not None:
 
1294
            self._rename_in_limbo(children)
 
1295
            del self._limbo_children[trans_id]
 
1296
            del self._limbo_children_names[trans_id]
 
1297
        delete_any(self._limbo_name(trans_id))
 
1298
 
 
1299
 
 
1300
class TreeTransform(DiskTreeTransform):
1230
1301
    """Represent a tree transformation.
1231
1302
 
1232
1303
    This object is designed to support incremental generation of the transform,
1291
1362
    FileMover does not delete files until it is sure that a rollback will not
1292
1363
    happen.
1293
1364
    """
1294
 
    def __init__(self, tree, pb=DummyProgress()):
 
1365
    def __init__(self, tree, pb=None):
1295
1366
        """Note: a tree_write lock is taken on the tree.
1296
1367
 
1297
1368
        Use TreeTransform.finalize() to release the lock (can be omitted if
1318
1389
            tree.unlock()
1319
1390
            raise
1320
1391
 
1321
 
        TreeTransformBase.__init__(self, tree, limbodir, pb,
 
1392
        # Cache of realpath results, to speed up canonical_path
 
1393
        self._realpaths = {}
 
1394
        # Cache of relpath results, to speed up canonical_path
 
1395
        self._relpaths = {}
 
1396
        DiskTreeTransform.__init__(self, tree, limbodir, pb,
1322
1397
                                   tree.case_sensitive)
1323
1398
        self._deletiondir = deletiondir
1324
1399
 
 
1400
    def canonical_path(self, path):
 
1401
        """Get the canonical tree-relative path"""
 
1402
        # don't follow final symlinks
 
1403
        abs = self._tree.abspath(path)
 
1404
        if abs in self._relpaths:
 
1405
            return self._relpaths[abs]
 
1406
        dirname, basename = os.path.split(abs)
 
1407
        if dirname not in self._realpaths:
 
1408
            self._realpaths[dirname] = os.path.realpath(dirname)
 
1409
        dirname = self._realpaths[dirname]
 
1410
        abs = pathjoin(dirname, basename)
 
1411
        if dirname in self._relpaths:
 
1412
            relpath = pathjoin(self._relpaths[dirname], basename)
 
1413
            relpath = relpath.rstrip('/\\')
 
1414
        else:
 
1415
            relpath = self._tree.relpath(abs)
 
1416
        self._relpaths[abs] = relpath
 
1417
        return relpath
 
1418
 
 
1419
    def tree_kind(self, trans_id):
 
1420
        """Determine the file kind in the working tree.
 
1421
 
 
1422
        Raises NoSuchFile if the file does not exist
 
1423
        """
 
1424
        path = self._tree_id_paths.get(trans_id)
 
1425
        if path is None:
 
1426
            raise NoSuchFile(None)
 
1427
        try:
 
1428
            return file_kind(self._tree.abspath(path))
 
1429
        except OSError, e:
 
1430
            if e.errno != errno.ENOENT:
 
1431
                raise
 
1432
            else:
 
1433
                raise NoSuchFile(path)
 
1434
 
 
1435
    def _set_mode(self, trans_id, mode_id, typefunc):
 
1436
        """Set the mode of new file contents.
 
1437
        The mode_id is the existing file to get the mode from (often the same
 
1438
        as trans_id).  The operation is only performed if there's a mode match
 
1439
        according to typefunc.
 
1440
        """
 
1441
        if mode_id is None:
 
1442
            mode_id = trans_id
 
1443
        try:
 
1444
            old_path = self._tree_id_paths[mode_id]
 
1445
        except KeyError:
 
1446
            return
 
1447
        try:
 
1448
            mode = os.stat(self._tree.abspath(old_path)).st_mode
 
1449
        except OSError, e:
 
1450
            if e.errno in (errno.ENOENT, errno.ENOTDIR):
 
1451
                # Either old_path doesn't exist, or the parent of the
 
1452
                # target is not a directory (but will be one eventually)
 
1453
                # Either way, we know it doesn't exist *right now*
 
1454
                # See also bug #248448
 
1455
                return
 
1456
            else:
 
1457
                raise
 
1458
        if typefunc(mode):
 
1459
            os.chmod(self._limbo_name(trans_id), mode)
 
1460
 
 
1461
    def iter_tree_children(self, parent_id):
 
1462
        """Iterate through the entry's tree children, if any"""
 
1463
        try:
 
1464
            path = self._tree_id_paths[parent_id]
 
1465
        except KeyError:
 
1466
            return
 
1467
        try:
 
1468
            children = os.listdir(self._tree.abspath(path))
 
1469
        except OSError, e:
 
1470
            if not (osutils._is_error_enotdir(e)
 
1471
                    or e.errno in (errno.ENOENT, errno.ESRCH)):
 
1472
                raise
 
1473
            return
 
1474
 
 
1475
        for child in children:
 
1476
            childpath = joinpath(path, child)
 
1477
            if self._tree.is_control_filename(childpath):
 
1478
                continue
 
1479
            yield self.trans_id_tree_path(childpath)
 
1480
 
 
1481
    def _generate_limbo_path(self, trans_id):
 
1482
        """Generate a limbo path using the final path if possible.
 
1483
 
 
1484
        This optimizes the performance of applying the tree transform by
 
1485
        avoiding renames.  These renames can be avoided only when the parent
 
1486
        directory is already scheduled for creation.
 
1487
 
 
1488
        If the final path cannot be used, falls back to using the trans_id as
 
1489
        the relpath.
 
1490
        """
 
1491
        parent = self._new_parent.get(trans_id)
 
1492
        # if the parent directory is already in limbo (e.g. when building a
 
1493
        # tree), choose a limbo name inside the parent, to reduce further
 
1494
        # renames.
 
1495
        use_direct_path = False
 
1496
        if self._new_contents.get(parent) == 'directory':
 
1497
            filename = self._new_name.get(trans_id)
 
1498
            if filename is not None:
 
1499
                if parent not in self._limbo_children:
 
1500
                    self._limbo_children[parent] = set()
 
1501
                    self._limbo_children_names[parent] = {}
 
1502
                    use_direct_path = True
 
1503
                # the direct path can only be used if no other file has
 
1504
                # already taken this pathname, i.e. if the name is unused, or
 
1505
                # if it is already associated with this trans_id.
 
1506
                elif self._case_sensitive_target:
 
1507
                    if (self._limbo_children_names[parent].get(filename)
 
1508
                        in (trans_id, None)):
 
1509
                        use_direct_path = True
 
1510
                else:
 
1511
                    for l_filename, l_trans_id in\
 
1512
                        self._limbo_children_names[parent].iteritems():
 
1513
                        if l_trans_id == trans_id:
 
1514
                            continue
 
1515
                        if l_filename.lower() == filename.lower():
 
1516
                            break
 
1517
                    else:
 
1518
                        use_direct_path = True
 
1519
 
 
1520
        if not use_direct_path:
 
1521
            return DiskTreeTransform._generate_limbo_path(self, trans_id)
 
1522
 
 
1523
        limbo_name = pathjoin(self._limbo_files[parent], filename)
 
1524
        self._limbo_children[parent].add(trans_id)
 
1525
        self._limbo_children_names[parent][filename] = trans_id
 
1526
        return limbo_name
 
1527
 
 
1528
 
1325
1529
    def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
1326
1530
        """Apply all changes to the inventory and filesystem.
1327
1531
 
1337
1541
        :param _mover: Supply an alternate FileMover, for testing
1338
1542
        """
1339
1543
        if not no_conflicts:
1340
 
            conflicts = self.find_conflicts()
1341
 
            if len(conflicts) != 0:
1342
 
                raise MalformedTransform(conflicts=conflicts)
 
1544
            self._check_malformed()
1343
1545
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1344
1546
        try:
1345
1547
            if precomputed_delta is None:
1449
1651
                child_pb.update('removing file', num, len(tree_paths))
1450
1652
                full_path = self._tree.abspath(path)
1451
1653
                if trans_id in self._removed_contents:
1452
 
                    mover.pre_delete(full_path, os.path.join(self._deletiondir,
1453
 
                                     trans_id))
1454
 
                elif trans_id in self._new_name or trans_id in \
1455
 
                    self._new_parent:
 
1654
                    delete_path = os.path.join(self._deletiondir, trans_id)
 
1655
                    mover.pre_delete(full_path, delete_path)
 
1656
                elif (trans_id in self._new_name
 
1657
                      or trans_id in self._new_parent):
1456
1658
                    try:
1457
1659
                        mover.rename(full_path, self._limbo_name(trans_id))
1458
 
                    except OSError, e:
 
1660
                    except errors.TransformRenameFailed, e:
1459
1661
                        if e.errno != errno.ENOENT:
1460
1662
                            raise
1461
1663
                    else:
1486
1688
                if trans_id in self._needs_rename:
1487
1689
                    try:
1488
1690
                        mover.rename(self._limbo_name(trans_id), full_path)
1489
 
                    except OSError, e:
 
1691
                    except errors.TransformRenameFailed, e:
1490
1692
                        # We may be renaming a dangling inventory id
1491
1693
                        if e.errno != errno.ENOENT:
1492
1694
                            raise
1504
1706
        return modified_paths
1505
1707
 
1506
1708
 
1507
 
class TransformPreview(TreeTransformBase):
 
1709
class TransformPreview(DiskTreeTransform):
1508
1710
    """A TreeTransform for generating preview trees.
1509
1711
 
1510
1712
    Unlike TreeTransform, this version works when the input tree is a
1512
1714
    unversioned files in the input tree.
1513
1715
    """
1514
1716
 
1515
 
    def __init__(self, tree, pb=DummyProgress(), case_sensitive=True):
 
1717
    def __init__(self, tree, pb=None, case_sensitive=True):
1516
1718
        tree.lock_read()
1517
1719
        limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
1518
 
        TreeTransformBase.__init__(self, tree, limbodir, pb, case_sensitive)
 
1720
        DiskTreeTransform.__init__(self, tree, limbodir, pb, case_sensitive)
1519
1721
 
1520
1722
    def canonical_path(self, path):
1521
1723
        return path
1563
1765
        self._all_children_cache = {}
1564
1766
        self._path2trans_id_cache = {}
1565
1767
        self._final_name_cache = {}
1566
 
 
1567
 
    def _changes(self, file_id):
1568
 
        for changes in self._transform.iter_changes():
1569
 
            if changes[0] == file_id:
1570
 
                return changes
 
1768
        self._iter_changes_cache = dict((c[0], c) for c in
 
1769
                                        self._transform.iter_changes())
1571
1770
 
1572
1771
    def _content_change(self, file_id):
1573
1772
        """Return True if the content of this file changed"""
1574
 
        changes = self._changes(file_id)
 
1773
        changes = self._iter_changes_cache.get(file_id)
1575
1774
        # changes[2] is true if the file content changed.  See
1576
1775
        # InterTree.iter_changes.
1577
1776
        return (changes is not None and changes[2])
1593
1792
        parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
1594
1793
                       self._iter_parent_trees()]
1595
1794
        vf.add_lines((file_id, tree_revision), parent_keys,
1596
 
                     self.get_file(file_id).readlines())
 
1795
                     self.get_file_lines(file_id))
1597
1796
        repo = self._get_repository()
1598
1797
        base_vf = repo.texts
1599
1798
        if base_vf not in vf.fallback_versionedfiles:
1621
1820
            executable = self.is_executable(file_id, path)
1622
1821
        return kind, executable, None
1623
1822
 
 
1823
    def is_locked(self):
 
1824
        return False
 
1825
 
1624
1826
    def lock_read(self):
1625
1827
        # Perhaps in theory, this should lock the TreeTransform?
1626
 
        pass
 
1828
        return self
1627
1829
 
1628
1830
    def unlock(self):
1629
1831
        pass
1646
1848
    def __iter__(self):
1647
1849
        return iter(self.all_file_ids())
1648
1850
 
1649
 
    def has_id(self, file_id):
 
1851
    def _has_id(self, file_id, fallback_check):
1650
1852
        if file_id in self._transform._r_new_id:
1651
1853
            return True
1652
1854
        elif file_id in set([self._transform.tree_file_id(trans_id) for
1653
1855
            trans_id in self._transform._removed_id]):
1654
1856
            return False
1655
1857
        else:
1656
 
            return self._transform._tree.has_id(file_id)
 
1858
            return fallback_check(file_id)
 
1859
 
 
1860
    def has_id(self, file_id):
 
1861
        return self._has_id(file_id, self._transform._tree.has_id)
 
1862
 
 
1863
    def has_or_had_id(self, file_id):
 
1864
        return self._has_id(file_id, self._transform._tree.has_or_had_id)
1657
1865
 
1658
1866
    def _path2trans_id(self, path):
1659
1867
        # We must not use None here, because that is a valid value to store.
1712
1920
            if self._transform.final_file_id(trans_id) is None:
1713
1921
                yield self._final_paths._determine_path(trans_id)
1714
1922
 
1715
 
    def _make_inv_entries(self, ordered_entries, specific_file_ids):
 
1923
    def _make_inv_entries(self, ordered_entries, specific_file_ids=None,
 
1924
        yield_parents=False):
1716
1925
        for trans_id, parent_file_id in ordered_entries:
1717
1926
            file_id = self._transform.final_file_id(trans_id)
1718
1927
            if file_id is None:
1744
1953
                ordered_ids.append((trans_id, parent_file_id))
1745
1954
        return ordered_ids
1746
1955
 
1747
 
    def iter_entries_by_dir(self, specific_file_ids=None):
 
1956
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
1748
1957
        # This may not be a maximally efficient implementation, but it is
1749
1958
        # reasonably straightforward.  An implementation that grafts the
1750
1959
        # TreeTransform changes onto the tree's iter_entries_by_dir results
1752
1961
        # position.
1753
1962
        ordered_ids = self._list_files_by_dir()
1754
1963
        for entry, trans_id in self._make_inv_entries(ordered_ids,
1755
 
                                                      specific_file_ids):
1756
 
            yield unicode(self._final_paths.get_path(trans_id)), entry
1757
 
 
1758
 
    def list_files(self, include_root=False):
1759
 
        """See Tree.list_files."""
 
1964
            specific_file_ids, yield_parents=yield_parents):
 
1965
            yield unicode(self._final_paths.get_path(trans_id)), entry
 
1966
 
 
1967
    def _iter_entries_for_dir(self, dir_path):
 
1968
        """Return path, entry for items in a directory without recursing down."""
 
1969
        dir_file_id = self.path2id(dir_path)
 
1970
        ordered_ids = []
 
1971
        for file_id in self.iter_children(dir_file_id):
 
1972
            trans_id = self._transform.trans_id_file_id(file_id)
 
1973
            ordered_ids.append((trans_id, file_id))
 
1974
        for entry, trans_id in self._make_inv_entries(ordered_ids):
 
1975
            yield unicode(self._final_paths.get_path(trans_id)), entry
 
1976
 
 
1977
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
1978
        """See WorkingTree.list_files."""
1760
1979
        # XXX This should behave like WorkingTree.list_files, but is really
1761
1980
        # more like RevisionTree.list_files.
1762
 
        for path, entry in self.iter_entries_by_dir():
1763
 
            if entry.name == '' and not include_root:
1764
 
                continue
1765
 
            yield path, 'V', entry.kind, entry.file_id, entry
 
1981
        if recursive:
 
1982
            prefix = None
 
1983
            if from_dir:
 
1984
                prefix = from_dir + '/'
 
1985
            entries = self.iter_entries_by_dir()
 
1986
            for path, entry in entries:
 
1987
                if entry.name == '' and not include_root:
 
1988
                    continue
 
1989
                if prefix:
 
1990
                    if not path.startswith(prefix):
 
1991
                        continue
 
1992
                    path = path[len(prefix):]
 
1993
                yield path, 'V', entry.kind, entry.file_id, entry
 
1994
        else:
 
1995
            if from_dir is None and include_root is True:
 
1996
                root_entry = inventory.make_entry('directory', '',
 
1997
                    ROOT_PARENT, self.get_root_id())
 
1998
                yield '', 'V', 'directory', root_entry.file_id, root_entry
 
1999
            entries = self._iter_entries_for_dir(from_dir or '')
 
2000
            for path, entry in entries:
 
2001
                yield path, 'V', entry.kind, entry.file_id, entry
1766
2002
 
1767
2003
    def kind(self, file_id):
1768
2004
        trans_id = self._transform.trans_id_file_id(file_id)
1778
2014
    def get_file_mtime(self, file_id, path=None):
1779
2015
        """See Tree.get_file_mtime"""
1780
2016
        if not self._content_change(file_id):
1781
 
            return self._transform._tree.get_file_mtime(file_id, path)
 
2017
            return self._transform._tree.get_file_mtime(file_id)
1782
2018
        return self._stat_limbo_file(file_id).st_mtime
1783
2019
 
1784
2020
    def _file_size(self, entry, stat_value):
1838
2074
                statval = os.lstat(limbo_name)
1839
2075
                size = statval.st_size
1840
2076
                if not supports_executable():
1841
 
                    executable = None
 
2077
                    executable = False
1842
2078
                else:
1843
2079
                    executable = statval.st_mode & S_IEXEC
1844
2080
            else:
1845
2081
                size = None
1846
2082
                executable = None
1847
2083
            if kind == 'symlink':
1848
 
                link_or_sha1 = os.readlink(limbo_name)
1849
 
        if supports_executable():
1850
 
            executable = tt._new_executability.get(trans_id, executable)
 
2084
                link_or_sha1 = os.readlink(limbo_name).decode(osutils._fs_enc)
 
2085
        executable = tt._new_executability.get(trans_id, executable)
1851
2086
        return kind, size, executable, link_or_sha1
1852
2087
 
1853
2088
    def iter_changes(self, from_tree, include_unchanged=False,
1879
2114
        name = self._transform._limbo_name(trans_id)
1880
2115
        return open(name, 'rb')
1881
2116
 
 
2117
    def get_file_with_stat(self, file_id, path=None):
 
2118
        return self.get_file(file_id, path), None
 
2119
 
1882
2120
    def annotate_iter(self, file_id,
1883
2121
                      default_revision=_mod_revision.CURRENT_REVISION):
1884
 
        changes = self._changes(file_id)
 
2122
        changes = self._iter_changes_cache.get(file_id)
1885
2123
        if changes is None:
1886
2124
            get_old = True
1887
2125
        else:
1899
2137
            return old_annotation
1900
2138
        if not changed_content:
1901
2139
            return old_annotation
 
2140
        # TODO: This is doing something similar to what WT.annotate_iter is
 
2141
        #       doing, however it fails slightly because it doesn't know what
 
2142
        #       the *other* revision_id is, so it doesn't know how to give the
 
2143
        #       other as the origin for some lines, they all get
 
2144
        #       'default_revision'
 
2145
        #       It would be nice to be able to use the new Annotator based
 
2146
        #       approach, as well.
1902
2147
        return annotate.reannotate([old_annotation],
1903
2148
                                   self.get_file(file_id).readlines(),
1904
2149
                                   default_revision)
1909
2154
            return self._transform._tree.get_symlink_target(file_id)
1910
2155
        trans_id = self._transform.trans_id_file_id(file_id)
1911
2156
        name = self._transform._limbo_name(trans_id)
1912
 
        return os.readlink(name)
 
2157
        return osutils.readlink(name)
1913
2158
 
1914
2159
    def walkdirs(self, prefix=''):
1915
2160
        pending = [self._transform.root]
1970
2215
        self.transform = transform
1971
2216
 
1972
2217
    def _determine_path(self, trans_id):
1973
 
        if trans_id == self.transform.root:
 
2218
        if (trans_id == self.transform.root or trans_id == ROOT_PARENT):
1974
2219
            return ""
1975
2220
        name = self.transform.final_name(trans_id)
1976
2221
        parent_id = self.transform.final_parent(trans_id)
2000
2245
def build_tree(tree, wt, accelerator_tree=None, hardlink=False,
2001
2246
               delta_from_tree=False):
2002
2247
    """Create working tree for a branch, using a TreeTransform.
2003
 
    
 
2248
 
2004
2249
    This function should be used on empty trees, having a tree root at most.
2005
2250
    (see merge and revert functionality for working with existing trees)
2006
2251
 
2007
2252
    Existing files are handled like so:
2008
 
    
 
2253
 
2009
2254
    - Existing bzrdirs take precedence over creating new items.  They are
2010
2255
      created as '%s.diverted' % name.
2011
2256
    - Otherwise, if the content on disk matches the content we are building,
2046
2291
    for num, _unused in enumerate(wt.all_file_ids()):
2047
2292
        if num > 0:  # more than just a root
2048
2293
            raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
2049
 
    existing_files = set()
2050
 
    for dir, files in wt.walkdirs():
2051
 
        existing_files.update(f[0] for f in files)
2052
2294
    file_trans_id = {}
2053
2295
    top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2054
2296
    pp = ProgressPhase("Build phase", 2, top_pb)
2078
2320
                precomputed_delta = []
2079
2321
            else:
2080
2322
                precomputed_delta = None
 
2323
            # Check if tree inventory has content. If so, we populate
 
2324
            # existing_files with the directory content. If there are no
 
2325
            # entries we skip populating existing_files as its not used.
 
2326
            # This improves performance and unncessary work on large
 
2327
            # directory trees. (#501307)
 
2328
            if total > 0:
 
2329
                existing_files = set()
 
2330
                for dir, files in wt.walkdirs():
 
2331
                    existing_files.update(f[0] for f in files)
2081
2332
            for num, (tree_path, entry) in \
2082
2333
                enumerate(tree.inventory.iter_entries_by_dir()):
2083
2334
                pb.update("Building tree", num - len(deferred_contents), total)
2113
2364
                    executable = tree.is_executable(file_id, tree_path)
2114
2365
                    if executable:
2115
2366
                        tt.set_executability(executable, trans_id)
2116
 
                    deferred_contents.append((file_id, trans_id))
 
2367
                    trans_data = (trans_id, tree_path)
 
2368
                    deferred_contents.append((file_id, trans_data))
2117
2369
                else:
2118
2370
                    file_trans_id[file_id] = new_by_entry(tt, entry, parent_id,
2119
2371
                                                          tree)
2150
2402
def _create_files(tt, tree, desired_files, pb, offset, accelerator_tree,
2151
2403
                  hardlink):
2152
2404
    total = len(desired_files) + offset
 
2405
    wt = tt._tree
2153
2406
    if accelerator_tree is None:
2154
2407
        new_desired_files = desired_files
2155
2408
    else:
2156
2409
        iter = accelerator_tree.iter_changes(tree, include_unchanged=True)
2157
 
        unchanged = dict((f, p[1]) for (f, p, c, v, d, n, k, e)
2158
 
                         in iter if not (c or e[0] != e[1]))
 
2410
        unchanged = [(f, p[1]) for (f, p, c, v, d, n, k, e)
 
2411
                     in iter if not (c or e[0] != e[1])]
 
2412
        if accelerator_tree.supports_content_filtering():
 
2413
            unchanged = [(f, p) for (f, p) in unchanged
 
2414
                         if not accelerator_tree.iter_search_rules([p]).next()]
 
2415
        unchanged = dict(unchanged)
2159
2416
        new_desired_files = []
2160
2417
        count = 0
2161
 
        for file_id, trans_id in desired_files:
 
2418
        for file_id, (trans_id, tree_path) in desired_files:
2162
2419
            accelerator_path = unchanged.get(file_id)
2163
2420
            if accelerator_path is None:
2164
 
                new_desired_files.append((file_id, trans_id))
 
2421
                new_desired_files.append((file_id, (trans_id, tree_path)))
2165
2422
                continue
2166
2423
            pb.update('Adding file contents', count + offset, total)
2167
2424
            if hardlink:
2169
2426
                                   trans_id)
2170
2427
            else:
2171
2428
                contents = accelerator_tree.get_file(file_id, accelerator_path)
 
2429
                if wt.supports_content_filtering():
 
2430
                    filters = wt._content_filter_stack(tree_path)
 
2431
                    contents = filtered_output_bytes(contents, filters,
 
2432
                        ContentFilterContext(tree_path, tree))
2172
2433
                try:
2173
2434
                    tt.create_file(contents, trans_id)
2174
2435
                finally:
2175
 
                    contents.close()
 
2436
                    try:
 
2437
                        contents.close()
 
2438
                    except AttributeError:
 
2439
                        # after filtering, contents may no longer be file-like
 
2440
                        pass
2176
2441
            count += 1
2177
2442
        offset += count
2178
 
    for count, (trans_id, contents) in enumerate(tree.iter_files_bytes(
2179
 
                                                 new_desired_files)):
 
2443
    for count, ((trans_id, tree_path), contents) in enumerate(
 
2444
            tree.iter_files_bytes(new_desired_files)):
 
2445
        if wt.supports_content_filtering():
 
2446
            filters = wt._content_filter_stack(tree_path)
 
2447
            contents = filtered_output_bytes(contents, filters,
 
2448
                ContentFilterContext(tree_path, tree))
2180
2449
        tt.create_file(contents, trans_id)
2181
2450
        pb.update('Adding file contents', count + offset, total)
2182
2451
 
2197
2466
    if entry.kind == "directory":
2198
2467
        return True
2199
2468
    if entry.kind == "file":
2200
 
        if tree.get_file(file_id).read() == file(target_path, 'rb').read():
2201
 
            return True
 
2469
        f = file(target_path, 'rb')
 
2470
        try:
 
2471
            if tree.get_file_text(file_id) == f.read():
 
2472
                return True
 
2473
        finally:
 
2474
            f.close()
2202
2475
    elif entry.kind == "symlink":
2203
2476
        if tree.get_symlink_target(file_id) == os.readlink(target_path):
2204
2477
            return True
2242
2515
    if kind == 'file':
2243
2516
        contents = tree.get_file(entry.file_id).readlines()
2244
2517
        executable = tree.is_executable(entry.file_id)
2245
 
        return tt.new_file(name, parent_id, contents, entry.file_id, 
 
2518
        return tt.new_file(name, parent_id, contents, entry.file_id,
2246
2519
                           executable)
2247
2520
    elif kind in ('directory', 'tree-reference'):
2248
2521
        trans_id = tt.new_directory(name, parent_id, entry.file_id)
2249
2522
        if kind == 'tree-reference':
2250
2523
            tt.set_tree_reference(entry.reference_revision, trans_id)
2251
 
        return trans_id 
 
2524
        return trans_id
2252
2525
    elif kind == 'symlink':
2253
2526
        target = tree.get_symlink_target(entry.file_id)
2254
2527
        return tt.new_symlink(name, parent_id, target, entry.file_id)
2272
2545
        tt.create_directory(trans_id)
2273
2546
 
2274
2547
 
2275
 
def create_from_tree(tt, trans_id, tree, file_id, bytes=None):
2276
 
    """Create new file contents according to tree contents."""
 
2548
def create_from_tree(tt, trans_id, tree, file_id, bytes=None,
 
2549
    filter_tree_path=None):
 
2550
    """Create new file contents according to tree contents.
 
2551
    
 
2552
    :param filter_tree_path: the tree path to use to lookup
 
2553
      content filters to apply to the bytes output in the working tree.
 
2554
      This only applies if the working tree supports content filtering.
 
2555
    """
2277
2556
    kind = tree.kind(file_id)
2278
2557
    if kind == 'directory':
2279
2558
        tt.create_directory(trans_id)
2284
2563
                bytes = tree_file.readlines()
2285
2564
            finally:
2286
2565
                tree_file.close()
 
2566
        wt = tt._tree
 
2567
        if wt.supports_content_filtering() and filter_tree_path is not None:
 
2568
            filters = wt._content_filter_stack(filter_tree_path)
 
2569
            bytes = filtered_output_bytes(bytes, filters,
 
2570
                ContentFilterContext(filter_tree_path, tree))
2287
2571
        tt.create_file(bytes, trans_id)
2288
2572
    elif kind == "symlink":
2289
2573
        tt.create_symlink(tree.get_symlink_target(file_id), trans_id)
2333
2617
        if entry.kind != working_kind:
2334
2618
            contents_mod, meta_mod = True, False
2335
2619
        else:
2336
 
            cur_entry._read_tree_state(working_tree.id2path(file_id), 
 
2620
            cur_entry._read_tree_state(working_tree.id2path(file_id),
2337
2621
                                       working_tree)
2338
2622
            contents_mod, meta_mod = entry.detect_changes(cur_entry)
2339
2623
            cur_entry._forget_tree_state()
2341
2625
 
2342
2626
 
2343
2627
def revert(working_tree, target_tree, filenames, backups=False,
2344
 
           pb=DummyProgress(), change_reporter=None):
 
2628
           pb=None, change_reporter=None):
2345
2629
    """Revert a working tree's contents to those of a target tree."""
2346
2630
    target_tree.lock_read()
 
2631
    pb = ui.ui_factory.nested_progress_bar()
2347
2632
    tt = TreeTransform(working_tree, pb)
2348
2633
    try:
2349
2634
        pp = ProgressPhase("Revert phase", 3, pb)
2368
2653
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
2369
2654
                              backups, pp, basis_tree=None,
2370
2655
                              merge_modified=None):
2371
 
    pp.next_phase()
2372
2656
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2373
2657
    try:
2374
2658
        if merge_modified is None:
2378
2662
                                      merge_modified, basis_tree)
2379
2663
    finally:
2380
2664
        child_pb.finished()
2381
 
    pp.next_phase()
2382
2665
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2383
2666
    try:
2384
2667
        raw_conflicts = resolve_conflicts(tt, child_pb,
2477
2760
                    parent_trans = ROOT_PARENT
2478
2761
                else:
2479
2762
                    parent_trans = tt.trans_id_file_id(parent[1])
2480
 
                tt.adjust_path(name[1], parent_trans, trans_id)
 
2763
                if parent[0] is None and versioned[0]:
 
2764
                    tt.adjust_root_path(name[1], parent_trans)
 
2765
                else:
 
2766
                    tt.adjust_path(name[1], parent_trans, trans_id)
2481
2767
            if executable[0] != executable[1] and kind[1] == "file":
2482
2768
                tt.set_executability(executable[1], trans_id)
2483
 
        for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
2484
 
            deferred_files):
2485
 
            tt.create_file(bytes, trans_id, mode_id)
 
2769
        if working_tree.supports_content_filtering():
 
2770
            for index, ((trans_id, mode_id), bytes) in enumerate(
 
2771
                target_tree.iter_files_bytes(deferred_files)):
 
2772
                file_id = deferred_files[index][0]
 
2773
                # We're reverting a tree to the target tree so using the
 
2774
                # target tree to find the file path seems the best choice
 
2775
                # here IMO - Ian C 27/Oct/2009
 
2776
                filter_tree_path = target_tree.id2path(file_id)
 
2777
                filters = working_tree._content_filter_stack(filter_tree_path)
 
2778
                bytes = filtered_output_bytes(bytes, filters,
 
2779
                    ContentFilterContext(filter_tree_path, working_tree))
 
2780
                tt.create_file(bytes, trans_id, mode_id)
 
2781
        else:
 
2782
            for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
 
2783
                deferred_files):
 
2784
                tt.create_file(bytes, trans_id, mode_id)
 
2785
        tt.fixup_new_roots()
2486
2786
    finally:
2487
2787
        if basis_tree is not None:
2488
2788
            basis_tree.unlock()
2489
2789
    return merge_modified
2490
2790
 
2491
2791
 
2492
 
def resolve_conflicts(tt, pb=DummyProgress(), pass_func=None):
 
2792
def resolve_conflicts(tt, pb=None, pass_func=None):
2493
2793
    """Make many conflict-resolution attempts, but die if they fail"""
2494
2794
    if pass_func is None:
2495
2795
        pass_func = conflict_pass
2496
2796
    new_conflicts = set()
 
2797
    pb = ui.ui_factory.nested_progress_bar()
2497
2798
    try:
2498
2799
        for n in range(10):
2499
2800
            pb.update('Resolution pass', n+1, 10)
2503
2804
            new_conflicts.update(pass_func(tt, conflicts))
2504
2805
        raise MalformedTransform(conflicts=conflicts)
2505
2806
    finally:
2506
 
        pb.clear()
 
2807
        pb.finished()
2507
2808
 
2508
2809
 
2509
2810
def conflict_pass(tt, conflicts, path_tree=None):
2528
2829
                existing_file, new_file = conflict[1], conflict[2]
2529
2830
            new_name = tt.final_name(existing_file)+'.moved'
2530
2831
            tt.adjust_path(new_name, final_parent, existing_file)
2531
 
            new_conflicts.add((c_type, 'Moved existing file to', 
 
2832
            new_conflicts.add((c_type, 'Moved existing file to',
2532
2833
                               existing_file, new_file))
2533
2834
        elif c_type == 'parent loop':
2534
2835
            # break the loop by undoing one of the ops that caused the loop
2538
2839
            new_conflicts.add((c_type, 'Cancelled move', cur,
2539
2840
                               tt.final_parent(cur),))
2540
2841
            tt.adjust_path(tt.final_name(cur), tt.get_tree_parent(cur), cur)
2541
 
            
 
2842
 
2542
2843
        elif c_type == 'missing parent':
2543
2844
            trans_id = conflict[1]
2544
2845
            try:
2545
2846
                tt.cancel_deletion(trans_id)
2546
 
                new_conflicts.add(('deleting parent', 'Not deleting', 
 
2847
                new_conflicts.add(('deleting parent', 'Not deleting',
2547
2848
                                   trans_id))
2548
2849
            except KeyError:
2549
2850
                create = True
2558
2859
                        # special-case the other tree root (move its
2559
2860
                        # children to current root)
2560
2861
                        if entry.parent_id is None:
2561
 
                            create=False
 
2862
                            create = False
2562
2863
                            moved = _reparent_transform_children(
2563
2864
                                tt, trans_id, tt.root)
2564
2865
                            for child in moved:
2614
2915
        if len(conflict) == 3:
2615
2916
            yield Conflict.factory(c_type, action=action, path=modified_path,
2616
2917
                                     file_id=modified_id)
2617
 
             
 
2918
 
2618
2919
        else:
2619
2920
            conflicting_path = fp.get_path(conflict[3])
2620
2921
            conflicting_id = tt.final_file_id(conflict[3])
2621
2922
            yield Conflict.factory(c_type, action=action, path=modified_path,
2622
 
                                   file_id=modified_id, 
 
2923
                                   file_id=modified_id,
2623
2924
                                   conflict_path=conflicting_path,
2624
2925
                                   conflict_file_id=conflicting_id)
2625
2926
 
2632
2933
        self.pending_deletions = []
2633
2934
 
2634
2935
    def rename(self, from_, to):
2635
 
        """Rename a file from one path to another.  Functions like os.rename"""
 
2936
        """Rename a file from one path to another."""
2636
2937
        try:
2637
 
            os.rename(from_, to)
2638
 
        except OSError, e:
 
2938
            osutils.rename(from_, to)
 
2939
        except (IOError, OSError), e:
2639
2940
            if e.errno in (errno.EEXIST, errno.ENOTEMPTY):
2640
2941
                raise errors.FileExists(to, str(e))
2641
 
            raise
 
2942
            # normal OSError doesn't include filenames so it's hard to see where
 
2943
            # the problem is, see https://bugs.launchpad.net/bzr/+bug/491763
 
2944
            raise errors.TransformRenameFailed(from_, to, str(e), e.errno)
2642
2945
        self.past_renames.append((from_, to))
2643
2946
 
2644
2947
    def pre_delete(self, from_, to):
2654
2957
    def rollback(self):
2655
2958
        """Reverse all renames that have been performed"""
2656
2959
        for from_, to in reversed(self.past_renames):
2657
 
            os.rename(to, from_)
 
2960
            try:
 
2961
                osutils.rename(to, from_)
 
2962
            except (OSError, IOError), e:
 
2963
                raise errors.TransformRenameFailed(to, from_, str(e), e.errno)                
2658
2964
        # after rollback, don't reuse _FileMover
2659
2965
        past_renames = None
2660
2966
        pending_deletions = None