~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transform.py

  • Committer: INADA Naoki
  • Date: 2011-05-18 06:27:34 UTC
  • mfrom: (5887 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5894.
  • Revision ID: songofacandy@gmail.com-20110518062734-1ilhll0rrqyyp8um
merge from lp:bzr and resolve conflicts.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007, 2008, 2009 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
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,
25
32
    bencode,
26
33
    bzrdir,
 
34
    commit,
27
35
    delta,
28
36
    errors,
29
37
    inventory,
30
38
    multiparent,
31
39
    osutils,
32
40
    revision as _mod_revision,
 
41
    ui,
 
42
    urlutils,
33
43
    )
34
44
""")
35
45
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
36
 
                           ReusingTransform, NotVersionedError, CantMoveRoot,
 
46
                           ReusingTransform, CantMoveRoot,
37
47
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
38
48
                           UnableCreateSymlink)
39
49
from bzrlib.filters import filtered_output_bytes, ContentFilterContext
40
 
from bzrlib.inventory import InventoryEntry
41
50
from bzrlib.osutils import (
42
51
    delete_any,
43
52
    file_kind,
44
53
    has_symlinks,
45
 
    lexists,
46
54
    pathjoin,
47
55
    sha_file,
48
56
    splitpath,
49
57
    supports_executable,
50
 
)
51
 
from bzrlib.progress import DummyProgress, ProgressPhase
 
58
    )
 
59
from bzrlib.progress import ProgressPhase
52
60
from bzrlib.symbol_versioning import (
53
 
        deprecated_function,
54
 
        deprecated_in,
55
 
        )
56
 
from bzrlib.trace import mutter, warning
57
 
from bzrlib import tree
58
 
import bzrlib.ui
59
 
import bzrlib.urlutils as urlutils
 
61
    deprecated_function,
 
62
    deprecated_in,
 
63
    deprecated_method,
 
64
    )
60
65
 
61
66
 
62
67
ROOT_PARENT = "root-parent"
63
68
 
64
 
 
65
69
def unique_add(map, key, value):
66
70
    if key in map:
67
71
        raise DuplicateKey(key=key)
68
72
    map[key] = value
69
73
 
70
74
 
 
75
 
71
76
class _TransformResults(object):
72
77
    def __init__(self, modified_paths, rename_count):
73
78
        object.__init__(self)
78
83
class TreeTransformBase(object):
79
84
    """The base class for TreeTransform and its kin."""
80
85
 
81
 
    def __init__(self, tree, pb=DummyProgress(),
 
86
    def __init__(self, tree, pb=None,
82
87
                 case_sensitive=True):
83
88
        """Constructor.
84
89
 
85
90
        :param tree: The tree that will be transformed, but not necessarily
86
91
            the output tree.
87
 
        :param pb: A ProgressTask indicating how much progress is being made
 
92
        :param pb: ignored
88
93
        :param case_sensitive: If True, the target of the transform is
89
94
            case sensitive, not just case preserving.
90
95
        """
97
102
        self._new_parent = {}
98
103
        # mapping of trans_id with new contents -> new file_kind
99
104
        self._new_contents = {}
 
105
        # mapping of trans_id => (sha1 of content, stat_value)
 
106
        self._observed_sha1s = {}
100
107
        # Set of trans_ids whose contents will be removed
101
108
        self._removed_contents = set()
102
109
        # Mapping of trans_id -> new execute-bit value
121
128
            self._new_root = self.trans_id_tree_file_id(root_id)
122
129
        else:
123
130
            self._new_root = None
124
 
        # Indictor of whether the transform has been applied
 
131
        # Indicator of whether the transform has been applied
125
132
        self._done = False
126
133
        # A progress bar
127
134
        self._pb = pb
161
168
 
162
169
    def adjust_path(self, name, parent, trans_id):
163
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")
164
173
        if trans_id == self._new_root:
165
174
            raise CantMoveRoot
166
175
        self._new_name[trans_id] = name
167
176
        self._new_parent[trans_id] = parent
168
 
        if parent == ROOT_PARENT:
169
 
            if self._new_root is not None:
170
 
                raise ValueError("Cannot have multiple roots.")
171
 
            self._new_root = trans_id
172
177
 
173
178
    def adjust_root_path(self, name, parent):
174
179
        """Emulate moving the root by moving all children, instead.
202
207
        self.version_file(old_root_file_id, old_root)
203
208
        self.unversion_file(self._new_root)
204
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
 
205
271
    def trans_id_tree_file_id(self, inventory_id):
206
272
        """Determine the transaction id of a working tree file.
207
273
 
253
319
 
254
320
    def delete_contents(self, trans_id):
255
321
        """Schedule the contents of a path entry for deletion"""
256
 
        self.tree_kind(trans_id)
257
 
        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)
258
325
 
259
326
    def cancel_deletion(self, trans_id):
260
327
        """Cancel a scheduled deletion"""
325
392
        changed_kind = set(self._removed_contents)
326
393
        changed_kind.intersection_update(self._new_contents)
327
394
        changed_kind.difference_update(new_ids)
328
 
        changed_kind = (t for t in changed_kind if self.tree_kind(t) !=
329
 
                        self.final_kind(t))
 
395
        changed_kind = (t for t in changed_kind
 
396
                        if self.tree_kind(t) != self.final_kind(t))
330
397
        new_ids.update(changed_kind)
331
398
        return sorted(FinalPaths(self).get_paths(new_ids))
332
399
 
333
400
    def final_kind(self, trans_id):
334
401
        """Determine the final file kind, after any changes applied.
335
402
 
336
 
        Raises NoSuchFile if the file does not exist/has no contents.
