~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transform.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2007-11-03 01:53:30 UTC
  • mfrom: (2955.1.1 trunk)
  • Revision ID: pqm@pqm.ubuntu.com-20071103015330-pt1tec7wyxwwcey8
Fix #158972 don't use timeout for HttpServer

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2006, 2007 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
16
16
 
17
17
import os
18
18
import errno
19
 
from stat import S_ISREG, S_IEXEC
 
19
from stat import S_ISREG
20
20
 
21
21
from bzrlib.lazy_import import lazy_import
22
22
lazy_import(globals(), """
23
23
from bzrlib import (
24
 
    annotate,
25
24
    bzrdir,
26
25
    delta,
27
26
    errors,
28
 
    inventory,
29
 
    osutils,
30
 
    revision as _mod_revision,
 
27
    inventory
31
28
    )
32
29
""")
33
30
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
34
31
                           ReusingTransform, NotVersionedError, CantMoveRoot,
35
 
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
36
 
                           UnableCreateSymlink)
 
32
                           ExistingLimbo, ImmortalLimbo, NoFinalPath)
37
33
from bzrlib.inventory import InventoryEntry
38
 
from bzrlib.osutils import (
39
 
    delete_any,
40
 
    file_kind,
41
 
    has_symlinks,
42
 
    lexists,
43
 
    pathjoin,
44
 
    splitpath,
45
 
    supports_executable,
46
 
)
 
34
from bzrlib.osutils import (file_kind, supports_executable, pathjoin, lexists,
 
35
                            delete_any)
47
36
from bzrlib.progress import DummyProgress, ProgressPhase
48
37
from bzrlib.symbol_versioning import (
49
38
        deprecated_function,
 
39
        zero_fifteen,
 
40
        zero_ninety,
50
41
        )
51
42
from bzrlib.trace import mutter, warning
52
43
from bzrlib import tree
70
61
        self.rename_count = rename_count
71
62
 
72
63
 
73
 
class TreeTransformBase(object):
74
 
    """The base class for TreeTransform and TreeTransformBase"""
75
 
 
76
 
    def __init__(self, tree, limbodir, pb=DummyProgress(),
77
 
                 case_sensitive=True):
78
 
        """Constructor.
79
 
 
80
 
        :param tree: The tree that will be transformed, but not necessarily
81
 
            the output tree.
82
 
        :param limbodir: A directory where new files can be stored until
83
 
            they are installed in their proper places
84
 
        :param pb: A ProgressBar indicating how much progress is being made
85
 
        :param case_sensitive: If True, the target of the transform is
86
 
            case sensitive, not just case preserving.
 
64
class TreeTransform(object):
 
65
    """Represent a tree transformation.
 
66
    
 
67
    This object is designed to support incremental generation of the transform,
 
68
    in any order.
 
69
 
 
70
    However, it gives optimum performance when parent directories are created
 
71
    before their contents.  The transform is then able to put child files
 
72
    directly in their parent directory, avoiding later renames.
 
73
    
 
74
    It is easy to produce malformed transforms, but they are generally
 
75
    harmless.  Attempting to apply a malformed transform will cause an
 
76
    exception to be raised before any modifications are made to the tree.  
 
77
 
 
78
    Many kinds of malformed transforms can be corrected with the 
 
79
    resolve_conflicts function.  The remaining ones indicate programming error,
 
80
    such as trying to create a file with no path.
 
81
 
 
82
    Two sets of file creation methods are supplied.  Convenience methods are:
 
83
     * new_file
 
84
     * new_directory
 
85
     * new_symlink
 
86
 
 
87
    These are composed of the low-level methods:
 
88
     * create_path
 
89
     * create_file or create_directory or create_symlink
 
90
     * version_file
 
91
     * set_executability
 
92
    """
 
93
    def __init__(self, tree, pb=DummyProgress()):
 
94
        """Note: a tree_write lock is taken on the tree.
 
95
        
 
96
        Use TreeTransform.finalize() to release the lock (can be omitted if
 
97
        TreeTransform.apply() called).
87
98
        """
88
99
        object.__init__(self)
89
100
        self._tree = tree
90
 
        self._limbodir = limbodir
91
 
        self._deletiondir = None
 
101
        self._tree.lock_tree_write()
 
102
        try:
 
103
            control_files = self._tree._control_files
 
104
            self._limbodir = urlutils.local_path_from_url(
 
105
                control_files.controlfilename('limbo'))
 
106
            try:
 
107
                os.mkdir(self._limbodir)
 
108
            except OSError, e:
 
109
                if e.errno == errno.EEXIST:
 
110
                    raise ExistingLimbo(self._limbodir)
 
111
            self._deletiondir = urlutils.local_path_from_url(
 
112
                control_files.controlfilename('pending-deletion'))
 
113
            try:
 
114
                os.mkdir(self._deletiondir)
 
115
            except OSError, e:
 
116
                if e.errno == errno.EEXIST:
 
117
                    raise errors.ExistingPendingDeletion(self._deletiondir)
 
118
 
 
119
        except: 
 
120
            self._tree.unlock()
 
121
            raise
 
122
 
92
123
        self._id_number = 0
93
 
        # mapping of trans_id -> new basename
94
124
        self._new_name = {}
95
 
        # mapping of trans_id -> new parent trans_id
96
125
        self._new_parent = {}
97
 
        # mapping of trans_id with new contents -> new file_kind
98
126
        self._new_contents = {}
99
127
        # A mapping of transform ids to their limbo filename
100
128
        self._limbo_files = {}
105
133
        self._limbo_children_names = {}
106
134
        # List of transform ids that need to be renamed from limbo into place
107
135
        self._needs_rename = set()
108
 
        # Set of trans_ids whose contents will be removed
109
136
        self._removed_contents = set()
110
 
        # Mapping of trans_id -> new execute-bit value
111
137
        self._new_executability = {}
112
 
        # Mapping of trans_id -> new tree-reference value
113
138
        self._new_reference_revision = {}
114
 
        # Mapping of trans_id -> new file_id
115
139
        self._new_id = {}
116
 
        # Mapping of old file-id -> trans_id
117
140
        self._non_present_ids = {}
118
 
        # Mapping of new file_id -> trans_id
119
141
        self._r_new_id = {}
120
 
        # Set of file_ids that will be removed
121
142
        self._removed_id = set()
122
 
        # Mapping of path in old tree -> trans_id
123
143
        self._tree_path_ids = {}
124
 
        # Mapping trans_id -> path in old tree
125
144
        self._tree_id_paths = {}
126
145
        # Cache of realpath results, to speed up canonical_path
127
146
        self._realpaths = {}
128
147
        # Cache of relpath results, to speed up canonical_path
129
148
        self._relpaths = {}
130
 
        # The trans_id that will be used as the tree root
131
 
        root_id = tree.get_root_id()
132
 
        if root_id is not None:
133
 
            self._new_root = self.trans_id_tree_file_id(root_id)
134
 
        else:
135
 
            self._new_root = None
136
 
        # Indictor of whether the transform has been applied
137
 
        self._done = False
138
 
        # A progress bar
 
149
        self._new_root = self.trans_id_tree_file_id(tree.get_root_id())
 
150
        self.__done = False
139
151
        self._pb = pb
140
 
        # Whether the target is case sensitive
141
 
        self._case_sensitive_target = case_sensitive
142
 
        # A counter of how many files have been renamed
143
152
        self.rename_count = 0
144
153
 
145
154
    def __get_root(self):
170
179
                # We don't especially care *why* the dir is immortal.
171
180
                raise ImmortalLimbo(self._limbodir)
172
181
            try:
173
 
                if self._deletiondir is not None:
174
 
                    os.rmdir(self._deletiondir)
 
182
                os.rmdir(self._deletiondir)
175
183
            except OSError:
176
184
                raise errors.ImmortalPendingDeletion(self._deletiondir)
177
185
        finally:
199
207
        previous_name = self._new_name.get(trans_id)
200
208
        self._new_name[trans_id] = name
201
209
        self._new_parent[trans_id] = parent
202
 
        if parent == ROOT_PARENT:
203
 
            if self._new_root is not None:
204
 
                raise ValueError("Cannot have multiple roots.")
205
 
            self._new_root = trans_id
206
210
        if (trans_id in self._limbo_files and
207
211
            trans_id not in self._needs_rename):
208
212
            self._rename_in_limbo([trans_id])
265
269
        This reflects only files that already exist, not ones that will be
266
270
        added by transactions.
267
271
        """
268
 
        if inventory_id is None:
269
 
            raise ValueError('None is not a valid file id')
270
 
        path = self._tree.id2path(inventory_id)
 
272
        path = self._tree.inventory.id2path(inventory_id)
271
273
        return self.trans_id_tree_path(path)
272
274
 
273
275
    def trans_id_file_id(self, file_id):
276
278
        a transaction has been unversioned, it is deliberately still returned.
277
279
        (this will likely lead to an unversioned parent conflict.)
278
280
        """
279
 
        if file_id is None:
280
 
            raise ValueError('None is not a valid file id')
281
281
        if file_id in self._r_new_id and self._r_new_id[file_id] is not None:
282
282
            return self._r_new_id[file_id]
283
283
        elif file_id in self._tree.inventory:
366
366
        try:
367
367
            mode = os.stat(self._tree.abspath(old_path)).st_mode
368
368
        except OSError, e:
369
 
            if e.errno in (errno.ENOENT, errno.ENOTDIR):
370
 
                # Either old_path doesn't exist, or the parent of the
371
 
                # target is not a directory (but will be one eventually)
372
 
                # Either way, we know it doesn't exist *right now*
373
 
                # See also bug #248448
 
369
            if e.errno == errno.ENOENT:
374
370
                return
375
371
            else:
376
372
                raise
377
373
        if typefunc(mode):
378
374
            os.chmod(self._limbo_name(trans_id), mode)
379
375
 
380
 
    def create_hardlink(self, path, trans_id):
381
 
        """Schedule creation of a hard link"""
382
 
        name = self._limbo_name(trans_id)
383
 
        try:
384
 
            os.link(path, name)
385
 
        except OSError, e:
386
 
            if e.errno != errno.EPERM:
387
 
                raise
388
 
            raise errors.HardLinkNotSupported(path)
389
 
        try:
390
 
            unique_add(self._new_contents, trans_id, 'file')
391
 
        except:
392
 
            # Clean up the file, it never got registered so
393
 
            # TreeTransform.finalize() won't clean it up.
394
 
            os.unlink(name)
395
 
            raise
396
 
 
397
376
    def create_directory(self, trans_id):
398
377
        """Schedule creation of a new directory.