337
 
        (It is conceivable that a path would be created without the
338
 
        corresponding contents insertion command)
 
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)
339
406
        """
340
407
        if trans_id in self._new_contents:
341
408
            return self._new_contents[trans_id]
342
409
        elif trans_id in self._removed_contents:
343
 
            raise NoSuchFile(None)
 
410
            return None
344
411
        else:
345
412
            return self.tree_kind(trans_id)
346
413
 
459
526
        for trans_id in self._removed_id:
460
527
            file_id = self.tree_file_id(trans_id)
461
528
            if file_id is not None:
 
529
                # XXX: This seems like something that should go via a different
 
530
                #      indirection.
462
531
                if self._tree.inventory[file_id].kind == 'directory':
463
532
                    parents.append(trans_id)
464
533
            elif self.tree_kind(trans_id) == 'directory':
468
537
            # ensure that all children are registered with the transaction
469
538
            list(self.iter_tree_children(parent_id))
470
539
 
 
540
    @deprecated_method(deprecated_in((2, 3, 0)))
471
541
    def has_named_child(self, by_parent, parent_id, name):
472
 
        try:
473
 
            children = by_parent[parent_id]
474
 
        except KeyError:
475
 
            children = []
476
 
        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:
477
559
            if self.final_name(child) == name:
478
560
                return True
479
 
        try:
480
 
            path = self._tree_id_paths[parent_id]
481
 
        except KeyError:
 
561
        parent_path = self._tree_id_paths.get(parent_id, None)
 
562
        if parent_path is None:
 
563
            # No parent... no children
482
564
            return False
483
 
        childpath = joinpath(path, name)
484
 
        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)
485
567
        if child_id is None:
486
 
            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))
487
570
        else:
488
 
            if self.final_parent(child_id) != parent_id:
489
 
                return False
490
 
            if child_id in self._removed_contents:
491
 
                # XXX What about dangling file-ids?
492
 
                return False
493
 
            else:
494
 
                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))
495
587
 
496
588
    def _parent_loops(self):
497
589
        """No entry should be its own ancestor"""
532
624
        """
533
625
        conflicts = []
534
626
        for trans_id in self._new_id.iterkeys():
535
 
            try:
536
 
                kind = self.final_kind(trans_id)
537
 
            except NoSuchFile:
 
627
            kind = self.final_kind(trans_id)
 
628
            if kind is None:
538
629
                conflicts.append(('versioning no contents', trans_id))
539
630
                continue
540
 
            if not InventoryEntry.versionable_kind(kind):
 
631
            if not inventory.InventoryEntry.versionable_kind(kind):
541
632
                conflicts.append(('versioning bad kind', trans_id, kind))
542
633
        return conflicts
543
634
 
554
645
            if self.final_file_id(trans_id) is None:
555
646
                conflicts.append(('unversioned executability', trans_id))
556
647
            else:
557
 
                try:
558
 
                    non_file = self.final_kind(trans_id) != "file"
559
 
                except NoSuchFile:
560
 
                    non_file = True
561
 
                if non_file is True:
 
648
                if self.final_kind(trans_id) != "file":
562
649
                    conflicts.append(('non-file executability', trans_id))
563
650
        return conflicts
564
651
 
566
653
        """Check for overwrites (not permitted on Win32)"""
567
654
        conflicts = []
568
655
        for trans_id in self._new_contents:
569
 
            try:
570
 
                self.tree_kind(trans_id)
571
 
            except NoSuchFile:
 
656
            if self.tree_kind(trans_id) is None:
572
657
                continue
573
658
            if trans_id not in self._removed_contents:
574
659
                conflicts.append(('overwrite', trans_id,
581
666
        if (self._new_name, self._new_parent) == ({}, {}):
582
667
            return conflicts
583
668
        for children in by_parent.itervalues():
584
 
            name_ids = [(self.final_name(t), t) for t in children]
585
 
            if not self._case_sensitive_target:
586
 
                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))
587
677
            name_ids.sort()
588
678
            last_name = None
589
679
            last_trans_id = None
590
680
            for name, trans_id in name_ids:
591
 
                try:
592
 
                    kind = self.final_kind(trans_id)
593
 
                except NoSuchFile:
594
 
                    kind = None
 
681
                kind = self.final_kind(trans_id)
595
682
                file_id = self.final_file_id(trans_id)
596
683
                if kind is None and file_id is None:
597
684
                    continue
616
703
        return conflicts
617
704
 
618
705
    def _parent_type_conflicts(self, by_parent):
619
 
        """parents must have directory 'contents'."""
 
706
        """Children must have a directory parent"""
620
707
        conflicts = []
621
708
        for parent_id, children in by_parent.iteritems():
622
709
            if parent_id is ROOT_PARENT:
623
710
                continue
624
 
            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:
625
717
                continue
626
 
            for child in children:
627
 
                try:
628
 
                    self.final_kind(child)
629
 
                except NoSuchFile:
630
 
                    continue
631
 
            try:
632
 
                kind = self.final_kind(parent_id)
633
 
            except NoSuchFile:
634
 
                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)
635
721
            if kind is None:
 
722
                # The directory will be deleted
636
723
                conflicts.append(('missing parent', parent_id))
637
724
            elif kind != "directory":
 
725
                # Meh, we need a *directory* to put something in it
638
726
                conflicts.append(('non-directory parent', parent_id))
639
727
        return conflicts
640
728
 
641
 
    def _any_contents(self, trans_ids):
642
 
        """Return true if any of the trans_ids, will have contents."""
643
 
        for trans_id in trans_ids:
644
 
            try:
645
 
                kind = self.final_kind(trans_id)
646
 
            except NoSuchFile:
647
 
                continue
648
 
            return True
649
 
        return False
650
 
 
651
729
    def _set_executability(self, path, trans_id):
652
730
        """Set the executability of versioned files """
653
731
        if supports_executable():
675
753
        return trans_id
676
754
 
677
755
    def new_file(self, name, parent_id, contents, file_id=None,
678
 
                 executable=None):
 
756
                 executable=None, sha1=None):
679
757
        """Convenience method to create files.
680
758
 
681
759
        name is the name of the file to create.
688
766
        trans_id = self._new_entry(name, parent_id, file_id)
689
767
        # TODO: rather than scheduling a set_executable call,
690
768
        # have create_file create the file with the right mode.
691
 
        self.create_file(contents, trans_id)
 
769
        self.create_file(contents, trans_id, sha1=sha1)
692
770
        if executable is not None:
693
771
            self.set_executability(executable, trans_id)
694
772
        return trans_id
717
795
        self.create_symlink(target, trans_id)
718
796
        return trans_id
719
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
 
720
840
    def _affected_ids(self):
721
841
        """Return the set of transform ids affected by the transform"""
722
842
        trans_ids = set(self._removed_id)
781
901
        Return a (name, parent, kind, executable) tuple
782
902
        """
783
903
        to_name = self.final_name(to_trans_id)
784
 
        try:
785
 
            to_kind = self.final_kind(to_trans_id)
786
 
        except NoSuchFile:
787
 
            to_kind = None
 
904
        to_kind = self.final_kind(to_trans_id)
788
905
        to_parent = self.final_file_id(self.final_parent(to_trans_id))
789
906
        if to_trans_id in self._new_executability:
790
907
            to_executable = self._new_executability[to_trans_id]
859
976
    def get_preview_tree(self):
860
977
        """Return a tree representing the result of the transform.
861
978
 
862
 
        This tree only supports the subset of Tree functionality required
863
 
        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.
864
981
        """