399
378
        
408
387
        target is a bytestring.
409
388
        See also new_symlink.
410
389
        """
411
 
        if has_symlinks():
412
 
            os.symlink(target, self._limbo_name(trans_id))
413
 
            unique_add(self._new_contents, trans_id, 'symlink')
414
 
        else:
415
 
            try:
416
 
                path = FinalPaths(self).get_path(trans_id)
417
 
            except KeyError:
418
 
                path = None
419
 
            raise UnableCreateSymlink(path=path)
 
390
        os.symlink(target, self._limbo_name(trans_id))
 
391
        unique_add(self._new_contents, trans_id, 'symlink')
420
392
 
421
393
    def cancel_creation(self, trans_id):
422
394
        """Cancel the creation of new file contents."""
463
435
 
464
436
    def version_file(self, file_id, trans_id):
465
437
        """Schedule a file to become versioned."""
466
 
        if file_id is None:
467
 
            raise ValueError()
 
438
        assert file_id is not None
468
439
        unique_add(self._new_id, trans_id, file_id)
469
440
        unique_add(self._r_new_id, file_id, trans_id)
470
441
 
474
445
        del self._new_id[trans_id]
475
446
        del self._r_new_id[file_id]
476
447
 
477
 
    def new_paths(self, filesystem_only=False):
478
 
        """Determine the paths of all new and changed files.
479
 
 
480
 
        :param filesystem_only: if True, only calculate values for files
481
 
            that require renames or execute bit changes.
482
 
        """
483
 
        new_ids = set()
484
 
        if filesystem_only:
485
 
            stale_ids = self._needs_rename.difference(self._new_name)
486
 
            stale_ids.difference_update(self._new_parent)
487
 
            stale_ids.difference_update(self._new_contents)
488
 
            stale_ids.difference_update(self._new_id)
489
 
            needs_rename = self._needs_rename.difference(stale_ids)
490
 
            id_sets = (needs_rename, self._new_executability)
491
 
        else:
492
 
            id_sets = (self._new_name, self._new_parent, self._new_contents,
493
 
                       self._new_id, self._new_executability)
494
 
        for id_set in id_sets:
495
 
            new_ids.update(id_set)
496
 
        return sorted(FinalPaths(self).get_paths(new_ids))
497
 
 
498
 
    def _inventory_altered(self):
499
 
        """Get the trans_ids and paths of files needing new inv entries."""
500
 
        new_ids = set()
501
 
        for id_set in [self._new_name, self._new_parent, self._new_id,
502
 
                       self._new_executability]:
503
 
            new_ids.update(id_set)
504
 
        changed_kind = set(self._removed_contents)
505
 
        changed_kind.intersection_update(self._new_contents)
506
 
        changed_kind.difference_update(new_ids)
507
 
        changed_kind = (t for t in changed_kind if self.tree_kind(t) !=
508
 
                        self.final_kind(t))
509
 
        new_ids.update(changed_kind)
510
 
        return sorted(FinalPaths(self).get_paths(new_ids))
 
448
    def new_paths(self):
 
449
        """Determine the paths of all new and changed files"""
 
450
        new_ids = set()
 
451
        fp = FinalPaths(self)
 
452
        for id_set in (self._new_name, self._new_parent, self._new_contents,
 
453
                       self._new_id, self._new_executability):
 
454
            new_ids.update(id_set)
 
455
        new_paths = [(fp.get_path(t), t) for t in new_ids]
 
456
        new_paths.sort()
 
457
        return new_paths
511
458
 
512
459
    def tree_kind(self, trans_id):
513
460
        """Determine the file kind in the working tree.
548
495
            return None
549
496
        # the file is old; the old id is still valid
550
497
        if self._new_root == trans_id:
551
 
            return self._tree.get_root_id()
 
498
            return self._tree.inventory.root.file_id
552
499
        return self._tree.inventory.path2id(path)
553
500
 
554
501
    def final_file_id(self, trans_id):
558
505
        applied.
559
506
        """
560
507
        try:
 
508
            # there is a new id for this file
 
509
            assert self._new_id[trans_id] is not None
561
510
            return self._new_id[trans_id]
562
511
        except KeyError:
563
512
            if trans_id in self._removed_id:
620
569
 
621
570
    def find_conflicts(self):
622
571
        """Find any violations of inventory or filesystem invariants"""
623
 
        if self._done is True:
 
572
        if self.__done is True:
624
573
            raise ReusingTransform()
625
574
        conflicts = []
626
575
        # ensure all children of all existent parents are known
648
597
                        self.tree_kind(t) == 'directory'])
649
598
        for trans_id in self._removed_id:
650
599
            file_id = self.tree_file_id(trans_id)
651
 
            if file_id is not None:
652
 
                if self._tree.inventory[file_id].kind == 'directory':
653
 
                    parents.append(trans_id)
654
 
            elif self.tree_kind(trans_id) == 'directory':
 
600
            if self._tree.inventory[file_id].kind == 'directory':
655
601
                parents.append(trans_id)
656
602
 
657
603
        for parent_id in parents:
667
613
        try:
668
614
            children = os.listdir(self._tree.abspath(path))
669
615
        except OSError, e:
670
 
            if not (osutils._is_error_enotdir(e)
671
 
                    or e.errno in (errno.ENOENT, errno.ESRCH)):
 
616
            if e.errno != errno.ENOENT and e.errno != errno.ESRCH:
672
617
                raise
673
618
            return
674
 
 
 
619
            
675
620
        for child in children:
676
621
            childpath = joinpath(path, child)
677
622
            if self._tree.is_control_filename(childpath):
792
737
            return conflicts
793
738
        for children in by_parent.itervalues():
794
739
            name_ids = [(self.final_name(t), t) for t in children]
795
 
            if not self._case_sensitive_target:
796
 
                name_ids = [(n.lower(), t) for n, t in name_ids]
797
740
            name_ids.sort()
798
741
            last_name = None
799
742
            last_trans_id = None
817
760
        conflicts = []
818
761
        removed_tree_ids = set((self.tree_file_id(trans_id) for trans_id in
819
762
                                self._removed_id))
820
 
        all_ids = self._tree.all_file_ids()
821
 
        active_tree_ids = all_ids.difference(removed_tree_ids)
 
763
        active_tree_ids = set((f for f in self._tree.inventory if
 
764
                               f not in removed_tree_ids))
822
765
        for trans_id, file_id in self._new_id.iteritems():
823
766
            if file_id in active_tree_ids:
824
767
                old_trans_id = self.trans_id_tree_file_id(file_id)
857
800
                continue
858
801
            return True
859
802
        return False
 
803
            
 
804
    def apply(self, no_conflicts=False, _mover=None):
 
805
        """Apply all changes to the inventory and filesystem.
 
806
        
 
807
        If filesystem or inventory conflicts are present, MalformedTransform
 
808
        will be thrown.
 
809
 
 
810
        If apply succeeds, finalize is not necessary.
 
811
 
 
812
        :param no_conflicts: if True, the caller guarantees there are no
 
813
            conflicts, so no check is made.
 
814
        :param _mover: Supply an alternate FileMover, for testing
 
815
        """
 
816
        if not no_conflicts:
 
817
            conflicts = self.find_conflicts()
 
818
            if len(conflicts) != 0:
 
819
                raise MalformedTransform(conflicts=conflicts)
 
820
        inv = self._tree.inventory
 
821
        inventory_delta = []
 
822
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
823
        try:
 
824
            if _mover is None:
 
825
                mover = _FileMover()
 
826
            else:
 
827
                mover = _mover
 
828
            try:
 
829
                child_pb.update('Apply phase', 0, 2)
 
830
                self._apply_removals(inv, inventory_delta, mover)
 
831
                child_pb.update('Apply phase', 1, 2)
 
832
                modified_paths = self._apply_insertions(inv, inventory_delta,
 
833
                                                        mover)
 
834
            except:
 
835
                mover.rollback()
 
836
                raise
 
837
            else:
 
838
                mover.apply_deletions()
 
839
        finally:
 
840
            child_pb.finished()
 
841
        self._tree.apply_inventory_delta(inventory_delta)
 
842
        self.__done = True
 
843
        self.finalize()
 
844
        return _TransformResults(modified_paths, self.rename_count)
860
845
 
861
846
    def _limbo_name(self, trans_id):
862
847
        """Generate the limbo name of a file"""
878
863
                # the direct path can only be used if no other file has
879
864
                # already taken this pathname, i.e. if the name is unused, or
880
865
                # if it is already associated with this trans_id.
881
 
                elif self._case_sensitive_target:
882
 
                    if (self._limbo_children_names[parent].get(filename)
883
 
                        in (trans_id, None)):
884
 
                        use_direct_path = True
885
 
                else:
886
 
                    for l_filename, l_trans_id in\
887
 
                        self._limbo_children_names[parent].iteritems():
888
 
                        if l_trans_id == trans_id:
889
 
                            continue
890
 
                        if l_filename.lower() == filename.lower():
891
 
                            break
892
 
                    else:
893
 
                        use_direct_path = True
894
 
 
 
866
                elif (self._limbo_children_names[parent].get(filename)
 
867
                      in (trans_id, None)):
 
868
                    use_direct_path = True
895
869
        if use_direct_path:
896
870
            limbo_name = pathjoin(self._limbo_files[parent], filename)
897
871
            self._limbo_children[parent].add(trans_id)
902
876
        self._limbo_files[trans_id] = limbo_name
903
877
        return limbo_name
904
878
 
905
 
    def _set_executability(self, path, trans_id):
 
879
    def _apply_removals(self, inv, inventory_delta, mover):
 
880
        """Perform tree operations that remove directory/inventory names.
 
881
        
 
882
        That is, delete files that are to be deleted, and put any files that
 
883
        need renaming into limbo.  This must be done in strict child-to-parent
 
884
        order.
 