865
982
        return _PreviewTree(self)
866
983
 
867
 
    def commit(self, branch, message, merge_parents=None, strict=False):
 
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):
868
987
        """Commit the result of this TreeTransform to a branch.
869
988
 
870
989
        :param branch: The branch to commit to.
871
990
        :param message: The message to attach to the commit.
872
 
        :param merge_parents: Additional parents specified by pending merges.
 
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.)
873
1005
        :return: The revision_id of the revision committed.
874
1006
        """
875
1007
        self._check_malformed()
892
1024
        if self._tree.get_revision_id() != last_rev_id:
893
1025
            raise ValueError('TreeTransform not based on branch basis: %s' %
894
1026
                             self._tree.get_revision_id())
895
 
        builder = branch.get_commit_builder(parent_ids)
 
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)
896
1034
        preview = self.get_preview_tree()
897
1035
        list(builder.record_iter_changes(preview, last_rev_id,
898
1036
                                         self.iter_changes()))
1000
1138
class DiskTreeTransform(TreeTransformBase):
1001
1139
    """Tree transform storing its contents on disk."""
1002
1140
 
1003
 
    def __init__(self, tree, limbodir, pb=DummyProgress(),
 
1141
    def __init__(self, tree, limbodir, pb=None,
1004
1142
                 case_sensitive=True):
1005
1143
        """Constructor.
1006
1144
        :param tree: The tree that will be transformed, but not necessarily
1007
1145
            the output tree.
1008
1146
        :param limbodir: A directory where new files can be stored until
1009
1147
            they are installed in their proper places
1010
 
        :param pb: A ProgressBar indicating how much progress is being made
 
1148
        :param pb: ignored
1011
1149
        :param case_sensitive: If True, the target of the transform is
1012
1150
            case sensitive, not just case preserving.
1013
1151
        """
1023
1161
        self._limbo_children_names = {}
1024
1162
        # List of transform ids that need to be renamed from limbo into place
1025
1163
        self._needs_rename = set()
 
1164
        self._creation_mtime = None
1026
1165
 
1027
1166
    def finalize(self):
1028
1167
        """Release the working tree lock, if held, clean up limbo dir.
1054
1193
    def _limbo_name(self, trans_id):
1055
1194
        """Generate the limbo name of a file"""
1056
1195
        limbo_name = self._limbo_files.get(trans_id)
1057
 
        if limbo_name is not None:
1058
 
            return limbo_name
1059
 
        parent = self._new_parent.get(trans_id)
1060
 
        # if the parent directory is already in limbo (e.g. when building a
1061
 
        # tree), choose a limbo name inside the parent, to reduce further
1062
 
        # renames.
1063
 
        use_direct_path = False
1064
 
        if self._new_contents.get(parent) == 'directory':
1065
 
            filename = self._new_name.get(trans_id)
1066
 
            if filename is not None:
1067
 
                if parent not in self._limbo_children:
1068
 
                    self._limbo_children[parent] = set()
1069
 
                    self._limbo_children_names[parent] = {}
1070
 
                    use_direct_path = True
1071
 
                # the direct path can only be used if no other file has
1072
 
                # already taken this pathname, i.e. if the name is unused, or
1073
 
                # if it is already associated with this trans_id.
1074
 
                elif self._case_sensitive_target:
1075
 
                    if (self._limbo_children_names[parent].get(filename)
1076
 
                        in (trans_id, None)):
1077
 
                        use_direct_path = True
1078
 
                else:
1079
 
                    for l_filename, l_trans_id in\
1080
 
                        self._limbo_children_names[parent].iteritems():
1081
 
                        if l_trans_id == trans_id:
1082
 
                            continue
1083
 
                        if l_filename.lower() == filename.lower():
1084
 
                            break
1085
 
                    else:
1086
 
                        use_direct_path = True
1087
 
 
1088
 
        if use_direct_path:
1089
 
            limbo_name = pathjoin(self._limbo_files[parent], filename)
1090
 
            self._limbo_children[parent].add(trans_id)
1091
 
            self._limbo_children_names[parent][filename] = trans_id
1092
 
        else:
1093
 
            limbo_name = pathjoin(self._limbodir, trans_id)
1094
 
            self._needs_rename.add(trans_id)
1095
 
        self._limbo_files[trans_id] = limbo_name
 
1196
        if limbo_name is None:
 
1197
            limbo_name = self._generate_limbo_path(trans_id)
 
1198
            self._limbo_files[trans_id] = limbo_name
1096
1199
        return limbo_name
1097
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
 
1098
1210
    def adjust_path(self, name, parent, trans_id):
1099
1211
        previous_parent = self._new_parent.get(trans_id)
1100
1212
        previous_name = self._new_name.get(trans_id)
1102
1214
        if (trans_id in self._limbo_files and
1103
1215
            trans_id not in self._needs_rename):
1104
1216
            self._rename_in_limbo([trans_id])
1105
 
            self._limbo_children[previous_parent].remove(trans_id)
1106
 
            del self._limbo_children_names[previous_parent][previous_name]
 
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]
1107
1221
 
1108
1222
    def _rename_in_limbo(self, trans_ids):
1109
1223
        """Fix limbo names so that the right final path is produced.
1122
1236
                continue
1123
1237
            new_path = self._limbo_name(trans_id)
1124
1238
            os.rename(old_path, new_path)
1125
 
 
1126
 
    def create_file(self, contents, trans_id, mode_id=None):
 
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):
1127
1252
        """Schedule creation of a new file.
1128
1253
 
1129
 
        See also new_file.
1130
 
 
1131
 
        Contents is an iterator of strings, all of which will be written
1132
 
        to the target destination.
1133
 
 
1134
 
        New file takes the permissions of any existing file with that id,
1135
 
        unless mode_id is specified.
 
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.
1136
1264
        """
1137
1265
        name = self._limbo_name(trans_id)
1138
1266
        f = open(name, 'wb')
1145
1273
                f.close()
1146
1274
                os.unlink(name)
1147
1275
                raise
1148
 
 
1149
1276
            f.writelines(contents)
1150
1277
        finally:
1151
1278
            f.close()
 
1279
        self._set_mtime(name)
1152
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))
1153
1286
 
1154
1287
    def _read_file_chunks(self, trans_id):
1155
1288
        cur_file = open(self._limbo_name(trans_id), 'rb')
1161
1294
    def _read_symlink_target(self, trans_id):
1162
1295
        return os.readlink(self._limbo_name(trans_id))
1163
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
 
1164
1306
    def create_hardlink(self, path, trans_id):