885
        """
 
886
        tree_paths = list(self._tree_path_ids.iteritems())
 
887
        tree_paths.sort(reverse=True)
 
888
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
889
        try:
 
890
            for num, data in enumerate(tree_paths):
 
891
                path, trans_id = data
 
892
                child_pb.update('removing file', num, len(tree_paths))
 
893
                full_path = self._tree.abspath(path)
 
894
                if trans_id in self._removed_contents:
 
895
                    mover.pre_delete(full_path, os.path.join(self._deletiondir,
 
896
                                     trans_id))
 
897
                elif trans_id in self._new_name or trans_id in \
 
898
                    self._new_parent:
 
899
                    try:
 
900
                        mover.rename(full_path, self._limbo_name(trans_id))
 
901
                    except OSError, e:
 
902
                        if e.errno != errno.ENOENT:
 
903
                            raise
 
904
                    else:
 
905
                        self.rename_count += 1
 
906
                if trans_id in self._removed_id:
 
907
                    if trans_id == self._new_root:
 
908
                        file_id = self._tree.inventory.root.file_id
 
909
                    else:
 
910
                        file_id = self.tree_file_id(trans_id)
 
911
                    assert file_id is not None
 
912
                    inventory_delta.append((path, None, file_id, None))
 
913
        finally:
 
914
            child_pb.finished()
 
915
 
 
916
    def _apply_insertions(self, inv, inventory_delta, mover):
 
917
        """Perform tree operations that insert directory/inventory names.
 
918
        
 
919
        That is, create any files that need to be created, and restore from
 
920
        limbo any files that needed renaming.  This must be done in strict
 
921
        parent-to-child order.
 
922
        """
 
923
        new_paths = self.new_paths()
 
924
        modified_paths = []
 
925
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
926
        try:
 
927
            for num, (path, trans_id) in enumerate(new_paths):
 
928
                new_entry = None
 
929
                child_pb.update('adding file', num, len(new_paths))
 
930
                try:
 
931
                    kind = self._new_contents[trans_id]
 
932
                except KeyError:
 
933
                    kind = contents = None
 
934
                if trans_id in self._new_contents or \
 
935
                    self.path_changed(trans_id):
 
936
                    full_path = self._tree.abspath(path)
 
937
                    if trans_id in self._needs_rename:
 
938
                        try:
 
939
                            mover.rename(self._limbo_name(trans_id), full_path)
 
940
                        except OSError, e:
 
941
                            # We may be renaming a dangling inventory id
 
942
                            if e.errno != errno.ENOENT:
 
943
                                raise
 
944
                        else:
 
945
                            self.rename_count += 1
 
946
                    if trans_id in self._new_contents:
 
947
                        modified_paths.append(full_path)
 
948
                        del self._new_contents[trans_id]
 
949
 
 
950
                if trans_id in self._new_id:
 
951
                    if kind is None:
 
952
                        kind = file_kind(self._tree.abspath(path))
 
953
                    if trans_id in self._new_reference_revision:
 
954
                        new_entry = inventory.TreeReference(
 
955
                            self._new_id[trans_id],
 
956
                            self._new_name[trans_id], 
 
957
                            self.final_file_id(self._new_parent[trans_id]),
 
958
                            None, self._new_reference_revision[trans_id])
 
959
                    else:
 
960
                        new_entry = inventory.make_entry(kind,
 
961
                            self.final_name(trans_id),
 
962
                            self.final_file_id(self.final_parent(trans_id)),
 
963
                            self._new_id[trans_id])
 
964
                else:
 
965
                    if trans_id in self._new_name or trans_id in\
 
966
                        self._new_parent or\
 
967
                        trans_id in self._new_executability:
 
968
                        file_id = self.final_file_id(trans_id)
 
969
                        if file_id is not None:
 
970
                            entry = inv[file_id]
 
971
                            new_entry = entry.copy()
 
972
 
 
973
                    if trans_id in self._new_name or trans_id in\
 
974
                        self._new_parent:
 
975
                            if new_entry is not None:
 
976
                                new_entry.name = self.final_name(trans_id)
 
977
                                parent = self.final_parent(trans_id)
 
978
                                parent_id = self.final_file_id(parent)
 
979
                                new_entry.parent_id = parent_id
 
980
 
 
981
                if trans_id in self._new_executability:
 
982
                    self._set_executability(path, new_entry, trans_id)
 
983
                if new_entry is not None:
 
984
                    if new_entry.file_id in inv:
 
985
                        old_path = inv.id2path(new_entry.file_id)
 
986
                    else:
 
987
                        old_path = None
 
988
                    inventory_delta.append((old_path, path,
 
989
                                            new_entry.file_id,
 
990
                                            new_entry))
 
991
        finally:
 
992
            child_pb.finished()
 
993
        return modified_paths
 
994
 
 
995
    def _set_executability(self, path, entry, trans_id):
906
996
        """Set the executability of versioned files """
 
997
        new_executability = self._new_executability[trans_id]
 
998
        entry.executable = new_executability
907
999
        if supports_executable():
908
 
            new_executability = self._new_executability[trans_id]
909
1000
            abspath = self._tree.abspath(path)
910
1001
            current_mode = os.stat(abspath).st_mode
911
1002
            if new_executability:
1048
1139
            to_executable = False
1049
1140
        return to_name, to_parent, to_kind, to_executable
1050
1141
 
1051
 
    def iter_changes(self):
1052
 
        """Produce output in the same format as Tree.iter_changes.
 
1142
    def _iter_changes(self):
 
1143
        """Produce output in the same format as Tree._iter_changes.
1053
1144
 
1054
1145
        Will produce nonsensical results if invoked while inventory/filesystem
1055
1146
        conflicts (as reported by TreeTransform.find_conflicts()) are present.
1110
1201
                   (from_executable, to_executable)))
1111
1202
        return iter(sorted(results, key=lambda x:x[1]))
1112
1203
 
1113
 
    def get_preview_tree(self):
1114
 
        """Return a tree representing the result of the transform.
1115
 
 
1116
 
        This tree only supports the subset of Tree functionality required
1117
 
        by show_diff_trees.  It must only be compared to tt._tree.
1118
 
        """
1119
 
        return _PreviewTree(self)
1120
 
 
1121
 
 
1122
 
class TreeTransform(TreeTransformBase):
1123
 
    """Represent a tree transformation.
1124
 
 
1125
 
    This object is designed to support incremental generation of the transform,
1126
 
    in any order.
1127
 
 
1128
 
    However, it gives optimum performance when parent directories are created
1129
 
    before their contents.  The transform is then able to put child files
1130
 
    directly in their parent directory, avoiding later renames.
1131
 
 
1132
 
    It is easy to produce malformed transforms, but they are generally
1133
 
    harmless.  Attempting to apply a malformed transform will cause an
1134
 
    exception to be raised before any modifications are made to the tree.
1135
 
 
1136
 
    Many kinds of malformed transforms can be corrected with the
1137
 
    resolve_conflicts function.  The remaining ones indicate programming error,
1138
 
    such as trying to create a file with no path.
1139
 
 
1140
 
    Two sets of file creation methods are supplied.  Convenience methods are:
1141
 
     * new_file
1142
 
     * new_directory
1143
 
     * new_symlink
1144
 
 
1145
 
    These are composed of the low-level methods:
1146
 
     * create_path
1147
 
     * create_file or create_directory or create_symlink
1148
 
     * version_file
1149
 
     * set_executability
1150
 
 
1151
 
    Transform/Transaction ids
1152
 
    -------------------------
1153
 
    trans_ids are temporary ids assigned to all files involved in a transform.
1154
 
    It's possible, even common, that not all files in the Tree have trans_ids.
1155
 
 
1156
 
    trans_ids are used because filenames and file_ids are not good enough
1157
 
    identifiers; filenames change, and not all files have file_ids.  File-ids
1158
 
    are also associated with trans-ids, so that moving a file moves its
1159
 
    file-id.
1160
 
 
1161
 
    trans_ids are only valid for the TreeTransform that generated them.
1162
 
 
1163
 
    Limbo
1164
 
    -----
1165
 
    Limbo is a temporary directory use to hold new versions of files.
1166
 
    Files are added to limbo by create_file, create_directory, create_symlink,
1167
 
    and their convenience variants (new_*).  Files may be removed from limbo
1168
 
    using cancel_creation.  Files are renamed from limbo into their final
1169
 
    location as part of TreeTransform.apply
1170
 
 
1171
 
    Limbo must be cleaned up, by either calling TreeTransform.apply or
1172
 
    calling TreeTransform.finalize.
1173
 
 
1174
 
    Files are placed into limbo inside their parent directories, where
1175
 
    possible.  This reduces subsequent renames, and makes operations involving
1176
 
    lots of files faster.  This optimization is only possible if the parent
1177
 
    directory is created *before* creating any of its children, so avoid
1178
 
    creating children before parents, where possible.
1179
 
 
1180
 
    Pending-deletion
1181
 
    ----------------
1182
 
    This temporary directory is used by _FileMover for storing files that are
1183
 
    about to be deleted.  In case of rollback, the files will be restored.
1184
 
    FileMover does not delete files until it is sure that a rollback will not
1185
 
    happen.
1186
 
    """
1187
 
    def __init__(self, tree, pb=DummyProgress()):
1188
 
        """Note: a tree_write lock is taken on the tree.
1189
 
 
1190
 
        Use TreeTransform.finalize() to release the lock (can be omitted if
1191
 
        TreeTransform.apply() called).
1192
 
        """
1193
 
        tree.lock_tree_write()
1194
 
 
1195
 
        try:
1196
 
            limbodir = urlutils.local_path_from_url(
1197
 
                tree._transport.abspath('limbo'))
1198
 
            try:
1199
 
                os.mkdir(limbodir)
1200
 
            except OSError, e:
1201
 
                if e.errno == errno.EEXIST:
1202
 
                    raise ExistingLimbo(limbodir)
1203
 
            deletiondir = urlutils.local_path_from_url(
1204
 
                tree._transport.abspath('pending-deletion'))
1205
 
            try:
1206
 
                os.mkdir(deletiondir)
1207
 
            except OSError, e:
1208
 
                if e.errno == errno.EEXIST:
1209
 
                    raise errors.ExistingPendingDeletion(deletiondir)
1210
 
        except:
1211
 
            tree.unlock()
1212
 
            raise
1213
 
 
1214
 
        TreeTransformBase.__init__(self, tree, limbodir, pb,
1215
 
                                   tree.case_sensitive)
1216
 
        self._deletiondir = deletiondir
1217
 
 
1218
 
    def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
1219
 
        """Apply all changes to the inventory and filesystem.