1165
1307
        """Schedule creation of a hard link"""
1166
1308
        name = self._limbo_name(trans_id)
1205
1347
    def cancel_creation(self, trans_id):
1206
1348
        """Cancel the creation of new file contents."""
1207
1349
        del self._new_contents[trans_id]
 
1350
        if trans_id in self._observed_sha1s:
 
1351
            del self._observed_sha1s[trans_id]
1208
1352
        children = self._limbo_children.get(trans_id)
1209
1353
        # if this is a limbo directory with children, move them before removing
1210
1354
        # the directory
1214
1358
            del self._limbo_children_names[trans_id]
1215
1359
        delete_any(self._limbo_name(trans_id))
1216
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
 
1217
1444
 
1218
1445
class TreeTransform(DiskTreeTransform):
1219
1446
    """Represent a tree transformation.
1280
1507
    FileMover does not delete files until it is sure that a rollback will not
1281
1508
    happen.
1282
1509
    """
1283
 
    def __init__(self, tree, pb=DummyProgress()):
 
1510
    def __init__(self, tree, pb=None):
1284
1511
        """Note: a tree_write lock is taken on the tree.
1285
1512
 
1286
1513
        Use TreeTransform.finalize() to release the lock (can be omitted if
1337
1564
    def tree_kind(self, trans_id):
1338
1565
        """Determine the file kind in the working tree.
1339
1566
 
1340
 
        Raises NoSuchFile if the file does not exist
 
1567
        :returns: The file kind or None if the file does not exist
1341
1568
        """
1342
1569
        path = self._tree_id_paths.get(trans_id)
1343
1570
        if path is None:
1344
 
            raise NoSuchFile(None)
 
1571
            return None
1345
1572
        try:
1346
1573
            return file_kind(self._tree.abspath(path))
1347
 
        except OSError, e:
1348
 
            if e.errno != errno.ENOENT:
1349
 
                raise
1350
 
            else:
1351
 
                raise NoSuchFile(path)
 
1574
        except errors.NoSuchFile:
 
1575
            return None
1352
1576
 
1353
1577
    def _set_mode(self, trans_id, mode_id, typefunc):
1354
1578
        """Set the mode of new file contents.
1396
1620
                continue
1397
1621
            yield self.trans_id_tree_path(childpath)
1398
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
 
1399
1671
    def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
1400
1672
        """Apply all changes to the inventory and filesystem.
1401
1673
 
1412
1684
        """
1413
1685
        if not no_conflicts:
1414
1686
            self._check_malformed()
1415
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1687
        child_pb = ui.ui_factory.nested_progress_bar()
1416
1688
        try:
1417
1689
            if precomputed_delta is None:
1418
1690
                child_pb.update('Apply phase', 0, 2)
1438
1710
        finally:
1439
1711
            child_pb.finished()
1440
1712
        self._tree.apply_inventory_delta(inventory_delta)
 
1713
        self._apply_observed_sha1s()
1441
1714
        self._done = True
1442
1715
        self.finalize()
1443
1716
        return _TransformResults(modified_paths, self.rename_count)
1445
1718
    def _generate_inventory_delta(self):
1446
1719
        """Generate an inventory delta for the current transform."""
1447
1720
        inventory_delta = []
1448
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1721
        child_pb = ui.ui_factory.nested_progress_bar()
1449
1722
        new_paths = self._inventory_altered()
1450
1723
        total_entries = len(new_paths) + len(self._removed_id)
1451
1724
        try:
1475
1748
                if file_id is None:
1476
1749
                    continue
1477
1750
                needs_entry = False
1478
 
                try:
1479
 
                    kind = self.final_kind(trans_id)
1480
 
                except NoSuchFile:
 
1751
                kind = self.final_kind(trans_id)
 
1752
                if kind is None:
1481
1753
                    kind = self._tree.stored_kind(file_id)
1482
1754
                parent_trans_id = self.final_parent(trans_id)
1483
1755
                parent_file_id = new_path_file_ids.get(parent_trans_id)
1514
1786
        """
1515
1787
        tree_paths = list(self._tree_path_ids.iteritems())
1516
1788
        tree_paths.sort(reverse=True)
1517
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1789
        child_pb = ui.ui_factory.nested_progress_bar()
1518
1790
        try:
1519
1791
            for num, data in enumerate(tree_paths):
1520
1792
                path, trans_id = data
1521
1793
                child_pb.update('removing file', num, len(tree_paths))
1522
1794
                full_path = self._tree.abspath(path)
1523
1795
                if trans_id in self._removed_contents:
1524
 
                    mover.pre_delete(full_path, os.path.join(self._deletiondir,
1525
 
                                     trans_id))
1526
 
                elif trans_id in self._new_name or trans_id in \
1527
 
                    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):
1528
1800
                    try:
1529
1801
                        mover.rename(full_path, self._limbo_name(trans_id))
1530
 
                    except OSError, e:
 
1802
                    except errors.TransformRenameFailed, e:
1531
1803
                        if e.errno != errno.ENOENT:
1532
1804
                            raise
1533
1805
                    else:
1549
1821
        modified_paths = []
1550
1822
        new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1551
1823
                                 new_paths)
1552
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1824
        child_pb = ui.ui_factory.nested_progress_bar()
1553
1825
        try:
1554
1826
            for num, (path, trans_id) in enumerate(new_paths):
1555
1827
                if (num % 10) == 0:
1558
1830
                if trans_id in self._needs_rename:
1559
1831
                    try:
1560
1832
                        mover.rename(self._limbo_name(trans_id), full_path)
1561
 
                    except OSError, e:
 
1833
                    except errors.TransformRenameFailed, e:
1562
1834
                        # We may be renaming a dangling inventory id
1563
1835
                        if e.errno != errno.ENOENT:
1564
1836
                            raise
1565
1837
                    else:
1566
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.
1567
1842
                if (trans_id in self._new_contents or
1568
1843
                    self.path_changed(trans_id)):
1569
1844
                    if trans_id in self._new_contents:
1570
1845
                        modified_paths.append(full_path)
1571
1846
                if trans_id in self._new_executability:
1572
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)
1573
1852
        finally:
1574
1853
            child_pb.finished()
1575
1854
        self._new_contents.clear()
1576
1855
        return modified_paths
1577
1856
 
 
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
 
1578
1880
 
1579
1881
class TransformPreview(DiskTreeTransform):
1580
1882
    """A TreeTransform for generating preview trees.
1584
1886
    unversioned files in the input tree.
1585
1887
    """
1586
1888
 
1587
 
    def __init__(self, tree, pb=DummyProgress(), case_sensitive=True):
 
1889
    def __init__(self, tree, pb=None, case_sensitive=True):
1588
1890
        tree.lock_read()
1589
1891
        limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
1590
1892
        DiskTreeTransform.__init__(self, tree, limbodir, pb, case_sensitive)
1595
1897
    def tree_kind(self, trans_id):
1596
1898
        path = self._tree_id_paths.get(trans_id)
1597
1899
        if path is None:
1598
 
            raise NoSuchFile(None)
1599
 
        file_id = self._tree.path2id(path)
1600
 
        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
1601
1905
 
1602
1906
    def _set_mode(self, trans_id, mode_id, typefunc):
1603
1907
        """Set the mode of new file contents.
1623
1927
            childpath = joinpath(path, child)
1624
1928
            yield self.trans_id_tree_path(childpath)
1625
1929
 
1626
 
 
1627
 
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):
1628
1935
    """Partial implementation of Tree to support show_diff_trees"""
1629
1936
 
1630
1937
    def __init__(self, transform):
1635
1942
        self._all_children_cache = {}
1636
1943
        self._path2trans_id_cache = {}
1637
1944
        self._final_name_cache = {}
1638
 
 
1639
 
    def _changes(self, file_id):
1640
 
        for changes in self._transform.iter_changes():
1641
 
            if changes[0] == file_id:
1642
 
                return changes
 
1945
        self._iter_changes_cache = dict((c[0], c) for c in
 
1946
                                        self._transform.iter_changes())
1643
1947
 
1644
1948
    def _content_change(self, file_id):
1645
1949
        """Return True if the content of this file changed"""
1646
 
        changes = self._changes(file_id)
 
1950
        changes = self._iter_changes_cache.get(file_id)
1647
1951
        # changes[2] is true if the file content changed.  See
1648
1952
        # InterTree.iter_changes.
1649
1953
        return (changes is not None and changes[2])
1662
1966
                yield self._get_repository().revision_tree(revision_id)
1663
1967
 
1664
1968
    def _get_file_revision(self, file_id, vf, tree_revision):
1665
 
        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
1666
1970
                       self._iter_parent_trees()]
1667
1971
        vf.add_lines((file_id, tree_revision), parent_keys,
1668
 
                     self.get_file(file_id).readlines())
 
1972
                     self.get_file_lines(file_id))
1669
1973
        repo = self._get_repository()
1670
1974
        base_vf = repo.texts
1671
1975
        if base_vf not in vf.fallback_versionedfiles:
1672
1976
            vf.fallback_versionedfiles.append(base_vf)
1673
1977
        return tree_revision
1674
1978
 
1675
 
    def _stat_limbo_file(self, file_id):
1676
 
        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)
1677
1982
        name = self._transform._limbo_name(trans_id)
1678
1983
        return os.lstat(name)
1679
1984
 
1693
1998
            executable = self.is_executable(file_id, path)
1694
1999
        return kind, executable, None
1695
2000
 
 
2001
    def is_locked(self):
 
2002
        return False
 
2003
 
1696
2004
    def lock_read(self):
1697
2005
        # Perhaps in theory, this should lock the TreeTransform?
1698
 
        pass
 
2006
        return self
1699
2007
 
1700
2008
    def unlock(self):
1701
2009
        pass
1790
2098
            if self._transform.final_file_id(trans_id) is None:
1791
2099
                yield self._final_paths._determine_path(trans_id)
1792
2100
 
1793
 
    def _make_inv_entries(self, ordered_entries, specific_file_ids=None):
 
2101
    def _make_inv_entries(self, ordered_entries, specific_file_ids=None,
 
2102
        yield_parents=False):
1794
2103
        for trans_id, parent_file_id in ordered_entries:
1795
2104
            file_id = self._transform.final_file_id(trans_id)
1796
2105
            if file_id is None:
1798
2107
            if (specific_file_ids is not None
1799
2108
                and file_id not in specific_file_ids):
1800
2109
                continue
1801
 
            try:
1802
 
                kind = self._transform.final_kind(trans_id)
1803
 
            except NoSuchFile:
 
2110
            kind = self._transform.final_kind(trans_id)
 
2111
            if kind is None:
1804
2112
                kind = self._transform._tree.stored_kind(file_id)
1805
2113
            new_entry = inventory.make_entry(
1806
2114
                kind,
1822
2130
                ordered_ids.append((trans_id, parent_file_id))
1823
2131
        return ordered_ids
1824
2132
 
1825
 
    def iter_entries_by_dir(self, specific_file_ids=None):
 
2133
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
1826
2134
        # This may not be a maximally efficient implementation, but it is
1827
2135
        # reasonably straightforward.  An implementation that grafts the
1828
2136
        # TreeTransform changes onto the tree's iter_entries_by_dir results
1830
2138
        # position.
1831
2139
        ordered_ids = self._list_files_by_dir()
1832
2140
        for entry, trans_id in self._make_inv_entries(ordered_ids,
1833
 
                                                      specific_file_ids):
 
2141
            specific_file_ids, yield_parents=yield_parents):
1834
2142
            yield unicode(self._final_paths.get_path(trans_id)), entry
1835
2143
 
1836
2144
    def _iter_entries_for_dir(self, dir_path):
1883
2191
    def get_file_mtime(self, file_id, path=None):
1884
2192
        """See Tree.get_file_mtime"""
1885
2193
        if not self._content_change(file_id):
1886
 
            return self._transform._tree.get_file_mtime(file_id, path)
 
2194
            return self._transform._tree.get_file_mtime(file_id)
1887
2195
        return self._stat_limbo_file(file_id).st_mtime
1888
2196
 
1889
2197
    def _file_size(self, entry, stat_value):
1891
2199
 
1892
2200
    def get_file_size(self, file_id):
1893
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
1894
2208
        if self.kind(file_id) == 'file':
1895
2209
            return self._transform._tree.get_file_size(file_id)
1896
2210
        else:
1924
2238
            except errors.NoSuchId:
1925
2239
                return False
1926
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)
 
2249
 
1927
2250
    def path_content_summary(self, path):
1928
2251
        trans_id = self._path2trans_id(path)
1929
2252
        tt = self._transform
1943
2266
                statval = os.lstat(limbo_name)
1944
2267
                size = statval.st_size
1945
2268
                if not supports_executable():
1946
 
                    executable = None
 
2269
                    executable = False
1947
2270
                else:
1948
2271
                    executable = statval.st_mode & S_IEXEC
1949
2272
            else:
1951
2274
                executable = None
1952
2275
            if kind == 'symlink':