1220
 
 
1221
 
        If filesystem or inventory conflicts are present, MalformedTransform
1222
 
        will be thrown.
1223
 
 
1224
 
        If apply succeeds, finalize is not necessary.
1225
 
 
1226
 
        :param no_conflicts: if True, the caller guarantees there are no
1227
 
            conflicts, so no check is made.
1228
 
        :param precomputed_delta: An inventory delta to use instead of
1229
 
            calculating one.
1230
 
        :param _mover: Supply an alternate FileMover, for testing
1231
 
        """
1232
 
        if not no_conflicts:
1233
 
            conflicts = self.find_conflicts()
1234
 
            if len(conflicts) != 0:
1235
 
                raise MalformedTransform(conflicts=conflicts)
1236
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1237
 
        try:
1238
 
            if precomputed_delta is None:
1239
 
                child_pb.update('Apply phase', 0, 2)
1240
 
                inventory_delta = self._generate_inventory_delta()
1241
 
                offset = 1
1242
 
            else:
1243
 
                inventory_delta = precomputed_delta
1244
 
                offset = 0
1245
 
            if _mover is None:
1246
 
                mover = _FileMover()
1247
 
            else:
1248
 
                mover = _mover
1249
 
            try:
1250
 
                child_pb.update('Apply phase', 0 + offset, 2 + offset)
1251
 
                self._apply_removals(mover)
1252
 
                child_pb.update('Apply phase', 1 + offset, 2 + offset)
1253
 
                modified_paths = self._apply_insertions(mover)
1254
 
            except:
1255
 
                mover.rollback()
1256
 
                raise
1257
 
            else:
1258
 
                mover.apply_deletions()
1259
 
        finally:
1260
 
            child_pb.finished()
1261
 
        self._tree.apply_inventory_delta(inventory_delta)
1262
 
        self._done = True
1263
 
        self.finalize()
1264
 
        return _TransformResults(modified_paths, self.rename_count)
1265
 
 
1266
 
    def _generate_inventory_delta(self):
1267
 
        """Generate an inventory delta for the current transform."""
1268
 
        inventory_delta = []
1269
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1270
 
        new_paths = self._inventory_altered()
1271
 
        total_entries = len(new_paths) + len(self._removed_id)
1272
 
        try:
1273
 
            for num, trans_id in enumerate(self._removed_id):
1274
 
                if (num % 10) == 0:
1275
 
                    child_pb.update('removing file', num, total_entries)
1276
 
                if trans_id == self._new_root:
1277
 
                    file_id = self._tree.get_root_id()
1278
 
                else:
1279
 
                    file_id = self.tree_file_id(trans_id)
1280
 
                # File-id isn't really being deleted, just moved
1281
 
                if file_id in self._r_new_id:
1282
 
                    continue
1283
 
                path = self._tree_id_paths[trans_id]
1284
 
                inventory_delta.append((path, None, file_id, None))
1285
 
            new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1286
 
                                     new_paths)
1287
 
            entries = self._tree.iter_entries_by_dir(
1288
 
                new_path_file_ids.values())
1289
 
            old_paths = dict((e.file_id, p) for p, e in entries)
1290
 
            final_kinds = {}
1291
 
            for num, (path, trans_id) in enumerate(new_paths):
1292
 
                if (num % 10) == 0:
1293
 
                    child_pb.update('adding file',
1294
 
                                    num + len(self._removed_id), total_entries)
1295
 
                file_id = new_path_file_ids[trans_id]
1296
 
                if file_id is None:
1297
 
                    continue
1298
 
                needs_entry = False
1299
 
                try:
1300
 
                    kind = self.final_kind(trans_id)
1301
 
                except NoSuchFile:
1302
 
                    kind = self._tree.stored_kind(file_id)
1303
 
                parent_trans_id = self.final_parent(trans_id)
1304
 
                parent_file_id = new_path_file_ids.get(parent_trans_id)
1305
 
                if parent_file_id is None:
1306
 
                    parent_file_id = self.final_file_id(parent_trans_id)
1307
 
                if trans_id in self._new_reference_revision:
1308
 
                    new_entry = inventory.TreeReference(
1309
 
                        file_id,
1310
 
                        self._new_name[trans_id],
1311
 
                        self.final_file_id(self._new_parent[trans_id]),
1312
 
                        None, self._new_reference_revision[trans_id])
1313
 
                else:
1314
 
                    new_entry = inventory.make_entry(kind,
1315
 
                        self.final_name(trans_id),
1316
 
                        parent_file_id, file_id)
1317
 
                old_path = old_paths.get(new_entry.file_id)
1318
 
                new_executability = self._new_executability.get(trans_id)
1319
 
                if new_executability is not None:
1320
 
                    new_entry.executable = new_executability
1321
 
                inventory_delta.append(
1322
 
                    (old_path, path, new_entry.file_id, new_entry))
1323
 
        finally:
1324
 
            child_pb.finished()
1325
 
        return inventory_delta
1326
 
 
1327
 
    def _apply_removals(self, mover):
1328
 
        """Perform tree operations that remove directory/inventory names.
1329
 
 
1330
 
        That is, delete files that are to be deleted, and put any files that
1331
 
        need renaming into limbo.  This must be done in strict child-to-parent
1332
 
        order.
1333
 
 
1334
 
        If inventory_delta is None, no inventory delta generation is performed.
1335
 
        """
1336
 
        tree_paths = list(self._tree_path_ids.iteritems())
1337
 
        tree_paths.sort(reverse=True)
1338
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1339
 
        try:
1340
 
            for num, data in enumerate(tree_paths):
1341
 
                path, trans_id = data
1342
 
                child_pb.update('removing file', num, len(tree_paths))
1343
 
                full_path = self._tree.abspath(path)
1344
 
                if trans_id in self._removed_contents:
1345
 
                    mover.pre_delete(full_path, os.path.join(self._deletiondir,
1346
 
                                     trans_id))
1347
 
                elif trans_id in self._new_name or trans_id in \
1348
 
                    self._new_parent:
1349
 
                    try:
1350
 
                        mover.rename(full_path, self._limbo_name(trans_id))
1351
 
                    except OSError, e:
1352
 
                        if e.errno != errno.ENOENT:
1353
 
                            raise
1354
 
                    else:
1355
 
                        self.rename_count += 1
1356
 
        finally:
1357
 
            child_pb.finished()
1358
 
 
1359
 
    def _apply_insertions(self, mover):
1360
 
        """Perform tree operations that insert directory/inventory names.
1361
 
 
1362
 
        That is, create any files that need to be created, and restore from
1363
 
        limbo any files that needed renaming.  This must be done in strict
1364
 
        parent-to-child order.
1365
 
 
1366
 
        If inventory_delta is None, no inventory delta is calculated, and
1367
 
        no list of modified paths is returned.
1368
 
        """
1369
 
        new_paths = self.new_paths(filesystem_only=True)
1370
 
        modified_paths = []
1371
 
        new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1372
 
                                 new_paths)
1373
 
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1374
 
        try:
1375
 
            for num, (path, trans_id) in enumerate(new_paths):
1376
 
                if (num % 10) == 0:
1377
 
                    child_pb.update('adding file', num, len(new_paths))
1378
 
                full_path = self._tree.abspath(path)
1379
 
                if trans_id in self._needs_rename:
1380
 
                    try:
1381
 
                        mover.rename(self._limbo_name(trans_id), full_path)
1382
 
                    except OSError, e:
1383
 
                        # We may be renaming a dangling inventory id
1384
 
                        if e.errno != errno.ENOENT:
1385
 
                            raise
1386
 
                    else:
1387
 
                        self.rename_count += 1
1388
 
                if (trans_id in self._new_contents or
1389
 
                    self.path_changed(trans_id)):
1390
 
                    if trans_id in self._new_contents:
1391
 
                        modified_paths.append(full_path)
1392
 
                if trans_id in self._new_executability:
1393
 
                    self._set_executability(path, trans_id)
1394
 
        finally:
1395
 
            child_pb.finished()
1396
 
        self._new_contents.clear()
1397
 
        return modified_paths
1398
 
 
1399
 
 
1400
 
class TransformPreview(TreeTransformBase):
1401
 
    """A TreeTransform for generating preview trees.
1402
 
 
1403
 
    Unlike TreeTransform, this version works when the input tree is a
1404
 
    RevisionTree, rather than a WorkingTree.  As a result, it tends to ignore
1405
 
    unversioned files in the input tree.
1406
 
    """
1407
 
 
1408
 
    def __init__(self, tree, pb=DummyProgress(), case_sensitive=True):
1409
 
        tree.lock_read()
1410
 
        limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
1411
 
        TreeTransformBase.__init__(self, tree, limbodir, pb, case_sensitive)
1412
 
 
1413
 
    def canonical_path(self, path):
1414
 
        return path
1415
 
 
1416
 
    def tree_kind(self, trans_id):
1417
 
        path = self._tree_id_paths.get(trans_id)
1418
 
        if path is None:
1419
 
            raise NoSuchFile(None)
1420
 
        file_id = self._tree.path2id(path)
1421
 
        return self._tree.kind(file_id)
1422
 
 
1423
 
    def _set_mode(self, trans_id, mode_id, typefunc):
1424
 
        """Set the mode of new file contents.
1425
 
        The mode_id is the existing file to get the mode from (often the same
1426
 
        as trans_id).  The operation is only performed if there's a mode match
1427
 
        according to typefunc.
1428
 
        """
1429
 
        # is it ok to ignore this?  probably
1430
 
        pass
1431
 
 
1432
 
    def iter_tree_children(self, parent_id):
1433
 
        """Iterate through the entry's tree children, if any"""
1434
 
        try:
1435
 
            path = self._tree_id_paths[parent_id]
1436
 
        except KeyError:
1437
 
            return
1438
 
        file_id = self.tree_file_id(parent_id)
1439
 
        if file_id is None:
1440
 
            return
1441
 
        children = getattr(self._tree.inventory[file_id], 'children', {})
1442
 
        for child in children:
1443
 
            childpath = joinpath(path, child)
1444
 
            yield self.trans_id_tree_path(childpath)
1445
 
 
1446
 
 
1447
 
class _PreviewTree(tree.Tree):
1448
 
    """Partial implementation of Tree to support show_diff_trees"""
1449
 
 
1450
 
    def __init__(self, transform):
1451
 
        self._transform = transform
1452
 
        self._final_paths = FinalPaths(transform)