1953
2276
                link_or_sha1 = os.readlink(limbo_name).decode(osutils._fs_enc)
1954
 
        if supports_executable():
1955
 
            executable = tt._new_executability.get(trans_id, executable)
 
2277
        executable = tt._new_executability.get(trans_id, executable)
1956
2278
        return kind, size, executable, link_or_sha1
1957
2279
 
1958
2280
    def iter_changes(self, from_tree, include_unchanged=False,
1989
2311
 
1990
2312
    def annotate_iter(self, file_id,
1991
2313
                      default_revision=_mod_revision.CURRENT_REVISION):
1992
 
        changes = self._changes(file_id)
 
2314
        changes = self._iter_changes_cache.get(file_id)
1993
2315
        if changes is None:
1994
2316
            get_old = True
1995
2317
        else:
2018
2340
                                   self.get_file(file_id).readlines(),
2019
2341
                                   default_revision)
2020
2342
 
2021
 
    def get_symlink_target(self, file_id):
 
2343
    def get_symlink_target(self, file_id, path=None):
2022
2344
        """See Tree.get_symlink_target"""
2023
2345
        if not self._content_change(file_id):
2024
2346
            return self._transform._tree.get_symlink_target(file_id)
2039
2361
                path_from_root = self._final_paths.get_path(child_id)
2040
2362
                basename = self._transform.final_name(child_id)
2041
2363
                file_id = self._transform.final_file_id(child_id)
2042
 
                try:
2043
 
                    kind = self._transform.final_kind(child_id)
 
2364
                kind  = self._transform.final_kind(child_id)
 
2365
                if kind is not None:
2044
2366
                    versioned_kind = kind
2045
 
                except NoSuchFile:
 
2367
                else:
2046
2368
                    kind = 'unknown'
2047
2369
                    versioned_kind = self._transform._tree.stored_kind(file_id)
2048
2370
                if versioned_kind == 'directory':
2161
2483
    for num, _unused in enumerate(wt.all_file_ids()):
2162
2484
        if num > 0:  # more than just a root
2163
2485
            raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
2164
 
    existing_files = set()
2165
 
    for dir, files in wt.walkdirs():
2166
 
        existing_files.update(f[0] for f in files)
2167
2486
    file_trans_id = {}
2168
 
    top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
2487
    top_pb = ui.ui_factory.nested_progress_bar()
2169
2488
    pp = ProgressPhase("Build phase", 2, top_pb)
2170
2489
    if tree.inventory.root is not None:
2171
2490
        # This is kind of a hack: we should be altering the root
2184
2503
        pp.next_phase()
2185
2504
        file_trans_id[wt.get_root_id()] = \
2186
2505
            tt.trans_id_tree_file_id(wt.get_root_id())
2187
 
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
2506
        pb = ui.ui_factory.nested_progress_bar()
2188
2507
        try:
2189
2508
            deferred_contents = []
2190
2509
            num = 0
2193
2512
                precomputed_delta = []
2194
2513
            else:
2195
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)
2196
2524
            for num, (tree_path, entry) in \
2197
2525
                enumerate(tree.inventory.iter_entries_by_dir()):
2198
2526
                pb.update("Building tree", num - len(deferred_contents), total)
2228
2556
                    executable = tree.is_executable(file_id, tree_path)
2229
2557
                    if executable:
2230
2558
                        tt.set_executability(executable, trans_id)
2231
 
                    trans_data = (trans_id, tree_path)
 
2559
                    trans_data = (trans_id, tree_path, entry.text_sha1)
2232
2560
                    deferred_contents.append((file_id, trans_data))
2233
2561
                else:
2234
2562
                    file_trans_id[file_id] = new_by_entry(tt, entry, parent_id,
2250
2578
            precomputed_delta = None
2251
2579
        conflicts = cook_conflicts(raw_conflicts, tt)
2252
2580
        for conflict in conflicts:
2253
 
            warning(conflict)
 
2581
            trace.warning(conflict)
2254
2582
        try:
2255
2583
            wt.add_conflicts(conflicts)
2256
2584
        except errors.UnsupportedOperation:
2271
2599
        new_desired_files = desired_files
2272
2600
    else:
2273
2601
        iter = accelerator_tree.iter_changes(tree, include_unchanged=True)
2274
 
        unchanged = dict((f, p[1]) for (f, p, c, v, d, n, k, e)
2275
 
                         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)
2276
2608
        new_desired_files = []
2277
2609
        count = 0
2278
 
        for file_id, (trans_id, tree_path) in desired_files:
 
2610
        for file_id, (trans_id, tree_path, text_sha1) in desired_files:
2279
2611
            accelerator_path = unchanged.get(file_id)
2280
2612
            if accelerator_path is None:
2281
 
                new_desired_files.append((file_id, (trans_id, tree_path)))
 
2613
                new_desired_files.append((file_id,
 
2614
                    (trans_id, tree_path, text_sha1)))
2282
2615
                continue
2283
2616
            pb.update('Adding file contents', count + offset, total)
2284
2617
            if hardlink:
2291
2624
                    contents = filtered_output_bytes(contents, filters,
2292
2625
                        ContentFilterContext(tree_path, tree))
2293
2626
                try:
2294
 
                    tt.create_file(contents, trans_id)
 
2627
                    tt.create_file(contents, trans_id, sha1=text_sha1)
2295
2628
                finally:
2296
2629
                    try:
2297
2630
                        contents.close()
2300
2633
                        pass
2301
2634
            count += 1
2302
2635
        offset += count
2303
 
    for count, ((trans_id, tree_path), contents) in enumerate(
 
2636
    for count, ((trans_id, tree_path, text_sha1), contents) in enumerate(
2304
2637
            tree.iter_files_bytes(new_desired_files)):
2305
2638
        if wt.supports_content_filtering():
2306
2639
            filters = wt._content_filter_stack(tree_path)
2307
2640
            contents = filtered_output_bytes(contents, filters,
2308
2641
                ContentFilterContext(tree_path, tree))
2309
 
        tt.create_file(contents, trans_id)
 
2642
        tt.create_file(contents, trans_id, sha1=text_sha1)
2310
2643
        pb.update('Adding file contents', count + offset, total)
2311
2644
 
2312
2645
 
2314
2647
    for child in tt.iter_tree_children(old_parent):
2315
2648
        tt.adjust_path(tt.final_name(child), new_parent, child)
2316
2649
 
 
2650
 
2317
2651
def _reparent_transform_children(tt, old_parent, new_parent):
2318
2652
    by_parent = tt.by_parent()
2319
2653
    for child in by_parent[old_parent]:
2320
2654
        tt.adjust_path(tt.final_name(child), new_parent, child)
2321
2655
    return by_parent[old_parent]
2322
2656
 
 
2657
 
2323
2658
def _content_match(tree, entry, file_id, kind, target_path):
2324
2659
    if entry.kind != kind:
2325
2660
        return False
2326
2661
    if entry.kind == "directory":
2327
2662
        return True
2328
2663
    if entry.kind == "file":
2329
 
        if tree.get_file(file_id).read() == file(target_path, 'rb').read():
2330
 
            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()
2331
2670
    elif entry.kind == "symlink":
2332
2671
        if tree.get_symlink_target(file_id) == os.readlink(target_path):
2333
2672
            return True
2385
2724
        raise errors.BadFileKindError(name, kind)
2386
2725
 
2387
2726
 
2388
 
@deprecated_function(deprecated_in((1, 9, 0)))
2389
 
def create_by_entry(tt, entry, tree, trans_id, lines=None, mode_id=None):
2390
 
    """Create new file contents according to an inventory entry.
2391
 
 
2392
 
    DEPRECATED.  Use create_from_tree instead.
 
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.
2393
2734
    """
2394
 
    if entry.kind == "file":
2395
 
        if lines is None:
2396
 
            lines = tree.get_file(entry.file_id).readlines()
2397
 
        tt.create_file(lines, trans_id, mode_id=mode_id)
2398
 
    elif entry.kind == "symlink":
2399
 
        tt.create_symlink(tree.get_symlink_target(entry.file_id), trans_id)
2400
 
    elif entry.kind == "directory":
2401
 
        tt.create_directory(trans_id)
2402
 
 
2403
 
 
2404
 
def create_from_tree(tt, trans_id, tree, file_id, bytes=None):
2405
 
    """Create new file contents according to tree contents."""
2406
2735
    kind = tree.kind(file_id)
2407
2736
    if kind == 'directory':
2408
2737
        tt.create_directory(trans_id)
2413
2742
                bytes = tree_file.readlines()
2414
2743
            finally:
2415
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))
2416
2750
        tt.create_file(bytes, trans_id)
2417
2751
    elif kind == "symlink":
2418
2752
        tt.create_symlink(tree.get_symlink_target(file_id), trans_id)
2426
2760
        tt.set_executability(entry.executable, trans_id)
2427
2761
 
2428
2762
 
 
2763
@deprecated_function(deprecated_in((2, 3, 0)))
2429
2764
def get_backup_name(entry, by_parent, parent_trans_id, tt):
2430
2765
    return _get_backup_name(entry.name, by_parent, parent_trans_id, tt)
2431
2766
 
2432
2767
 
 
2768
@deprecated_function(deprecated_in((2, 3, 0)))
2433
2769
def _get_backup_name(name, by_parent, parent_trans_id, tt):
2434
2770
    """Produce a backup-style name that appears to be available"""
2435
2771
    def name_gen():
2470
2806
 
2471
2807
 
2472
2808
def revert(working_tree, target_tree, filenames, backups=False,
2473
 
           pb=DummyProgress(), change_reporter=None):
 
2809
           pb=None, change_reporter=None):
2474
2810
    """Revert a working tree's contents to those of a target tree."""
2475
2811
    target_tree.lock_read()
 
2812
    pb = ui.ui_factory.nested_progress_bar()
2476
2813
    tt = TreeTransform(working_tree, pb)
2477
2814
    try:
2478
2815
        pp = ProgressPhase("Revert phase", 3, pb)
2483
2820
                unversioned_filter=working_tree.is_ignored)
2484
2821
            delta.report_changes(tt.iter_changes(), change_reporter)
2485
2822
        for conflict in conflicts:
2486
 
            warning(conflict)
 
2823
            trace.warning(conflict)
2487
2824
        pp.next_phase()
2488
2825
        tt.apply()
2489
2826
        working_tree.set_merge_modified(merge_modified)
2497
2834
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
2498
2835
                              backups, pp, basis_tree=None,
2499
2836
                              merge_modified=None):
2500
 
    pp.next_phase()
2501
 
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
2837
    child_pb = ui.ui_factory.nested_progress_bar()
2502
2838
    try:
2503
2839
        if merge_modified is None:
2504
2840
            merge_modified = working_tree.merge_modified()
2507
2843
                                      merge_modified, basis_tree)
2508
2844
    finally:
2509
2845
        child_pb.finished()
2510
 
    pp.next_phase()
2511
 
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
2846
    child_pb = ui.ui_factory.nested_progress_bar()
2512
2847
    try:
2513
2848
        raw_conflicts = resolve_conflicts(tt, child_pb,
2514
2849
            lambda t, c: conflict_pass(t, c, target_tree))
2522
2857
                 backups, merge_modified, basis_tree=None):
2523
2858
    if basis_tree is not None:
2524
2859
        basis_tree.lock_read()
2525
 
    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,
2526
2865
        specific_files=specific_files, pb=pb)
2527
2866
    if target_tree.get_root_id() is None:
2528
2867
        skip_root = True
2532
2871
        deferred_files = []
2533
2872
        for id_num, (file_id, path, changed_content, versioned, parent, name,
2534
2873
                kind, executable) in enumerate(change_list):
2535
 
            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:
2536
2881
                continue
2537
2882
            trans_id = tt.trans_id_file_id(file_id)
2538
2883
            mode_id = None
2539
2884
            if changed_content:
2540
2885
                keep_content = False
2541
 
                if kind[0] == 'file' and (backups or kind[1] is None):
 
2886
                if wt_kind == 'file' and (backups or target_kind is None):
2542
2887
                    wt_sha1 = working_tree.get_file_sha1(file_id)
2543
2888
                    if merge_modified.get(file_id) != wt_sha1:
2544
2889
                        # acquire the basis tree lazily to prevent the
2550
2895
                        if file_id in basis_tree:
2551
2896
                            if wt_sha1 != basis_tree.get_file_sha1(file_id):
2552
2897
                                keep_content = True
2553
 
                        elif kind[1] is None and not versioned[1]:
 
2898
                        elif target_kind is None and not target_versioned:
2554
2899
                            keep_content = True
2555
 
                if kind[0] is not None:
 
2900
                if wt_kind is not None:
2556
2901
                    if not keep_content:
2557
2902
                        tt.delete_contents(trans_id)
2558
 
                    elif kind[1] is not None:
2559
 
                        parent_trans_id = tt.trans_id_file_id(parent[0])
2560
 
                        by_parent = tt.by_parent()