1453
 
        self.__by_parent = None
1454
 
        self._parent_ids = []
1455
 
 
1456
 
    def _changes(self, file_id):
1457
 
        for changes in self._transform.iter_changes():
1458
 
            if changes[0] == file_id:
1459
 
                return changes
1460
 
 
1461
 
    def _content_change(self, file_id):
1462
 
        """Return True if the content of this file changed"""
1463
 
        changes = self._changes(file_id)
1464
 
        # changes[2] is true if the file content changed.  See
1465
 
        # InterTree.iter_changes.
1466
 
        return (changes is not None and changes[2])
1467
 
 
1468
 
    def _get_repository(self):
1469
 
        repo = getattr(self._transform._tree, '_repository', None)
1470
 
        if repo is None:
1471
 
            repo = self._transform._tree.branch.repository
1472
 
        return repo
1473
 
 
1474
 
    def _iter_parent_trees(self):
1475
 
        for revision_id in self.get_parent_ids():
1476
 
            try:
1477
 
                yield self.revision_tree(revision_id)
1478
 
            except errors.NoSuchRevisionInTree:
1479
 
                yield self._get_repository().revision_tree(revision_id)
1480
 
 
1481
 
    def _get_file_revision(self, file_id, vf, tree_revision):
1482
 
        parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
1483
 
                       self._iter_parent_trees()]
1484
 
        vf.add_lines((file_id, tree_revision), parent_keys,
1485
 
                     self.get_file(file_id).readlines())
1486
 
        repo = self._get_repository()
1487
 
        base_vf = repo.texts
1488
 
        if base_vf not in vf.fallback_versionedfiles:
1489
 
            vf.fallback_versionedfiles.append(base_vf)
1490
 
        return tree_revision
1491
 
 
1492
 
    def _stat_limbo_file(self, file_id):
1493
 
        trans_id = self._transform.trans_id_file_id(file_id)
1494
 
        name = self._transform._limbo_name(trans_id)
1495
 
        return os.lstat(name)
1496
 
 
1497
 
    @property
1498
 
    def _by_parent(self):
1499
 
        if self.__by_parent is None:
1500
 
            self.__by_parent = self._transform.by_parent()
1501
 
        return self.__by_parent
1502
 
 
1503
 
    def lock_read(self):
1504
 
        # Perhaps in theory, this should lock the TreeTransform?
1505
 
        pass
1506
 
 
1507
 
    def unlock(self):
1508
 
        pass
1509
 
 
1510
 
    @property
1511
 
    def inventory(self):
1512
 
        """This Tree does not use inventory as its backing data."""
1513
 
        raise NotImplementedError(_PreviewTree.inventory)
1514
 
 
1515
 
    def get_root_id(self):
1516
 
        return self._transform.final_file_id(self._transform.root)
1517
 
 
1518
 
    def all_file_ids(self):
1519
 
        tree_ids = set(self._transform._tree.all_file_ids())
1520
 
        tree_ids.difference_update(self._transform.tree_file_id(t)
1521
 
                                   for t in self._transform._removed_id)
1522
 
        tree_ids.update(self._transform._new_id.values())
1523
 
        return tree_ids
1524
 
 
1525
 
    def __iter__(self):
1526
 
        return iter(self.all_file_ids())
1527
 
 
1528
 
    def paths2ids(self, specific_files, trees=None, require_versioned=False):
1529
 
        """See Tree.paths2ids"""
1530
 
        to_find = set(specific_files)
1531
 
        result = set()
1532
 
        for (file_id, paths, changed, versioned, parent, name, kind,
1533
 
             executable) in self._transform.iter_changes():
1534
 
            if paths[1] in to_find:
1535
 
                result.add(file_id)
1536
 
                to_find.remove(paths[1])
1537
 
        result.update(self._transform._tree.paths2ids(to_find,
1538
 
                      trees=[], require_versioned=require_versioned))
1539
 
        return result
1540
 
 
1541
 
    def _path2trans_id(self, path):
1542
 
        segments = splitpath(path)
1543
 
        cur_parent = self._transform.root
1544
 
        for cur_segment in segments:
1545
 
            for child in self._all_children(cur_parent):
1546
 
                if self._transform.final_name(child) == cur_segment:
1547
 
                    cur_parent = child
1548
 
                    break
1549
 
            else:
1550
 
                return None
1551
 
        return cur_parent
1552
 
 
1553
 
    def path2id(self, path):
1554
 
        return self._transform.final_file_id(self._path2trans_id(path))
1555
 
 
1556
 
    def id2path(self, file_id):
1557
 
        trans_id = self._transform.trans_id_file_id(file_id)
1558
 
        try:
1559
 
            return self._final_paths._determine_path(trans_id)
1560
 
        except NoFinalPath:
1561
 
            raise errors.NoSuchId(self, file_id)
1562
 
 
1563
 
    def _all_children(self, trans_id):
1564
 
        children = set(self._transform.iter_tree_children(trans_id))
1565
 
        # children in the _new_parent set are provided by _by_parent.
1566
 
        children.difference_update(self._transform._new_parent.keys())
1567
 
        children.update(self._by_parent.get(trans_id, []))
1568
 
        return children
1569
 
 
1570
 
    def _make_inv_entries(self, ordered_entries, specific_file_ids):
1571
 
        for trans_id, parent_file_id in ordered_entries:
1572
 
            file_id = self._transform.final_file_id(trans_id)
1573
 
            if file_id is None:
1574
 
                continue
1575
 
            if (specific_file_ids is not None
1576
 
                and file_id not in specific_file_ids):
1577
 
                continue
1578
 
            try:
1579
 
                kind = self._transform.final_kind(trans_id)
1580
 
            except NoSuchFile:
1581
 
                kind = self._transform._tree.stored_kind(file_id)
1582
 
            new_entry = inventory.make_entry(
1583
 
                kind,
1584
 
                self._transform.final_name(trans_id),
1585
 
                parent_file_id, file_id)
1586
 
            yield new_entry, trans_id
1587
 
 
1588
 
    def _list_files_by_dir(self):
1589
 
        todo = [ROOT_PARENT]
1590
 
        ordered_ids = []
1591
 
        while len(todo) > 0:
1592
 
            parent = todo.pop()
1593
 
            parent_file_id = self._transform.final_file_id(parent)
1594
 
            children = list(self._all_children(parent))
1595
 
            paths = dict(zip(children, self._final_paths.get_paths(children)))
1596
 
            children.sort(key=paths.get)
1597
 
            todo.extend(reversed(children))
1598
 
            for trans_id in children:
1599
 
                ordered_ids.append((trans_id, parent_file_id))
1600
 
        return ordered_ids
1601
 
 
1602
 
    def iter_entries_by_dir(self, specific_file_ids=None):
1603
 
        # This may not be a maximally efficient implementation, but it is
1604
 
        # reasonably straightforward.  An implementation that grafts the
1605
 
        # TreeTransform changes onto the tree's iter_entries_by_dir results
1606
 
        # might be more efficient, but requires tricky inferences about stack
1607
 
        # position.
1608
 
        ordered_ids = self._list_files_by_dir()
1609
 
        for entry, trans_id in self._make_inv_entries(ordered_ids,
1610
 
                                                      specific_file_ids):
1611
 
            yield unicode(self._final_paths.get_path(trans_id)), entry
1612
 
 
1613
 
    def list_files(self, include_root=False):
1614
 
        """See Tree.list_files."""
1615
 
        # XXX This should behave like WorkingTree.list_files, but is really
1616
 
        # more like RevisionTree.list_files.
1617
 
        for path, entry in self.iter_entries_by_dir():
1618
 
            if entry.name == '' and not include_root:
1619
 
                continue
1620
 
            yield path, 'V', entry.kind, entry.file_id, entry
1621
 
 
1622
 
    def kind(self, file_id):
1623
 
        trans_id = self._transform.trans_id_file_id(file_id)
1624
 
        return self._transform.final_kind(trans_id)
1625
 
 
1626
 
    def stored_kind(self, file_id):
1627
 
        trans_id = self._transform.trans_id_file_id(file_id)
1628
 
        try:
1629
 
            return self._transform._new_contents[trans_id]
1630
 
        except KeyError:
1631
 
            return self._transform._tree.stored_kind(file_id)
1632
 
 
1633
 
    def get_file_mtime(self, file_id, path=None):
1634
 
        """See Tree.get_file_mtime"""
1635
 
        if not self._content_change(file_id):
1636
 
            return self._transform._tree.get_file_mtime(file_id, path)
1637
 
        return self._stat_limbo_file(file_id).st_mtime
1638
 
 
1639
 
    def get_file_size(self, file_id):
1640
 
        """See Tree.get_file_size"""
1641
 
        if self.kind(file_id) == 'file':
1642
 
            return self._transform._tree.get_file_size(file_id)
1643
 
        else:
1644
 
            return None
1645
 
 
1646
 
    def get_file_sha1(self, file_id, path=None, stat_value=None):
1647
 
        return self._transform._tree.get_file_sha1(file_id)
1648
 
 
1649
 
    def is_executable(self, file_id, path=None):
1650
 
        trans_id = self._transform.trans_id_file_id(file_id)
1651
 
        try:
1652
 
            return self._transform._new_executability[trans_id]
1653
 
        except KeyError:
1654
 
            return self._transform._tree.is_executable(file_id, path)
1655
 
 
1656
 
    def path_content_summary(self, path):
1657
 
        trans_id = self._path2trans_id(path)
1658
 
        tt = self._transform
1659
 
        tree_path = tt._tree_id_paths.get(trans_id)
1660
 
        kind = tt._new_contents.get(trans_id)
1661
 
        if kind is None:
1662
 
            if tree_path is None or trans_id in tt._removed_contents:
1663
 
                return 'missing', None, None, None
1664
 
            summary = tt._tree.path_content_summary(tree_path)
1665
 
            kind, size, executable, link_or_sha1 = summary
1666
 
        else:
1667
 
            link_or_sha1 = None
1668
 
            limbo_name = tt._limbo_name(trans_id)
1669
 
            if trans_id in tt._new_reference_revision:
1670
 
                kind = 'tree-reference'
1671
 
            if kind == 'file':
1672
 
                statval = os.lstat(limbo_name)
1673
 
                size = statval.st_size
1674
 
                if not supports_executable():
1675
 
                    executable = None
1676
 
                else:
1677
 
                    executable = statval.st_mode & S_IEXEC
1678
 
            else:
1679
 
                size = None
1680
 
                executable = None
1681
 
            if kind == 'symlink':
1682
 
                link_or_sha1 = os.readlink(limbo_name)
1683
 
        if supports_executable():
1684
 
            executable = tt._new_executability.get(trans_id, executable)
1685
 
        return kind, size, executable, link_or_sha1
1686
 
 
1687
 
    def iter_changes(self, from_tree, include_unchanged=False,
1688
 
                      specific_files=None, pb=None, extra_trees=None,
1689
 
                      require_versioned=True, want_unversioned=False):
1690
 
        """See InterTree.iter_changes.
1691
 
 
1692
 
        This implementation does not support include_unchanged, specific_files,
1693
 
        or want_unversioned.  extra_trees, require_versioned, and pb are
1694
 
        ignored.
1695
 
        """
1696
 
        if from_tree is not self._transform._tree:
1697
 
            raise ValueError('from_tree must be transform source tree.')
1698
 
        if include_unchanged:
1699
 
            raise ValueError('include_unchanged is not supported')
1700
 
        if specific_files is not None:
1701
 
            raise ValueError('specific_files is not supported')
1702
 
        if want_unversioned:
1703
 
            raise ValueError('want_unversioned is not supported')
1704
 
        return self._transform.iter_changes()
1705
 
 
1706
 
    def get_file(self, file_id, path=None):
1707
 
        """See Tree.get_file"""
1708
 
        if not self._content_change(file_id):
1709
 
            return self._transform._tree.get_file(file_id, path)
1710
 
        trans_id = self._transform.trans_id_file_id(file_id)
1711
 
        name = self._transform._limbo_name(trans_id)
1712
 
        return open(name, 'rb')
1713
 
 
1714
 
    def get_file_text(self, file_id):
1715
 
        text_file = self.get_file(file_id)
1716
 
        try:
1717
 
            return text_file.read()
1718
 
        finally:
1719
 
            text_file.close()
1720
 
 
1721
 
    def annotate_iter(self, file_id,
1722
 
                      default_revision=_mod_revision.CURRENT_REVISION):
1723
 
        changes = self._changes(file_id)
1724
 
        if changes is None:
1725
 
            get_old = True
1726
 
        else:
1727
 
            changed_content, versioned, kind = (changes[2], changes[3],
1728
 
                                                changes[6])
1729
 
            if kind[1] is None:
1730
 
                return None
1731
 
            get_old = (kind[0] == 'file' and versioned[0])
1732
 
        if get_old:
1733
 
            old_annotation = self._transform._tree.annotate_iter(file_id,
1734
 
                default_revision=default_revision)
1735
 
        else:
1736
 
            old_annotation = []
1737
 
        if changes is None:
1738
 
            return old_annotation
1739
 
        if not changed_content:
1740
 
            return old_annotation
1741
 
        return annotate.reannotate([old_annotation],
1742
 
                                   self.get_file(file_id).readlines(),
1743
 
                                   default_revision)
1744
 
 
1745
 
    def get_symlink_target(self, file_id):
1746
 
        """See Tree.get_symlink_target"""
1747
 
        if not self._content_change(file_id):
1748
 
            return self._transform._tree.get_symlink_target(file_id)
1749
 
        trans_id = self._transform.trans_id_file_id(file_id)
1750
 
        name = self._transform._limbo_name(trans_id)
1751
 
        return os.readlink(name)
1752
 
 
1753
 
    def walkdirs(self, prefix=''):
1754
 
        pending = [self._transform.root]
1755
 
        while len(pending) > 0:
1756
 
            parent_id = pending.pop()
1757
 
            children = []
1758
 
            subdirs = []
1759
 
            prefix = prefix.rstrip('/')
1760
 
            parent_path = self._final_paths.get_path(parent_id)
1761
 
            parent_file_id = self._transform.final_file_id(parent_id)
1762
 
            for child_id in self._all_children(parent_id):
1763
 
                path_from_root = self._final_paths.get_path(child_id)
1764
 
                basename = self._transform.final_name(child_id)
1765
 
                file_id = self._transform.final_file_id(child_id)
1766
 
                try:
1767
 
                    kind = self._transform.final_kind(child_id)
1768
 
                    versioned_kind = kind
1769
 
                except NoSuchFile:
1770
 
                    kind = 'unknown'
1771
 
                    versioned_kind = self._transform._tree.stored_kind(file_id)
1772
 
                if versioned_kind == 'directory':
1773
 
                    subdirs.append(child_id)
1774
 
                children.append((path_from_root, basename, kind, None,
1775
 
                                 file_id, versioned_kind))
1776
 
            children.sort()
1777
 
            if parent_path.startswith(prefix):
1778
 
                yield (parent_path, parent_file_id), children
1779
 
            pending.extend(sorted(subdirs, key=self._final_paths.get_path,
1780
 
                                  reverse=True))
1781
 
 
1782
 
    def get_parent_ids(self):
1783
 
        return self._parent_ids
1784
 
 
1785
 
    def set_parent_ids(self, parent_ids):
1786
 
        self._parent_ids = parent_ids
1787
 
 
1788
 
    def get_revision_tree(self, revision_id):
1789
 
        return self._transform._tree.get_revision_tree(revision_id)
1790
 
 
1791
1204
 
1792
1205
def joinpath(parent, child):
1793
1206
    """Join tree-relative paths, handling the tree root specially"""
1824
1237
            self._known_paths[trans_id] = self._determine_path(trans_id)
1825
1238
        return self._known_paths[trans_id]
1826
1239
 
1827
 
    def get_paths(self, trans_ids):
1828
 
        return [(self.get_path(t), t) for t in trans_ids]
1829
 
 
1830
 
 
1831
 
 
1832
1240
def topology_sorted_ids(tree):
1833
1241
    """Determine the topological order of the ids in a tree"""
1834
1242
    file_ids = list(tree)
1836
1244
    return file_ids
1837
1245
 
1838
1246
 
1839
 
def build_tree(tree, wt, accelerator_tree=None, hardlink=False,
1840
 
               delta_from_tree=False):
 
1247
def build_tree(tree, wt):
1841
1248
    """Create working tree for a branch, using a TreeTransform.
1842
1249
    
1843
1250
    This function should be used on empty trees, having a tree root at most.
1850
1257
    - Otherwise, if the content on disk matches the content we are building,
1851
1258
      it is silently replaced.
1852
1259
    - Otherwise, conflict resolution will move the old file to 'oldname.moved'.
1853
 
 
1854
 
    :param tree: The tree to convert wt into a copy of
1855
 
    :param wt: The working tree that files will be placed into
1856
 
    :param accelerator_tree: A tree which can be used for retrieving file
1857
 
        contents more quickly than tree itself, i.e. a workingtree.  tree
1858
 
        will be used for cases where accelerator_tree's content is different.
1859
 
    :param hardlink: If true, hard-link files to accelerator_tree, where
1860
 
        possible.  accelerator_tree must implement abspath, i.e. be a
1861
 
        working tree.
1862
 
    :param delta_from_tree: If true, build_tree may use the input Tree to
1863
 
        generate the inventory delta.
1864
1260
    """
1865
1261
    wt.lock_tree_write()
1866
1262
    try:
1867
1263
        tree.lock_read()
1868
1264
        try:
1869
 
            if accelerator_tree is not None:
1870
 
                accelerator_tree.lock_read()
1871
 
            try:
1872
 
                return _build_tree(tree, wt, accelerator_tree, hardlink,
1873
 
                                   delta_from_tree)
1874
 
            finally:
1875
 
                if accelerator_tree is not None:
1876
 
                    accelerator_tree.unlock()
 
1265
            return _build_tree(tree, wt)
1877
1266
        finally:
1878
1267
            tree.unlock()
1879
1268
    finally:
1880
1269
        wt.unlock()
1881
1270
 
1882
 
 
1883
 
def _build_tree(tree, wt, accelerator_tree, hardlink, delta_from_tree):
 
1271
def _build_tree(tree, wt):
1884
1272
    """See build_tree."""
1885
 
    for num, _unused in enumerate(wt.all_file_ids()):
1886
 
        if num > 0:  # more than just a root
1887
 
            raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
1888
 
    existing_files = set()
1889
 
    for dir, files in wt.walkdirs():
1890
 
        existing_files.update(f[0] for f in files)
 
1273
    if len(wt.inventory) > 1:  # more than just a root
 
1274
        raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
1891
1275
    file_trans_id = {}
1892
1276
    top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1893
1277
    pp = ProgressPhase("Build phase", 2, top_pb)
1899
1283
        # is set within the tree, nor setting the root and thus
1900
1284
        # marking the tree as dirty, because we use two different
1901
1285
        # idioms here: tree interfaces and inventory interfaces.
1902
 
        if wt.get_root_id() != tree.get_root_id():
1903
 
            wt.set_root_id(tree.get_root_id())
 
1286
        if wt.path2id('') != tree.inventory.root.file_id:
 
1287
            wt.set_root_id(tree.inventory.root.file_id)
1904
1288
            wt.flush()
1905
1289
    tt = TreeTransform(wt)
1906
1290
    divert = set()
1911
1295
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1912
1296
        try:
1913
1297
            deferred_contents = []
1914
 
            num = 0
1915
 
            total = len(tree.inventory)
1916
 
            if delta_from_tree:
1917
 
                precomputed_delta = []
1918
 
            else:
1919
 
                precomputed_delta = None
1920
1298
            for num, (tree_path, entry) in \
1921
1299
                enumerate(tree.inventory.iter_entries_by_dir()):
1922
 
                pb.update("Building tree", num - len(deferred_contents), total)
 
1300
                pb.update("Building tree", num - len(deferred_contents),
 
1301
                          len(tree.inventory))
1923
1302
                if entry.parent_id is None:
1924
1303
                    continue
1925
1304
                reparent = False
1926
1305
                file_id = entry.file_id
1927
 
                if delta_from_tree:
1928
 
                    precomputed_delta.append((None, tree_path, file_id, entry))
1929
 
                if tree_path in existing_files:
1930
 
                    target_path = wt.abspath(tree_path)
 
1306
                target_path = wt.abspath(tree_path)
 
1307
                try:
1931
1308
                    kind = file_kind(target_path)
 
1309
                except NoSuchFile:
 
1310
                    pass
 