2561
 
                        backup_name = _get_backup_name(name[0], by_parent,
2562
 
                                                       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)
2563
2907
                        tt.adjust_path(backup_name, parent_trans_id, trans_id)
2564
 
                        new_trans_id = tt.create_path(name[0], parent_trans_id)
2565
 
                        if versioned == (True, True):
 
2908
                        new_trans_id = tt.create_path(wt_name, parent_trans_id)
 
2909
                        if wt_versioned and target_versioned:
2566
2910
                            tt.unversion_file(trans_id)
2567
2911
                            tt.version_file(file_id, new_trans_id)
2568
2912
                        # New contents should have the same unix perms as old
2569
2913
                        # contents
2570
2914
                        mode_id = trans_id
2571
2915
                        trans_id = new_trans_id
2572
 
                if kind[1] in ('directory', 'tree-reference'):
 
2916
                if target_kind in ('directory', 'tree-reference'):
2573
2917
                    tt.create_directory(trans_id)
2574
 
                    if kind[1] == 'tree-reference':
 
2918
                    if target_kind == 'tree-reference':
2575
2919
                        revision = target_tree.get_reference_revision(file_id,
2576
 
                                                                      path[1])
 
2920
                                                                      target_path)
2577
2921
                        tt.set_tree_reference(revision, trans_id)
2578
 
                elif kind[1] == 'symlink':
 
2922
                elif target_kind == 'symlink':
2579
2923
                    tt.create_symlink(target_tree.get_symlink_target(file_id),
2580
2924
                                      trans_id)
2581
 
                elif kind[1] == 'file':
 
2925
                elif target_kind == 'file':
2582
2926
                    deferred_files.append((file_id, (trans_id, mode_id)))
2583
2927
                    if basis_tree is None:
2584
2928
                        basis_tree = working_tree.basis_tree()
2592
2936
                        merge_modified[file_id] = new_sha1
2593
2937
 
2594
2938
                    # preserve the execute bit when backing up
2595
 
                    if keep_content and executable[0] == executable[1]:
2596
 
                        tt.set_executability(executable[1], trans_id)
2597
 
                elif kind[1] is not None:
2598
 
                    raise AssertionError(kind[1])
2599
 
            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:
2600
2944
                tt.version_file(file_id, trans_id)
2601
 
            if versioned == (True, False):
 
2945
            if wt_versioned and not target_versioned:
2602
2946
                tt.unversion_file(trans_id)
2603
 
            if (name[1] is not None and
2604
 
                (name[0] != name[1] or parent[0] != parent[1])):
2605
 
                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:
2606
2950
                    parent_trans = ROOT_PARENT
2607
2951
                else:
2608
 
                    parent_trans = tt.trans_id_file_id(parent[1])
2609
 
                tt.adjust_path(name[1], parent_trans, trans_id)
2610
 
            if executable[0] != executable[1] and kind[1] == "file":
2611
 
                tt.set_executability(executable[1], trans_id)
2612
 
        for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
2613
 
            deferred_files):
2614
 
            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()
2615
2976
    finally:
2616
2977
        if basis_tree is not None:
2617
2978
            basis_tree.unlock()
2618
2979
    return merge_modified
2619
2980
 
2620
2981
 
2621
 
def resolve_conflicts(tt, pb=DummyProgress(), pass_func=None):
 
2982
def resolve_conflicts(tt, pb=None, pass_func=None):
2622
2983
    """Make many conflict-resolution attempts, but die if they fail"""
2623
2984
    if pass_func is None:
2624
2985
        pass_func = conflict_pass
2625
2986
    new_conflicts = set()
 
2987
    pb = ui.ui_factory.nested_progress_bar()
2626
2988
    try:
2627
2989
        for n in range(10):
2628
2990
            pb.update('Resolution pass', n+1, 10)
2632
2994
            new_conflicts.update(pass_func(tt, conflicts))
2633
2995
        raise MalformedTransform(conflicts=conflicts)
2634
2996
    finally:
2635
 
        pb.clear()
 
2997
        pb.finished()
2636
2998
 
2637
2999
 
2638
3000
def conflict_pass(tt, conflicts, path_tree=None):
2670
3032
 
2671
3033
        elif c_type == 'missing parent':
2672
3034
            trans_id = conflict[1]
2673
 
            try:
2674
 
                tt.cancel_deletion(trans_id)
2675
 
                new_conflicts.add(('deleting parent', 'Not deleting',
2676
 
                                   trans_id))
2677
 
            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:
2678
3059
                create = True
2679
3060
                try:
2680
3061
                    tt.final_name(trans_id)
2683
3064
                        file_id = tt.final_file_id(trans_id)
2684
3065
                        if file_id is None:
2685
3066
                            file_id = tt.inactive_file_id(trans_id)
2686
 
                        entry = path_tree.inventory[file_id]
 
3067
                        _, entry = path_tree.iter_entries_by_dir(
 
3068
                            [file_id]).next()
2687
3069
                        # special-case the other tree root (move its
2688
3070
                        # children to current root)
2689
3071
                        if entry.parent_id is None:
2690
 
                            create=False
 
3072
                            create = False
2691
3073
                            moved = _reparent_transform_children(
2692
3074
                                tt, trans_id, tt.root)
2693
3075
                            for child in moved:
2705
3087
            file_id = tt.inactive_file_id(conflict[1])
2706
3088
            # special-case the other tree root (move its children instead)
2707
3089
            if path_tree and file_id in path_tree:
2708
 
                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
2709
3092
                    continue
2710
3093
            tt.version_file(file_id, conflict[1])
2711
3094
            new_conflicts.add((c_type, 'Versioned directory', conflict[1]))
2761
3144
        self.pending_deletions = []
2762
3145
 
2763
3146
    def rename(self, from_, to):
2764
 
        """Rename a file from one path to another.  Functions like os.rename"""
 
3147
        """Rename a file from one path to another."""
2765
3148
        try:
2766
3149
            os.rename(from_, to)
2767
3150
        except OSError, e:
2768
3151
            if e.errno in (errno.EEXIST, errno.ENOTEMPTY):
2769
3152
                raise errors.FileExists(to, str(e))
2770
 
            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)
2771
3156
        self.past_renames.append((from_, to))
2772
3157
 
2773
3158
    def pre_delete(self, from_, to):
2783
3168
    def rollback(self):
2784
3169
        """Reverse all renames that have been performed"""
2785
3170
        for from_, to in reversed(self.past_renames):
2786
 
            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)
2787
3175
        # after rollback, don't reuse _FileMover
2788
3176
        past_renames = None
2789
3177
        pending_deletions = None