1311
                else:
1932
1312
                    if kind == "directory":
1933
1313
                        try:
1934
1314
                            bzrdir.BzrDir.open(target_path)
1942
1322
                        tt.delete_contents(tt.trans_id_tree_path(tree_path))
1943
1323
                        if kind == 'directory':
1944
1324
                            reparent = True
 
1325
                if entry.parent_id not in file_trans_id:
 
1326
                    raise AssertionError(
 
1327
                        'entry %s parent id %r is not in file_trans_id %r'
 
1328
                        % (entry, entry.parent_id, file_trans_id))
1945
1329
                parent_id = file_trans_id[entry.parent_id]
1946
1330
                if entry.kind == 'file':
1947
1331
                    # We *almost* replicate new_by_entry, so that we can defer
1948
1332
                    # getting the file text, and get them all at once.
1949
1333
                    trans_id = tt.create_path(entry.name, parent_id)
1950
1334
                    file_trans_id[file_id] = trans_id
1951
 
                    tt.version_file(file_id, trans_id)
1952
 
                    executable = tree.is_executable(file_id, tree_path)
1953
 
                    if executable:
 
1335
                    tt.version_file(entry.file_id, trans_id)
 
1336
                    executable = tree.is_executable(entry.file_id, tree_path)
 
1337
                    if executable is not None:
1954
1338
                        tt.set_executability(executable, trans_id)
1955
 
                    deferred_contents.append((file_id, trans_id))
 
1339
                    deferred_contents.append((entry.file_id, trans_id))
1956
1340
                else:
1957
1341
                    file_trans_id[file_id] = new_by_entry(tt, entry, parent_id,
1958
1342
                                                          tree)
1960
1344
                    new_trans_id = file_trans_id[file_id]
1961
1345
                    old_parent = tt.trans_id_tree_path(tree_path)
1962
1346
                    _reparent_children(tt, old_parent, new_trans_id)
1963
 
            offset = num + 1 - len(deferred_contents)
1964
 
            _create_files(tt, tree, deferred_contents, pb, offset,
1965
 
                          accelerator_tree, hardlink)
 
1347
            for num, (trans_id, bytes) in enumerate(
 
1348
                tree.iter_files_bytes(deferred_contents)):
 
1349
                tt.create_file(bytes, trans_id)
 
1350
                pb.update('Adding file contents',
 
1351
                          (num + len(tree.inventory) - len(deferred_contents)),
 
1352
                          len(tree.inventory))
1966
1353
        finally:
1967
1354
            pb.finished()
1968
1355
        pp.next_phase()
1969
1356
        divert_trans = set(file_trans_id[f] for f in divert)
1970
1357
        resolver = lambda t, c: resolve_checkout(t, c, divert_trans)
1971
1358
        raw_conflicts = resolve_conflicts(tt, pass_func=resolver)
1972
 
        if len(raw_conflicts) > 0:
1973
 
            precomputed_delta = None
1974
1359
        conflicts = cook_conflicts(raw_conflicts, tt)
1975
1360
        for conflict in conflicts:
1976
1361
            warning(conflict)
1978
1363
            wt.add_conflicts(conflicts)
1979
1364
        except errors.UnsupportedOperation:
1980
1365
            pass
1981
 
        result = tt.apply(no_conflicts=True,
1982
 
                          precomputed_delta=precomputed_delta)
 
1366
        result = tt.apply()
1983
1367
    finally:
1984
1368
        tt.finalize()
1985
1369
        top_pb.finished()
1986
1370
    return result
1987
1371
 
1988
1372
 
1989
 
def _create_files(tt, tree, desired_files, pb, offset, accelerator_tree,
1990
 
                  hardlink):
1991
 
    total = len(desired_files) + offset
1992
 
    if accelerator_tree is None:
1993
 
        new_desired_files = desired_files
1994
 
    else:
1995
 
        iter = accelerator_tree.iter_changes(tree, include_unchanged=True)
1996
 
        unchanged = dict((f, p[1]) for (f, p, c, v, d, n, k, e)
1997
 
                         in iter if not (c or e[0] != e[1]))
1998
 
        new_desired_files = []
1999
 
        count = 0
2000
 
        for file_id, trans_id in desired_files:
2001
 
            accelerator_path = unchanged.get(file_id)
2002
 
            if accelerator_path is None:
2003
 
                new_desired_files.append((file_id, trans_id))
2004
 
                continue
2005
 
            pb.update('Adding file contents', count + offset, total)
2006
 
            if hardlink:
2007
 
                tt.create_hardlink(accelerator_tree.abspath(accelerator_path),
2008
 
                                   trans_id)
2009
 
            else:
2010
 
                contents = accelerator_tree.get_file(file_id, accelerator_path)
2011
 
                try:
2012
 
                    tt.create_file(contents, trans_id)
2013
 
                finally:
2014
 
                    contents.close()
2015
 
            count += 1
2016
 
        offset += count
2017
 
    for count, (trans_id, contents) in enumerate(tree.iter_files_bytes(
2018
 
                                                 new_desired_files)):
2019
 
        tt.create_file(contents, trans_id)
2020
 
        pb.update('Adding file contents', count + offset, total)
2021
 
 
2022
 
 
2023
1373
def _reparent_children(tt, old_parent, new_parent):
2024
1374
    for child in tt.iter_tree_children(old_parent):
2025
1375
        tt.adjust_path(tt.final_name(child), new_parent, child)
2026
1376
 
2027
 
def _reparent_transform_children(tt, old_parent, new_parent):
2028
 
    by_parent = tt.by_parent()
2029
 
    for child in by_parent[old_parent]:
2030
 
        tt.adjust_path(tt.final_name(child), new_parent, child)
2031
 
    return by_parent[old_parent]
2032
1377
 
2033
1378
def _content_match(tree, entry, file_id, kind, target_path):
2034
1379
    if entry.kind != kind:
2048
1393
    new_conflicts = set()
2049
1394
    for c_type, conflict in ((c[0], c) for c in conflicts):
2050
1395
        # Anything but a 'duplicate' would indicate programmer error
2051
 
        if c_type != 'duplicate':
2052
 
            raise AssertionError(c_type)
 
1396
        assert c_type == 'duplicate', c_type
2053
1397
        # Now figure out which is new and which is old
2054
1398
        if tt.new_contents(conflict[1]):
2055
1399
            new_file = conflict[1]
2094
1438
    else:
2095
1439
        raise errors.BadFileKindError(name, kind)
2096
1440
 
2097
 
 
2098
1441
def create_by_entry(tt, entry, tree, trans_id, lines=None, mode_id=None):
2099
1442
    """Create new file contents according to an inventory entry."""
2100
1443
    if entry.kind == "file":
2106
1449
    elif entry.kind == "directory":
2107
1450
        tt.create_directory(trans_id)
2108
1451
 
2109
 
 
2110
1452
def create_entry_executability(tt, entry, trans_id):
2111
1453
    """Set the executability of a trans_id according to an inventory entry"""
2112
1454
    if entry.kind == "file":
2113
1455
        tt.set_executability(entry.executable, trans_id)
2114
1456
 
2115
1457
 
 
1458
@deprecated_function(zero_fifteen)
 
1459
def find_interesting(working_tree, target_tree, filenames):
 
1460
    """Find the ids corresponding to specified filenames.
 
1461
    
 
1462
    Deprecated: Please use tree1.paths2ids(filenames, [tree2]).
 
1463
    """
 
1464
    working_tree.lock_read()
 
1465
    try:
 
1466
        target_tree.lock_read()
 
1467
        try:
 
1468
            return working_tree.paths2ids(filenames, [target_tree])
 
1469
        finally:
 
1470
            target_tree.unlock()
 
1471
    finally:
 
1472
        working_tree.unlock()
 
1473
 
 
1474
 
 
1475
@deprecated_function(zero_ninety)
 
1476
def change_entry(tt, file_id, working_tree, target_tree, 
 
1477
                 trans_id_file_id, backups, trans_id, by_parent):
 
1478
    """Replace a file_id's contents with those from a target tree."""
 
1479
    if file_id is None and target_tree is None:
 
1480
        # skip the logic altogether in the deprecation test
 
1481
        return
 
1482
    e_trans_id = trans_id_file_id(file_id)
 
1483
    entry = target_tree.inventory[file_id]
 
1484
    has_contents, contents_mod, meta_mod, = _entry_changes(file_id, entry, 
 
1485
                                                           working_tree)
 
1486
    if contents_mod:
 
1487
        mode_id = e_trans_id
 
1488
        if has_contents:
 
1489
            if not backups:
 
1490
                tt.delete_contents(e_trans_id)
 
1491
            else:
 
1492
                parent_trans_id = trans_id_file_id(entry.parent_id)
 
1493
                backup_name = get_backup_name(entry, by_parent,
 
1494
                                              parent_trans_id, tt)
 
1495
                tt.adjust_path(backup_name, parent_trans_id, e_trans_id)
 
1496
                tt.unversion_file(e_trans_id)
 
1497
                e_trans_id = tt.create_path(entry.name, parent_trans_id)
 
1498
                tt.version_file(file_id, e_trans_id)
 
1499
                trans_id[file_id] = e_trans_id
 
1500
        create_by_entry(tt, entry, target_tree, e_trans_id, mode_id=mode_id)
 
1501
        create_entry_executability(tt, entry, e_trans_id)
 
1502
 
 
1503
    elif meta_mod:
 
1504
        tt.set_executability(entry.executable, e_trans_id)
 
1505
    if tt.final_name(e_trans_id) != entry.name:
 
1506
        adjust_path  = True
 
1507
    else:
 
1508
        parent_id = tt.final_parent(e_trans_id)
 
1509
        parent_file_id = tt.final_file_id(parent_id)
 
1510
        if parent_file_id != entry.parent_id:
 
1511
            adjust_path = True
 
1512
        else:
 
1513
            adjust_path = False
 
1514
    if adjust_path:
 
1515
        parent_trans_id = trans_id_file_id(entry.parent_id)
 
1516
        tt.adjust_path(entry.name, parent_trans_id, e_trans_id)
 
1517
 
 
1518
 
2116
1519
def get_backup_name(entry, by_parent, parent_trans_id, tt):
2117
1520
    return _get_backup_name(entry.name, by_parent, parent_trans_id, tt)
2118
1521
 
2163
1566
    tt = TreeTransform(working_tree, pb)
2164
1567
    try:
2165
1568
        pp = ProgressPhase("Revert phase", 3, pb)
2166
 
        conflicts, merge_modified = _prepare_revert_transform(
2167
 
            working_tree, target_tree, tt, filenames, backups, pp)
 
1569
        pp.next_phase()
 
1570
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1571
        try:
 
1572
            merge_modified = _alter_files(working_tree, target_tree, tt,
 
1573
                                          child_pb, filenames, backups)
 
1574
        finally:
 
1575
            child_pb.finished()
 
1576
        pp.next_phase()
 
1577
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1578
        try:
 
1579
            raw_conflicts = resolve_conflicts(tt, child_pb)
 
1580
        finally:
 
1581
            child_pb.finished()
 
1582
        conflicts = cook_conflicts(raw_conflicts, tt)
2168
1583
        if change_reporter:
2169
1584
            change_reporter = delta._ChangeReporter(
2170
1585
                unversioned_filter=working_tree.is_ignored)
2171
 
            delta.report_changes(tt.iter_changes(), change_reporter)
 
1586
            delta.report_changes(tt._iter_changes(), change_reporter)
2172
1587
        for conflict in conflicts:
2173
1588
            warning(conflict)
2174
1589
        pp.next_phase()
2181
1596
    return conflicts
2182
1597
 
2183
1598
 
2184
 
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
2185
 
                              backups, pp, basis_tree=None,
2186
 
                              merge_modified=None):
2187
 
    pp.next_phase()
2188
 
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2189
 
    try:
2190
 
        if merge_modified is None:
2191
 
            merge_modified = working_tree.merge_modified()
2192
 
        merge_modified = _alter_files(working_tree, target_tree, tt,
2193
 
                                      child_pb, filenames, backups,
2194
 
                                      merge_modified, basis_tree)
2195
 
    finally:
2196
 
        child_pb.finished()
2197
 
    pp.next_phase()
2198
 
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2199
 
    try:
2200
 
        raw_conflicts = resolve_conflicts(tt, child_pb,
2201
 
            lambda t, c: conflict_pass(t, c, target_tree))
2202
 
    finally:
2203
 
        child_pb.finished()
2204
 
    conflicts = cook_conflicts(raw_conflicts, tt)
2205
 
    return conflicts, merge_modified
2206
 
 
2207
 
 
2208
1599
def _alter_files(working_tree, target_tree, tt, pb, specific_files,
2209
 
                 backups, merge_modified, basis_tree=None):
2210
 
    if basis_tree is not None:
2211
 
        basis_tree.lock_read()
2212
 
    change_list = target_tree.iter_changes(working_tree,
 
1600
                 backups):
 
1601
    merge_modified = working_tree.merge_modified()
 
1602
    change_list = target_tree._iter_changes(working_tree,
2213
1603
        specific_files=specific_files, pb=pb)
2214
 
    if target_tree.get_root_id() is None:
 
1604
    if target_tree.inventory.root is None:
2215
1605
        skip_root = True
2216
1606
    else:
2217
1607
        skip_root = False
 
1608
    basis_tree = None
2218
1609
    try:
2219
1610
        deferred_files = []
2220
1611
        for id_num, (file_id, path, changed_content, versioned, parent, name,
2256
1647
                        # contents
2257
1648
                        mode_id = trans_id
2258
1649
                        trans_id = new_trans_id
2259
 
                if kind[1] in ('directory', 'tree-reference'):
 
1650
                if kind[1] == 'directory':
2260
1651
                    tt.create_directory(trans_id)
2261
 
                    if kind[1] == 'tree-reference':
2262
 
                        revision = target_tree.get_reference_revision(file_id,
2263
 
                                                                      path[1])
2264
 
                        tt.set_tree_reference(revision, trans_id)
2265
1652
                elif kind[1] == 'symlink':
2266
1653
                    tt.create_symlink(target_tree.get_symlink_target(file_id),
2267
1654
                                      trans_id)
2281
1668
                    # preserve the execute bit when backing up
2282
1669
                    if keep_content and executable[0] == executable[1]:
2283
1670
                        tt.set_executability(executable[1], trans_id)
2284
 
                elif kind[1] is not None:
2285
 
                    raise AssertionError(kind[1])
 
1671
                else:
 
1672
                    assert kind[1] is None
2286
1673
            if versioned == (False, True):
2287
1674
                tt.version_file(file_id, trans_id)
2288
1675
            if versioned == (True, False):
2289
1676
                tt.unversion_file(trans_id)
2290
 
            if (name[1] is not None and
 
1677
            if (name[1] is not None and 
2291
1678
                (name[0] != name[1] or parent[0] != parent[1])):
2292
 
                if name[1] == '' and parent[1] is None:
2293
 
                    parent_trans = ROOT_PARENT
2294
 
                else:
2295
 
                    parent_trans = tt.trans_id_file_id(parent[1])
2296
 
                tt.adjust_path(name[1], parent_trans, trans_id)
 
1679
                tt.adjust_path(
 
1680
                    name[1], tt.trans_id_file_id(parent[1]), trans_id)
2297
1681
            if executable[0] != executable[1] and kind[1] == "file":
2298
1682
                tt.set_executability(executable[1], trans_id)
2299
1683
        for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
2337
1721
                               conflict[1], conflict[2], ))
2338
1722
        elif c_type == 'duplicate':
2339
1723
            # files that were renamed take precedence
 
1724
            new_name = tt.final_name(conflict[1])+'.moved'
2340
1725
            final_parent = tt.final_parent(conflict[1])
2341
1726
            if tt.path_changed(conflict[1]):
2342
 
                existing_file, new_file = conflict[2], conflict[1]
 
1727
                tt.adjust_path(new_name, final_parent, conflict[2])
 
1728
                new_conflicts.add((c_type, 'Moved existing file to', 
 
1729
                                   conflict[2], conflict[1]))
2343
1730
            else:
2344
 
                existing_file, new_file = conflict[1], conflict[2]
2345
 
            new_name = tt.final_name(existing_file)+'.moved'
2346
 
            tt.adjust_path(new_name, final_parent, existing_file)
2347
 
            new_conflicts.add((c_type, 'Moved existing file to', 
2348
 
                               existing_file, new_file))
 
1731
                tt.adjust_path(new_name, final_parent, conflict[1])
 
1732
                new_conflicts.add((c_type, 'Moved existing file to', 
 
1733
                                  conflict[1], conflict[2]))
2349
1734
        elif c_type == 'parent loop':
2350
1735
            # break the loop by undoing one of the ops that caused the loop
2351
1736
            cur = conflict[1]
2362
1747
                new_conflicts.add(('deleting parent', 'Not deleting', 
2363
1748
                                   trans_id))
2364
1749
            except KeyError:
2365
 
                create = True
 
1750
                tt.create_directory(trans_id)
 
1751
                new_conflicts.add((c_type, 'Created directory', trans_id))
2366
1752
                try:
2367
1753
                    tt.final_name(trans_id)
2368
1754
                except NoFinalPath:
2369
 
                    if path_tree is not None:
2370
 
                        file_id = tt.final_file_id(trans_id)
2371
 
                        if file_id is None:
2372
 
                            file_id = tt.inactive_file_id(trans_id)
2373
 
                        entry = path_tree.inventory[file_id]
2374
 
                        # special-case the other tree root (move its
2375
 
                        # children to current root)
2376
 
                        if entry.parent_id is None:
2377
 
                            create=False
2378
 
                            moved = _reparent_transform_children(
2379
 
                                tt, trans_id, tt.root)
2380
 
                            for child in moved:
2381
 
                                new_conflicts.add((c_type, 'Moved to root',
2382
 
                                                   child))
2383
 
                        else:
2384
 
                            parent_trans_id = tt.trans_id_file_id(
2385
 
                                entry.parent_id)
2386
 
                            tt.adjust_path(entry.name, parent_trans_id,
2387
 
                                           trans_id)
2388
 
                if create:
2389
 
                    tt.create_directory(trans_id)
2390
 
                    new_conflicts.add((c_type, 'Created directory', trans_id))
 
1755
                    file_id = tt.final_file_id(trans_id)
 
1756
                    entry = path_tree.inventory[file_id]
 
1757
                    parent_trans_id = tt.trans_id_file_id(entry.parent_id)
 
1758
                    tt.adjust_path(entry.name, parent_trans_id, trans_id)
2391
1759
        elif c_type == 'unversioned parent':
2392
 
            file_id = tt.inactive_file_id(conflict[1])
2393
 
            # special-case the other tree root (move its children instead)
2394
 
            if path_tree and file_id in path_tree:
2395
 
                if path_tree.inventory[file_id].parent_id is None:
2396
 
                    continue
2397
 
            tt.version_file(file_id, conflict[1])
 
1760
            tt.version_file(tt.inactive_file_id(conflict[1]), conflict[1])
2398
1761
            new_conflicts.add((c_type, 'Versioned directory', conflict[1]))
2399
 
        elif c_type == 'non-directory parent':
2400
 
            parent_id = conflict[1]
2401
 
            parent_parent = tt.final_parent(parent_id)
2402
 
            parent_name = tt.final_name(parent_id)
2403
 
            parent_file_id = tt.final_file_id(parent_id)
2404
 
            new_parent_id = tt.new_directory(parent_name + '.new',
2405
 
                parent_parent, parent_file_id)
2406
 
            _reparent_transform_children(tt, parent_id, new_parent_id)
2407
 
            if parent_file_id is not None:
2408
 
                tt.unversion_file(parent_id)
2409
 
            new_conflicts.add((c_type, 'Created directory', new_parent_id))
2410
 
        elif c_type == 'versioning no contents':
2411
 
            tt.cancel_versioning(conflict[1])
2412
1762
    return new_conflicts
2413
1763
 
2414
1764
 
2449
1799
 
2450
1800
    def rename(self, from_, to):
2451
1801
        """Rename a file from one path to another.  Functions like os.rename"""
2452
 
        try:
2453
 
            os.rename(from_, to)
2454
 
        except OSError, e:
2455
 
            if e.errno in (errno.EEXIST, errno.ENOTEMPTY):
2456
 
                raise errors.FileExists(to, str(e))
2457
 
            raise
 
1802
        os.rename(from_, to)
2458
1803
        self.past_renames.append((from_, to))
2459
1804
 
2460
1805
    def pre_delete(self, from_, to):