~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: 2010-05-28 00:25:32 UTC
  • mfrom: (5264.1.2 command-help-bug-177500)
  • Revision ID: pqm@pqm.ubuntu.com-20100528002532-9bzj1fajyxckd1rg
(lifeless) Stop raising at runtime when a command has no help,
 instead have a test in the test suite that checks all known command objects.
 (Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
19
19
from stat import S_ISREG, S_IEXEC
20
20
import time
21
21
 
22
 
from bzrlib import (
23
 
    errors,
24
 
    lazy_import,
25
 
    registry,
26
 
    trace,
27
 
    tree,
28
 
    )
29
 
lazy_import.lazy_import(globals(), """
 
22
from bzrlib.lazy_import import lazy_import
 
23
lazy_import(globals(), """
30
24
from bzrlib import (
31
25
    annotate,
32
26
    bencode,
33
27
    bzrdir,
34
28
    commit,
35
 
    conflicts,
36
29
    delta,
37
30
    errors,
38
31
    inventory,
40
33
    osutils,
41
34
    revision as _mod_revision,
42
35
    ui,
43
 
    urlutils,
44
36
    )
45
37
""")
46
38
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
48
40
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
49
41
                           UnableCreateSymlink)
50
42
from bzrlib.filters import filtered_output_bytes, ContentFilterContext
 
43
from bzrlib.inventory import InventoryEntry
51
44
from bzrlib.osutils import (
52
45
    delete_any,
53
46
    file_kind,
54
47
    has_symlinks,
 
48
    lexists,
55
49
    pathjoin,
56
50
    sha_file,
57
51
    splitpath,
58
52
    supports_executable,
59
 
    )
 
53
)
60
54
from bzrlib.progress import ProgressPhase
61
55
from bzrlib.symbol_versioning import (
62
 
    deprecated_function,
63
 
    deprecated_in,
64
 
    deprecated_method,
65
 
    )
 
56
        deprecated_function,
 
57
        deprecated_in,
 
58
        )
 
59
from bzrlib.trace import mutter, warning
 
60
from bzrlib import tree
 
61
import bzrlib.ui
 
62
import bzrlib.urlutils as urlutils
66
63
 
67
64
 
68
65
ROOT_PARENT = "root-parent"
69
66
 
 
67
 
70
68
def unique_add(map, key, value):
71
69
    if key in map:
72
70
        raise DuplicateKey(key=key)
73
71
    map[key] = value
74
72
 
75
73
 
76
 
 
77
74
class _TransformResults(object):
78
75
    def __init__(self, modified_paths, rename_count):
79
76
        object.__init__(self)
103
100
        self._new_parent = {}
104
101
        # mapping of trans_id with new contents -> new file_kind
105
102
        self._new_contents = {}
106
 
        # mapping of trans_id => (sha1 of content, stat_value)
107
 
        self._observed_sha1s = {}
108
103
        # Set of trans_ids whose contents will be removed
109
104
        self._removed_contents = set()
110
105
        # Mapping of trans_id -> new execute-bit value
129
124
            self._new_root = self.trans_id_tree_file_id(root_id)
130
125
        else:
131
126
            self._new_root = None
132
 
        # Indicator of whether the transform has been applied
 
127
        # Indictor of whether the transform has been applied
133
128
        self._done = False
134
129
        # A progress bar
135
130
        self._pb = pb
138
133
        # A counter of how many files have been renamed
139
134
        self.rename_count = 0
140
135
 
141
 
    def __enter__(self):
142
 
        """Support Context Manager API."""
143
 
        return self
144
 
 
145
 
    def __exit__(self, exc_type, exc_val, exc_tb):
146
 
        """Support Context Manager API."""
147
 
        self.finalize()
148
 
 
149
136
    def finalize(self):
150
137
        """Release the working tree lock, if held.
151
138
 
226
213
        This means that the old root trans-id becomes obsolete, so it is
227
214
        recommended only to invoke this after the root trans-id has become
228
215
        irrelevant.
229
 
 
230
216
        """
231
217
        new_roots = [k for k, v in self._new_parent.iteritems() if v is
232
218
                     ROOT_PARENT]
233
219
        if len(new_roots) < 1:
234
 
            if self.final_kind(self.root) is None:
235
 
                self.cancel_deletion(self.root)
236
 
            if self.final_file_id(self.root) is None:
237
 
                self.version_file(self.tree_file_id(self.root),
238
 
                                     self.root)
239
220
            return
240
221
        if len(new_roots) != 1:
241
222
            raise ValueError('A tree cannot have two roots!')
243
224
            self._new_root = new_roots[0]
244
225
            return
245
226
        old_new_root = new_roots[0]
 
227
        # TODO: What to do if a old_new_root is present, but self._new_root is
 
228
        #       not listed as being removed? This code explicitly unversions
 
229
        #       the old root and versions it with the new file_id. Though that
 
230
        #       seems like an incomplete delta
 
231
 
246
232
        # unversion the new root's directory.
247
 
        if self.final_kind(self._new_root) is None:
248
 
            file_id = self.final_file_id(old_new_root)
249
 
        else:
250
 
            file_id = self.final_file_id(self._new_root)
 
233
        file_id = self.final_file_id(old_new_root)
251
234
        if old_new_root in self._new_id:
252
235
            self.cancel_versioning(old_new_root)
253
236
        else:
257
240
        if (self.tree_file_id(self._new_root) is not None and
258
241
            self._new_root not in self._removed_id):
259
242
            self.unversion_file(self._new_root)
260
 
        if file_id is not None:
261
 
            self.version_file(file_id, self._new_root)
 
243
        self.version_file(file_id, self._new_root)
262
244
 
263
245
        # Now move children of new root into old root directory.
264
246
        # Ensure all children are registered with the transaction, but don't
333
315
 
334
316
    def delete_contents(self, trans_id):
335
317
        """Schedule the contents of a path entry for deletion"""
336
 
        kind = self.tree_kind(trans_id)
337
 
        if kind is not None:
338
 
            self._removed_contents.add(trans_id)
 
318
        # Ensure that the object exists in the WorkingTree, this will raise an
 
319
        # exception if there is a problem
 
320
        self.tree_kind(trans_id)
 
321
        self._removed_contents.add(trans_id)
339
322
 
340
323
    def cancel_deletion(self, trans_id):
341
324
        """Cancel a scheduled deletion"""
398
381
        return sorted(FinalPaths(self).get_paths(new_ids))
399
382
 
400
383
    def _inventory_altered(self):
401
 
        """Determine which trans_ids need new Inventory entries.
402
 
 
403
 
        An new entry is needed when anything that would be reflected by an
404
 
        inventory entry changes, including file name, file_id, parent file_id,
405
 
        file kind, and the execute bit.
406
 
 
407
 
        Some care is taken to return entries with real changes, not cases
408
 
        where the value is deleted and then restored to its original value,
409
 
        but some actually unchanged values may be returned.
410
 
 
411
 
        :returns: A list of (path, trans_id) for all items requiring an
412
 
            inventory change. Ordered by path.
413
 
        """
414
 
        changed_ids = set()
415
 
        # Find entries whose file_ids are new (or changed).
416
 
        new_file_id = set(t for t in self._new_id
417
 
                          if self._new_id[t] != self.tree_file_id(t))
418
 
        for id_set in [self._new_name, self._new_parent, new_file_id,
 
384
        """Get the trans_ids and paths of files needing new inv entries."""
 
385
        new_ids = set()
 
386
        for id_set in [self._new_name, self._new_parent, self._new_id,
419
387
                       self._new_executability]:
420
 
            changed_ids.update(id_set)
421
 
        # removing implies a kind change
 
388
            new_ids.update(id_set)
422
389
        changed_kind = set(self._removed_contents)
423
 
        # so does adding
424
390
        changed_kind.intersection_update(self._new_contents)
425
 
        # Ignore entries that are already known to have changed.
426
 
        changed_kind.difference_update(changed_ids)
427
 
        #  to keep only the truly changed ones
428
 
        changed_kind = (t for t in changed_kind
429
 
                        if self.tree_kind(t) != self.final_kind(t))
430
 
        # all kind changes will alter the inventory
431
 
        changed_ids.update(changed_kind)
432
 
        # To find entries with changed parent_ids, find parents which existed,
433
 
        # but changed file_id.
434
 
        changed_file_id = set(t for t in new_file_id if t in self._removed_id)
435
 
        # Now add all their children to the set.
436
 
        for parent_trans_id in new_file_id:
437
 
            changed_ids.update(self.iter_tree_children(parent_trans_id))
438
 
        return sorted(FinalPaths(self).get_paths(changed_ids))
 
391
        changed_kind.difference_update(new_ids)
 
392
        changed_kind = (t for t in changed_kind if self.tree_kind(t) !=
 
393
                        self.final_kind(t))
 
394
        new_ids.update(changed_kind)
 
395
        return sorted(FinalPaths(self).get_paths(new_ids))
439
396
 
440
397
    def final_kind(self, trans_id):
441
398
        """Determine the final file kind, after any changes applied.
442
399
 
443
 
        :return: None if the file does not exist/has no contents.  (It is
444
 
            conceivable that a path would be created without the corresponding
445
 
            contents insertion command)
 
400
        Raises NoSuchFile if the file does not exist/has no contents.
 
401
        (It is conceivable that a path would be created without the
 
402
        corresponding contents insertion command)
446
403
        """
447
404
        if trans_id in self._new_contents:
448
405
            return self._new_contents[trans_id]
449
406
        elif trans_id in self._removed_contents:
450
 
            return None
 
407
            raise NoSuchFile(None)
451
408
        else:
452
409
            return self.tree_kind(trans_id)
453
410
 
566
523
        for trans_id in self._removed_id:
567
524
            file_id = self.tree_file_id(trans_id)
568
525
            if file_id is not None:
569
 
                # XXX: This seems like something that should go via a different
570
 
                #      indirection.
571
526
                if self._tree.inventory[file_id].kind == 'directory':
572
527
                    parents.append(trans_id)
573
528
            elif self.tree_kind(trans_id) == 'directory':
577
532
            # ensure that all children are registered with the transaction
578
533
            list(self.iter_tree_children(parent_id))
579
534
 
580
 
    @deprecated_method(deprecated_in((2, 3, 0)))
581
535
    def has_named_child(self, by_parent, parent_id, name):
582
 
        return self._has_named_child(
583
 
            name, parent_id, known_children=by_parent.get(parent_id, []))
584
 
 
585
 
    def _has_named_child(self, name, parent_id, known_children):
586
 
        """Does a parent already have a name child.
587
 
 
588
 
        :param name: The searched for name.
589
 
 
590
 
        :param parent_id: The parent for which the check is made.
591
 
 
592
 
        :param known_children: The already known children. This should have
593
 
            been recently obtained from `self.by_parent.get(parent_id)`
594
 
            (or will be if None is passed).
595
 
        """
596
 
        if known_children is None:
597
 
            known_children = self.by_parent().get(parent_id, [])
598
 
        for child in known_children:
 
536
        try:
 
537
            children = by_parent[parent_id]
 
538
        except KeyError:
 
539
            children = []
 
540
        for child in children:
599
541
            if self.final_name(child) == name:
600
542
                return True
601
 
        parent_path = self._tree_id_paths.get(parent_id, None)
602
 
        if parent_path is None:
603
 
            # No parent... no children
 
543
        try:
 
544
            path = self._tree_id_paths[parent_id]
 
545
        except KeyError:
604
546
            return False
605
 
        child_path = joinpath(parent_path, name)
606
 
        child_id = self._tree_path_ids.get(child_path, None)
 
547
        childpath = joinpath(path, name)
 
548
        child_id = self._tree_path_ids.get(childpath)
607
549
        if child_id is None:
608
 
            # Not known by the tree transform yet, check the filesystem
609
 
            return osutils.lexists(self._tree.abspath(child_path))
 
550
            return lexists(self._tree.abspath(childpath))
610
551
        else:
611
 
            raise AssertionError('child_id is missing: %s, %s, %s'
612
 
                                 % (name, parent_id, child_id))
613
 
 
614
 
    def _available_backup_name(self, name, target_id):
615
 
        """Find an available backup name.
616
 
 
617
 
        :param name: The basename of the file.
618
 
 
619
 
        :param target_id: The directory trans_id where the backup should 
620
 
            be placed.
621
 
        """
622
 
        known_children = self.by_parent().get(target_id, [])
623
 
        return osutils.available_backup_name(
624
 
            name,
625
 
            lambda base: self._has_named_child(
626
 
                base, target_id, known_children))
 
552
            if self.final_parent(child_id) != parent_id:
 
553
                return False
 
554
            if child_id in self._removed_contents:
 
555
                # XXX What about dangling file-ids?
 
556
                return False
 
557
            else:
 
558
                return True
627
559
 
628
560
    def _parent_loops(self):
629
561
        """No entry should be its own ancestor"""
664
596
        """
665
597
        conflicts = []
666
598
        for trans_id in self._new_id.iterkeys():
667
 
            kind = self.final_kind(trans_id)
668
 
            if kind is None:
 
599
            try:
 
600
                kind = self.final_kind(trans_id)
 
601
            except NoSuchFile:
669
602
                conflicts.append(('versioning no contents', trans_id))
670
603
                continue
671
 
            if not inventory.InventoryEntry.versionable_kind(kind):
 
604
            if not InventoryEntry.versionable_kind(kind):
672
605
                conflicts.append(('versioning bad kind', trans_id, kind))
673
606
        return conflicts
674
607
 
685
618
            if self.final_file_id(trans_id) is None:
686
619
                conflicts.append(('unversioned executability', trans_id))
687
620
            else:
688
 
                if self.final_kind(trans_id) != "file":
 
621
                try:
 
622
                    non_file = self.final_kind(trans_id) != "file"
 
623
                except NoSuchFile:
 
624
                    non_file = True
 
625
                if non_file is True:
689
626
                    conflicts.append(('non-file executability', trans_id))
690
627
        return conflicts
691
628
 
693
630
        """Check for overwrites (not permitted on Win32)"""
694
631
        conflicts = []
695
632
        for trans_id in self._new_contents:
696
 
            if self.tree_kind(trans_id) is None:
 
633
            try:
 
634
                self.tree_kind(trans_id)
 
635
            except NoSuchFile:
697
636
                continue
698
637
            if trans_id not in self._removed_contents:
699
638
                conflicts.append(('overwrite', trans_id,
706
645
        if (self._new_name, self._new_parent) == ({}, {}):
707
646
            return conflicts
708
647
        for children in by_parent.itervalues():
709
 
            name_ids = []
710
 
            for child_tid in children:
711
 
                name = self.final_name(child_tid)
712
 
                if name is not None:
713
 
                    # Keep children only if they still exist in the end
714
 
                    if not self._case_sensitive_target:
715
 
                        name = name.lower()
716
 
                    name_ids.append((name, child_tid))
 
648
            name_ids = [(self.final_name(t), t) for t in children]
 
649
            if not self._case_sensitive_target:
 
650
                name_ids = [(n.lower(), t) for n, t in name_ids]
717
651
            name_ids.sort()
718
652
            last_name = None
719
653
            last_trans_id = None
720
654
            for name, trans_id in name_ids:
721
 
                kind = self.final_kind(trans_id)
 
655
                try:
 
656
                    kind = self.final_kind(trans_id)
 
657
                except NoSuchFile:
 
658
                    kind = None
722
659
                file_id = self.final_file_id(trans_id)
723
660
                if kind is None and file_id is None:
724
661
                    continue
743
680
        return conflicts
744
681
 
745
682
    def _parent_type_conflicts(self, by_parent):
746
 
        """Children must have a directory parent"""
 
683
        """parents must have directory 'contents'."""
747
684
        conflicts = []
748
685
        for parent_id, children in by_parent.iteritems():
749
686
            if parent_id is ROOT_PARENT:
750
687
                continue
751
 
            no_children = True
752
 
            for child_id in children:
753
 
                if self.final_kind(child_id) is not None:
754
 
                    no_children = False
755
 
                    break
756
 
            if no_children:
 
688
            if not self._any_contents(children):
757
689
                continue
758
 
            # There is at least a child, so we need an existing directory to
759
 
            # contain it.
760
 
            kind = self.final_kind(parent_id)
 
690
            for child in children:
 
691
                try:
 
692
                    self.final_kind(child)
 
693
                except NoSuchFile:
 
694
                    continue
 
695
            try:
 
696
                kind = self.final_kind(parent_id)
 
697
            except NoSuchFile:
 
698
                kind = None
761
699
            if kind is None:
762
 
                # The directory will be deleted
763
700
                conflicts.append(('missing parent', parent_id))
764
701
            elif kind != "directory":
765
 
                # Meh, we need a *directory* to put something in it
766
702
                conflicts.append(('non-directory parent', parent_id))
767
703
        return conflicts
768
704
 
 
705
    def _any_contents(self, trans_ids):
 
706
        """Return true if any of the trans_ids, will have contents."""
 
707
        for trans_id in trans_ids:
 
708
            try:
 
709
                kind = self.final_kind(trans_id)
 
710
            except NoSuchFile:
 
711
                continue
 
712
            return True
 
713
        return False
 
714
 
769
715
    def _set_executability(self, path, trans_id):
770
716
        """Set the executability of versioned files """
771
717
        if supports_executable():
793
739
        return trans_id
794
740
 
795
741
    def new_file(self, name, parent_id, contents, file_id=None,
796
 
                 executable=None, sha1=None):
 
742
                 executable=None):
797
743
        """Convenience method to create files.
798
744
 
799
745
        name is the name of the file to create.
806
752
        trans_id = self._new_entry(name, parent_id, file_id)
807
753
        # TODO: rather than scheduling a set_executable call,
808
754
        # have create_file create the file with the right mode.
809
 
        self.create_file(contents, trans_id, sha1=sha1)
 
755
        self.create_file(contents, trans_id)
810
756
        if executable is not None:
811
757
            self.set_executability(executable, trans_id)
812
758
        return trans_id
835
781
        self.create_symlink(target, trans_id)
836
782
        return trans_id
837
783
 
838
 
    def new_orphan(self, trans_id, parent_id):
839
 
        """Schedule an item to be orphaned.
840
 
 
841
 
        When a directory is about to be removed, its children, if they are not
842
 
        versioned are moved out of the way: they don't have a parent anymore.
843
 
 
844
 
        :param trans_id: The trans_id of the existing item.
845
 
        :param parent_id: The parent trans_id of the item.
846
 
        """
847
 
        raise NotImplementedError(self.new_orphan)
848
 
 
849
 
    def _get_potential_orphans(self, dir_id):
850
 
        """Find the potential orphans in a directory.
851
 
 
852
 
        A directory can't be safely deleted if there are versioned files in it.
853
 
        If all the contained files are unversioned then they can be orphaned.
854
 
 
855
 
        The 'None' return value means that the directory contains at least one
856
 
        versioned file and should not be deleted.
857
 
 
858
 
        :param dir_id: The directory trans id.
859
 
 
860
 
        :return: A list of the orphan trans ids or None if at least one
861
 
             versioned file is present.
862
 
        """
863
 
        orphans = []
864
 
        # Find the potential orphans, stop if one item should be kept
865
 
        for child_tid in self.by_parent()[dir_id]:
866
 
            if child_tid in self._removed_contents:
867
 
                # The child is removed as part of the transform. Since it was
868
 
                # versioned before, it's not an orphan
869
 
                continue
870
 
            elif self.final_file_id(child_tid) is None:
871
 
                # The child is not versioned
872
 
                orphans.append(child_tid)
873
 
            else:
874
 
                # We have a versioned file here, searching for orphans is
875
 
                # meaningless.
876
 
                orphans = None
877
 
                break
878
 
        return orphans
879
 
 
880
784
    def _affected_ids(self):
881
785
        """Return the set of transform ids affected by the transform"""
882
786
        trans_ids = set(self._removed_id)
941
845
        Return a (name, parent, kind, executable) tuple
942
846
        """
943
847
        to_name = self.final_name(to_trans_id)
944
 
        to_kind = self.final_kind(to_trans_id)
 
848
        try:
 
849
            to_kind = self.final_kind(to_trans_id)
 
850
        except NoSuchFile:
 
851
            to_kind = None
945
852
        to_parent = self.final_file_id(self.final_parent(to_trans_id))
946
853
        if to_trans_id in self._new_executability:
947
854
            to_executable = self._new_executability[to_trans_id]
1194
1101
        self._deletiondir = None
1195
1102
        # A mapping of transform ids to their limbo filename
1196
1103
        self._limbo_files = {}
1197
 
        self._possibly_stale_limbo_files = set()
1198
1104
        # A mapping of transform ids to a set of the transform ids of children
1199
1105
        # that their limbo directory has
1200
1106
        self._limbo_children = {}
1213
1119
        if self._tree is None:
1214
1120
            return
1215
1121
        try:
1216
 
            limbo_paths = self._limbo_files.values() + list(
1217
 
                self._possibly_stale_limbo_files)
1218
 
            limbo_paths = sorted(limbo_paths, reverse=True)
1219
 
            for path in limbo_paths:
1220
 
                try:
1221
 
                    delete_any(path)
1222
 
                except OSError, e:
1223
 
                    if e.errno != errno.ENOENT:
1224
 
                        raise
1225
 
                    # XXX: warn? perhaps we just got interrupted at an
1226
 
                    # inconvenient moment, but perhaps files are disappearing
1227
 
                    # from under us?
 
1122
            entries = [(self._limbo_name(t), t, k) for t, k in
 
1123
                       self._new_contents.iteritems()]
 
1124
            entries.sort(reverse=True)
 
1125
            for path, trans_id, kind in entries:
 
1126
                delete_any(path)
1228
1127
            try:
1229
1128
                delete_any(self._limbodir)
1230
1129
            except OSError:
1279
1178
        entries from _limbo_files, because they are now stale.
1280
1179
        """
1281
1180
        for trans_id in trans_ids:
1282
 
            old_path = self._limbo_files[trans_id]
1283
 
            self._possibly_stale_limbo_files.add(old_path)
1284
 
            del self._limbo_files[trans_id]
 
1181
            old_path = self._limbo_files.pop(trans_id)
1285
1182
            if trans_id not in self._new_contents:
1286
1183
                continue
1287
1184
            new_path = self._limbo_name(trans_id)
1288
 
            os.rename(old_path, new_path)
1289
 
            self._possibly_stale_limbo_files.remove(old_path)
 
1185
            osutils.rename(old_path, new_path)
1290
1186
            for descendant in self._limbo_descendants(trans_id):
1291
1187
                desc_path = self._limbo_files[descendant]
1292
1188
                desc_path = new_path + desc_path[len(old_path):]
1299
1195
            descendants.update(self._limbo_descendants(descendant))
1300
1196
        return descendants
1301
1197
 
1302
 
    def create_file(self, contents, trans_id, mode_id=None, sha1=None):
 
1198
    def create_file(self, contents, trans_id, mode_id=None):
1303
1199
        """Schedule creation of a new file.
1304
1200
 
1305
 
        :seealso: new_file.
1306
 
 
1307
 
        :param contents: an iterator of strings, all of which will be written
1308
 
            to the target destination.
1309
 
        :param trans_id: TreeTransform handle
1310
 
        :param mode_id: If not None, force the mode of the target file to match
1311
 
            the mode of the object referenced by mode_id.
1312
 
            Otherwise, we will try to preserve mode bits of an existing file.
1313
 
        :param sha1: If the sha1 of this content is already known, pass it in.
1314
 
            We can use it to prevent future sha1 computations.
 
1201
        See also new_file.
 
1202
 
 
1203
        Contents is an iterator of strings, all of which will be written
 
1204
        to the target destination.
 
1205
 
 
1206
        New file takes the permissions of any existing file with that id,
 
1207
        unless mode_id is specified.
1315
1208
        """
1316
1209
        name = self._limbo_name(trans_id)
1317
1210
        f = open(name, 'wb')
1318
1211
        try:
1319
 
            unique_add(self._new_contents, trans_id, 'file')
 
1212
            try:
 
1213
                unique_add(self._new_contents, trans_id, 'file')
 
1214
            except:
 
1215
                # Clean up the file, it never got registered so
 
1216
                # TreeTransform.finalize() won't clean it up.
 
1217
                f.close()
 
1218
                os.unlink(name)
 
1219
                raise
 
1220
 
1320
1221
            f.writelines(contents)
1321
1222
        finally:
1322
1223
            f.close()
1323
1224
        self._set_mtime(name)
1324
1225
        self._set_mode(trans_id, mode_id, S_ISREG)
1325
 
        # It is unfortunate we have to use lstat instead of fstat, but we just
1326
 
        # used utime and chmod on the file, so we need the accurate final
1327
 
        # details.
1328
 
        if sha1 is not None:
1329
 
            self._observed_sha1s[trans_id] = (sha1, osutils.lstat(name))
1330
1226
 
1331
1227
    def _read_file_chunks(self, trans_id):
1332
1228
        cur_file = open(self._limbo_name(trans_id), 'rb')
1391
1287
    def cancel_creation(self, trans_id):
1392
1288
        """Cancel the creation of new file contents."""
1393
1289
        del self._new_contents[trans_id]
1394
 
        if trans_id in self._observed_sha1s:
1395
 
            del self._observed_sha1s[trans_id]
1396
1290
        children = self._limbo_children.get(trans_id)
1397
1291
        # if this is a limbo directory with children, move them before removing
1398
1292
        # the directory
1402
1296
            del self._limbo_children_names[trans_id]
1403
1297
        delete_any(self._limbo_name(trans_id))
1404
1298
 
1405
 
    def new_orphan(self, trans_id, parent_id):
1406
 
        # FIXME: There is no tree config, so we use the branch one (it's weird
1407
 
        # to define it this way as orphaning can only occur in a working tree,
1408
 
        # but that's all we have (for now). It will find the option in
1409
 
        # locations.conf or bazaar.conf though) -- vila 20100916
1410
 
        conf = self._tree.branch.get_config()
1411
 
        conf_var_name = 'bzr.transform.orphan_policy'
1412
 
        orphan_policy = conf.get_user_option(conf_var_name)
1413
 
        default_policy = orphaning_registry.default_key
1414
 
        if orphan_policy is None:
1415
 
            orphan_policy = default_policy
1416
 
        if orphan_policy not in orphaning_registry:
1417
 
            trace.warning('%s (from %s) is not a known policy, defaulting '
1418
 
                'to %s' % (orphan_policy, conf_var_name, default_policy))
1419
 
            orphan_policy = default_policy
1420
 
        handle_orphan = orphaning_registry.get(orphan_policy)
1421
 
        handle_orphan(self, trans_id, parent_id)
1422
 
 
1423
 
 
1424
 
class OrphaningError(errors.BzrError):
1425
 
 
1426
 
    # Only bugs could lead to such exception being seen by the user
1427
 
    internal_error = True
1428
 
    _fmt = "Error while orphaning %s in %s directory"
1429
 
 
1430
 
    def __init__(self, orphan, parent):
1431
 
        errors.BzrError.__init__(self)
1432
 
        self.orphan = orphan
1433
 
        self.parent = parent
1434
 
 
1435
 
 
1436
 
class OrphaningForbidden(OrphaningError):
1437
 
 
1438
 
    _fmt = "Policy: %s doesn't allow creating orphans."
1439
 
 
1440
 
    def __init__(self, policy):
1441
 
        errors.BzrError.__init__(self)
1442
 
        self.policy = policy
1443
 
 
1444
 
 
1445
 
def move_orphan(tt, orphan_id, parent_id):
1446
 
    """See TreeTransformBase.new_orphan.
1447
 
 
1448
 
    This creates a new orphan in the `bzr-orphans` dir at the root of the
1449
 
    `TreeTransform`.
1450
 
 
1451
 
    :param tt: The TreeTransform orphaning `trans_id`.
1452
 
 
1453
 
    :param orphan_id: The trans id that should be orphaned.
1454
 
 
1455
 
    :param parent_id: The orphan parent trans id.
1456
 
    """
1457
 
    # Add the orphan dir if it doesn't exist
1458
 
    orphan_dir_basename = 'bzr-orphans'
1459
 
    od_id = tt.trans_id_tree_path(orphan_dir_basename)
1460
 
    if tt.final_kind(od_id) is None:
1461
 
        tt.create_directory(od_id)
1462
 
    parent_path = tt._tree_id_paths[parent_id]
1463
 
    # Find a name that doesn't exist yet in the orphan dir
1464
 
    actual_name = tt.final_name(orphan_id)
1465
 
    new_name = tt._available_backup_name(actual_name, od_id)
1466
 
    tt.adjust_path(new_name, od_id, orphan_id)
1467
 
    trace.warning('%s has been orphaned in %s'
1468
 
                  % (joinpath(parent_path, actual_name), orphan_dir_basename))
1469
 
 
1470
 
 
1471
 
def refuse_orphan(tt, orphan_id, parent_id):
1472
 
    """See TreeTransformBase.new_orphan.
1473
 
 
1474
 
    This refuses to create orphan, letting the caller handle the conflict.
1475
 
    """
1476
 
    raise OrphaningForbidden('never')
1477
 
 
1478
 
 
1479
 
orphaning_registry = registry.Registry()
1480
 
orphaning_registry.register(
1481
 
    'conflict', refuse_orphan,
1482
 
    'Leave orphans in place and create a conflict on the directory.')
1483
 
orphaning_registry.register(
1484
 
    'move', move_orphan,
1485
 
    'Move orphans into the bzr-orphans directory.')
1486
 
orphaning_registry._set_default_key('conflict')
1487
 
 
1488
1299
 
1489
1300
class TreeTransform(DiskTreeTransform):
1490
1301
    """Represent a tree transformation.
1608
1419
    def tree_kind(self, trans_id):
1609
1420
        """Determine the file kind in the working tree.
1610
1421
 
1611
 
        :returns: The file kind or None if the file does not exist
 
1422
        Raises NoSuchFile if the file does not exist
1612
1423
        """
1613
1424
        path = self._tree_id_paths.get(trans_id)
1614
1425
        if path is None:
1615
 
            return None
 
1426
            raise NoSuchFile(None)
1616
1427
        try:
1617
1428
            return file_kind(self._tree.abspath(path))
1618
 
        except errors.NoSuchFile:
1619
 
            return None
 
1429
        except OSError, e:
 
1430
            if e.errno != errno.ENOENT:
 
1431
                raise
 
1432
            else:
 
1433
                raise NoSuchFile(path)
1620
1434
 
1621
1435
    def _set_mode(self, trans_id, mode_id, typefunc):
1622
1436
        """Set the mode of new file contents.
1728
1542
        """
1729
1543
        if not no_conflicts:
1730
1544
            self._check_malformed()
1731
 
        child_pb = ui.ui_factory.nested_progress_bar()
 
1545
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1732
1546
        try:
1733
1547
            if precomputed_delta is None:
1734
1548
                child_pb.update('Apply phase', 0, 2)
1754
1568
        finally:
1755
1569
            child_pb.finished()
1756
1570
        self._tree.apply_inventory_delta(inventory_delta)
1757
 
        self._apply_observed_sha1s()
1758
1571
        self._done = True
1759
1572
        self.finalize()
1760
1573
        return _TransformResults(modified_paths, self.rename_count)
1762
1575
    def _generate_inventory_delta(self):
1763
1576
        """Generate an inventory delta for the current transform."""
1764
1577
        inventory_delta = []
1765
 
        child_pb = ui.ui_factory.nested_progress_bar()
 
1578
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1766
1579
        new_paths = self._inventory_altered()
1767
1580
        total_entries = len(new_paths) + len(self._removed_id)
1768
1581
        try:
1792
1605
                if file_id is None:
1793
1606
                    continue
1794
1607
                needs_entry = False
1795
 
                kind = self.final_kind(trans_id)
1796
 
                if kind is None:
 
1608
                try:
 
1609
                    kind = self.final_kind(trans_id)
 
1610
                except NoSuchFile:
1797
1611
                    kind = self._tree.stored_kind(file_id)
1798
1612
                parent_trans_id = self.final_parent(trans_id)
1799
1613
                parent_file_id = new_path_file_ids.get(parent_trans_id)
1830
1644
        """
1831
1645
        tree_paths = list(self._tree_path_ids.iteritems())
1832
1646
        tree_paths.sort(reverse=True)
1833
 
        child_pb = ui.ui_factory.nested_progress_bar()
 
1647
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1834
1648
        try:
1835
 
            for num, (path, trans_id) in enumerate(tree_paths):
1836
 
                # do not attempt to move root into a subdirectory of itself.
1837
 
                if path == '':
1838
 
                    continue
 
1649
            for num, data in enumerate(tree_paths):
 
1650
                path, trans_id = data
1839
1651
                child_pb.update('removing file', num, len(tree_paths))
1840
1652
                full_path = self._tree.abspath(path)
1841
1653
                if trans_id in self._removed_contents:
1867
1679
        modified_paths = []
1868
1680
        new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1869
1681
                                 new_paths)
1870
 
        child_pb = ui.ui_factory.nested_progress_bar()
 
1682
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1871
1683
        try:
1872
1684
            for num, (path, trans_id) in enumerate(new_paths):
1873
1685
                if (num % 10) == 0:
1882
1694
                            raise
1883
1695
                    else:
1884
1696
                        self.rename_count += 1
1885
 
                    # TODO: if trans_id in self._observed_sha1s, we should
1886
 
                    #       re-stat the final target, since ctime will be
1887
 
                    #       updated by the change.
1888
1697
                if (trans_id in self._new_contents or
1889
1698
                    self.path_changed(trans_id)):
1890
1699
                    if trans_id in self._new_contents:
1891
1700
                        modified_paths.append(full_path)
1892
1701
                if trans_id in self._new_executability:
1893
1702
                    self._set_executability(path, trans_id)
1894
 
                if trans_id in self._observed_sha1s:
1895
 
                    o_sha1, o_st_val = self._observed_sha1s[trans_id]
1896
 
                    st = osutils.lstat(full_path)
1897
 
                    self._observed_sha1s[trans_id] = (o_sha1, st)
1898
1703
        finally:
1899
1704
            child_pb.finished()
1900
 
        for path, trans_id in new_paths:
1901
 
            # new_paths includes stuff like workingtree conflicts. Only the
1902
 
            # stuff in new_contents actually comes from limbo.
1903
 
            if trans_id in self._limbo_files:
1904
 
                del self._limbo_files[trans_id]
1905
1705
        self._new_contents.clear()
1906
1706
        return modified_paths
1907
1707
 
1908
 
    def _apply_observed_sha1s(self):
1909
 
        """After we have finished renaming everything, update observed sha1s
1910
 
 
1911
 
        This has to be done after self._tree.apply_inventory_delta, otherwise
1912
 
        it doesn't know anything about the files we are updating. Also, we want
1913
 
        to do this as late as possible, so that most entries end up cached.
1914
 
        """
1915
 
        # TODO: this doesn't update the stat information for directories. So
1916
 
        #       the first 'bzr status' will still need to rewrite
1917
 
        #       .bzr/checkout/dirstate. However, we at least don't need to
1918
 
        #       re-read all of the files.
1919
 
        # TODO: If the operation took a while, we could do a time.sleep(3) here
1920
 
        #       to allow the clock to tick over and ensure we won't have any
1921
 
        #       problems. (we could observe start time, and finish time, and if
1922
 
        #       it is less than eg 10% overhead, add a sleep call.)
1923
 
        paths = FinalPaths(self)
1924
 
        for trans_id, observed in self._observed_sha1s.iteritems():
1925
 
            path = paths.get_path(trans_id)
1926
 
            # We could get the file_id, but dirstate prefers to use the path
1927
 
            # anyway, and it is 'cheaper' to determine.
1928
 
            # file_id = self._new_id[trans_id]
1929
 
            self._tree._observed_sha1(None, path, observed)
1930
 
 
1931
1708
 
1932
1709
class TransformPreview(DiskTreeTransform):
1933
1710
    """A TreeTransform for generating preview trees.
1948
1725
    def tree_kind(self, trans_id):
1949
1726
        path = self._tree_id_paths.get(trans_id)
1950
1727
        if path is None:
1951
 
            return None
1952
 
        kind = self._tree.path_content_summary(path)[0]
1953
 
        if kind == 'missing':
1954
 
            kind = None
1955
 
        return kind
 
1728
            raise NoSuchFile(None)
 
1729
        file_id = self._tree.path2id(path)
 
1730
        return self._tree.kind(file_id)
1956
1731
 
1957
1732
    def _set_mode(self, trans_id, mode_id, typefunc):
1958
1733
        """Set the mode of new file contents.
1978
1753
            childpath = joinpath(path, child)
1979
1754
            yield self.trans_id_tree_path(childpath)
1980
1755
 
1981
 
    def new_orphan(self, trans_id, parent_id):
1982
 
        raise NotImplementedError(self.new_orphan)
1983
 
 
1984
 
 
1985
 
class _PreviewTree(tree.InventoryTree):
 
1756
 
 
1757
class _PreviewTree(tree.Tree):
1986
1758
    """Partial implementation of Tree to support show_diff_trees"""
1987
1759
 
1988
1760
    def __init__(self, transform):
2017
1789
                yield self._get_repository().revision_tree(revision_id)
2018
1790
 
2019
1791
    def _get_file_revision(self, file_id, vf, tree_revision):
2020
 
        parent_keys = [(file_id, t.get_file_revision(file_id)) for t in
 
1792
        parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
2021
1793
                       self._iter_parent_trees()]
2022
1794
        vf.add_lines((file_id, tree_revision), parent_keys,
2023
1795
                     self.get_file_lines(file_id))
2027
1799
            vf.fallback_versionedfiles.append(base_vf)
2028
1800
        return tree_revision
2029
1801
 
2030
 
    def _stat_limbo_file(self, file_id=None, trans_id=None):
2031
 
        if trans_id is None:
2032
 
            trans_id = self._transform.trans_id_file_id(file_id)
 
1802
    def _stat_limbo_file(self, file_id):
 
1803
        trans_id = self._transform.trans_id_file_id(file_id)
2033
1804
        name = self._transform._limbo_name(trans_id)
2034
1805
        return os.lstat(name)
2035
1806
 
2158
1929
            if (specific_file_ids is not None
2159
1930
                and file_id not in specific_file_ids):
2160
1931
                continue
2161
 
            kind = self._transform.final_kind(trans_id)
2162
 
            if kind is None:
 
1932
            try:
 
1933
                kind = self._transform.final_kind(trans_id)
 
1934
            except NoSuchFile:
2163
1935
                kind = self._transform._tree.stored_kind(file_id)
2164
1936
            new_entry = inventory.make_entry(
2165
1937
                kind,
2250
2022
 
2251
2023
    def get_file_size(self, file_id):
2252
2024
        """See Tree.get_file_size"""
2253
 
        trans_id = self._transform.trans_id_file_id(file_id)
2254
 
        kind = self._transform.final_kind(trans_id)
2255
 
        if kind != 'file':
2256
 
            return None
2257
 
        if trans_id in self._transform._new_contents:
2258
 
            return self._stat_limbo_file(trans_id=trans_id).st_size
2259
2025
        if self.kind(file_id) == 'file':
2260
2026
            return self._transform._tree.get_file_size(file_id)
2261
2027
        else:
2289
2055
            except errors.NoSuchId:
2290
2056
                return False
2291
2057
 
2292
 
    def has_filename(self, path):
2293
 
        trans_id = self._path2trans_id(path)
2294
 
        if trans_id in self._transform._new_contents:
2295
 
            return True
2296
 
        elif trans_id in self._transform._removed_contents:
2297
 
            return False
2298
 
        else:
2299
 
            return self._transform._tree.has_filename(path)
2300
 
 
2301
2058
    def path_content_summary(self, path):
2302
2059
        trans_id = self._path2trans_id(path)
2303
2060
        tt = self._transform
2391
2148
                                   self.get_file(file_id).readlines(),
2392
2149
                                   default_revision)
2393
2150
 
2394
 
    def get_symlink_target(self, file_id, path=None):
 
2151
    def get_symlink_target(self, file_id):
2395
2152
        """See Tree.get_symlink_target"""
2396
2153
        if not self._content_change(file_id):
2397
2154
            return self._transform._tree.get_symlink_target(file_id)
2412
2169
                path_from_root = self._final_paths.get_path(child_id)
2413
2170
                basename = self._transform.final_name(child_id)
2414
2171
                file_id = self._transform.final_file_id(child_id)
2415
 
                kind  = self._transform.final_kind(child_id)
2416
 
                if kind is not None:
 
2172
                try:
 
2173
                    kind = self._transform.final_kind(child_id)
2417
2174
                    versioned_kind = kind
2418
 
                else:
 
2175
                except NoSuchFile:
2419
2176
                    kind = 'unknown'
2420
2177
                    versioned_kind = self._transform._tree.stored_kind(file_id)
2421
2178
                if versioned_kind == 'directory':
2534
2291
    for num, _unused in enumerate(wt.all_file_ids()):
2535
2292
        if num > 0:  # more than just a root
2536
2293
            raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
 
2294
    existing_files = set()
 
2295
    for dir, files in wt.walkdirs():
 
2296
        existing_files.update(f[0] for f in files)
2537
2297
    file_trans_id = {}
2538
 
    top_pb = ui.ui_factory.nested_progress_bar()
 
2298
    top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2539
2299
    pp = ProgressPhase("Build phase", 2, top_pb)
2540
2300
    if tree.inventory.root is not None:
2541
2301
        # This is kind of a hack: we should be altering the root
2554
2314
        pp.next_phase()
2555
2315
        file_trans_id[wt.get_root_id()] = \
2556
2316
            tt.trans_id_tree_file_id(wt.get_root_id())
2557
 
        pb = ui.ui_factory.nested_progress_bar()
 
2317
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
2558
2318
        try:
2559
2319
            deferred_contents = []
2560
2320
            num = 0
2563
2323
                precomputed_delta = []
2564
2324
            else:
2565
2325
                precomputed_delta = None
2566
 
            # Check if tree inventory has content. If so, we populate
2567
 
            # existing_files with the directory content. If there are no
2568
 
            # entries we skip populating existing_files as its not used.
2569
 
            # This improves performance and unncessary work on large
2570
 
            # directory trees. (#501307)
2571
 
            if total > 0:
2572
 
                existing_files = set()
2573
 
                for dir, files in wt.walkdirs():
2574
 
                    existing_files.update(f[0] for f in files)
2575
2326
            for num, (tree_path, entry) in \
2576
2327
                enumerate(tree.inventory.iter_entries_by_dir()):
2577
2328
                pb.update("Building tree", num - len(deferred_contents), total)
2607
2358
                    executable = tree.is_executable(file_id, tree_path)
2608
2359
                    if executable:
2609
2360
                        tt.set_executability(executable, trans_id)
2610
 
                    trans_data = (trans_id, tree_path, entry.text_sha1)
 
2361
                    trans_data = (trans_id, tree_path)
2611
2362
                    deferred_contents.append((file_id, trans_data))
2612
2363
                else:
2613
2364
                    file_trans_id[file_id] = new_by_entry(tt, entry, parent_id,
2629
2380
            precomputed_delta = None
2630
2381
        conflicts = cook_conflicts(raw_conflicts, tt)
2631
2382
        for conflict in conflicts:
2632
 
            trace.warning(unicode(conflict))
 
2383
            warning(conflict)
2633
2384
        try:
2634
2385
            wt.add_conflicts(conflicts)
2635
2386
        except errors.UnsupportedOperation:
2658
2409
        unchanged = dict(unchanged)
2659
2410
        new_desired_files = []
2660
2411
        count = 0
2661
 
        for file_id, (trans_id, tree_path, text_sha1) in desired_files:
 
2412
        for file_id, (trans_id, tree_path) in desired_files:
2662
2413
            accelerator_path = unchanged.get(file_id)
2663
2414
            if accelerator_path is None:
2664
 
                new_desired_files.append((file_id,
2665
 
                    (trans_id, tree_path, text_sha1)))
 
2415
                new_desired_files.append((file_id, (trans_id, tree_path)))
2666
2416
                continue
2667
2417
            pb.update('Adding file contents', count + offset, total)
2668
2418
            if hardlink:
2675
2425
                    contents = filtered_output_bytes(contents, filters,
2676
2426
                        ContentFilterContext(tree_path, tree))
2677
2427
                try:
2678
 
                    tt.create_file(contents, trans_id, sha1=text_sha1)
 
2428
                    tt.create_file(contents, trans_id)
2679
2429
                finally:
2680
2430
                    try:
2681
2431
                        contents.close()
2684
2434
                        pass
2685
2435
            count += 1
2686
2436
        offset += count
2687
 
    for count, ((trans_id, tree_path, text_sha1), contents) in enumerate(
 
2437
    for count, ((trans_id, tree_path), contents) in enumerate(
2688
2438
            tree.iter_files_bytes(new_desired_files)):
2689
2439
        if wt.supports_content_filtering():
2690
2440
            filters = wt._content_filter_stack(tree_path)
2691
2441
            contents = filtered_output_bytes(contents, filters,
2692
2442
                ContentFilterContext(tree_path, tree))
2693
 
        tt.create_file(contents, trans_id, sha1=text_sha1)
 
2443
        tt.create_file(contents, trans_id)
2694
2444
        pb.update('Adding file contents', count + offset, total)
2695
2445
 
2696
2446
 
2698
2448
    for child in tt.iter_tree_children(old_parent):
2699
2449
        tt.adjust_path(tt.final_name(child), new_parent, child)
2700
2450
 
2701
 
 
2702
2451
def _reparent_transform_children(tt, old_parent, new_parent):
2703
2452
    by_parent = tt.by_parent()
2704
2453
    for child in by_parent[old_parent]:
2705
2454
        tt.adjust_path(tt.final_name(child), new_parent, child)
2706
2455
    return by_parent[old_parent]
2707
2456
 
2708
 
 
2709
2457
def _content_match(tree, entry, file_id, kind, target_path):
2710
2458
    if entry.kind != kind:
2711
2459
        return False
2775
2523
        raise errors.BadFileKindError(name, kind)
2776
2524
 
2777
2525
 
 
2526
@deprecated_function(deprecated_in((1, 9, 0)))
 
2527
def create_by_entry(tt, entry, tree, trans_id, lines=None, mode_id=None):
 
2528
    """Create new file contents according to an inventory entry.
 
2529
 
 
2530
    DEPRECATED.  Use create_from_tree instead.
 
2531
    """
 
2532
    if entry.kind == "file":
 
2533
        if lines is None:
 
2534
            lines = tree.get_file(entry.file_id).readlines()
 
2535
        tt.create_file(lines, trans_id, mode_id=mode_id)
 
2536
    elif entry.kind == "symlink":
 
2537
        tt.create_symlink(tree.get_symlink_target(entry.file_id), trans_id)
 
2538
    elif entry.kind == "directory":
 
2539
        tt.create_directory(trans_id)
 
2540
 
 
2541
 
2778
2542
def create_from_tree(tt, trans_id, tree, file_id, bytes=None,
2779
2543
    filter_tree_path=None):
2780
2544
    """Create new file contents according to tree contents.
2811
2575
        tt.set_executability(entry.executable, trans_id)
2812
2576
 
2813
2577
 
2814
 
@deprecated_function(deprecated_in((2, 3, 0)))
2815
2578
def get_backup_name(entry, by_parent, parent_trans_id, tt):
2816
2579
    return _get_backup_name(entry.name, by_parent, parent_trans_id, tt)
2817
2580
 
2818
2581
 
2819
 
@deprecated_function(deprecated_in((2, 3, 0)))
2820
2582
def _get_backup_name(name, by_parent, parent_trans_id, tt):
2821
2583
    """Produce a backup-style name that appears to be available"""
2822
2584
    def name_gen():
2871
2633
                unversioned_filter=working_tree.is_ignored)
2872
2634
            delta.report_changes(tt.iter_changes(), change_reporter)
2873
2635
        for conflict in conflicts:
2874
 
            trace.warning(unicode(conflict))
 
2636
            warning(conflict)
2875
2637
        pp.next_phase()
2876
2638
        tt.apply()
2877
2639
        working_tree.set_merge_modified(merge_modified)
2885
2647
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
2886
2648
                              backups, pp, basis_tree=None,
2887
2649
                              merge_modified=None):
2888
 
    child_pb = ui.ui_factory.nested_progress_bar()
 
2650
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2889
2651
    try:
2890
2652
        if merge_modified is None:
2891
2653
            merge_modified = working_tree.merge_modified()
2894
2656
                                      merge_modified, basis_tree)
2895
2657
    finally:
2896
2658
        child_pb.finished()
2897
 
    child_pb = ui.ui_factory.nested_progress_bar()
 
2659
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2898
2660
    try:
2899
2661
        raw_conflicts = resolve_conflicts(tt, child_pb,
2900
2662
            lambda t, c: conflict_pass(t, c, target_tree))
2908
2670
                 backups, merge_modified, basis_tree=None):
2909
2671
    if basis_tree is not None:
2910
2672
        basis_tree.lock_read()
2911
 
    # We ask the working_tree for its changes relative to the target, rather
2912
 
    # than the target changes relative to the working tree. Because WT4 has an
2913
 
    # optimizer to compare itself to a target, but no optimizer for the
2914
 
    # reverse.
2915
 
    change_list = working_tree.iter_changes(target_tree,
 
2673
    change_list = target_tree.iter_changes(working_tree,
2916
2674
        specific_files=specific_files, pb=pb)
2917
2675
    if target_tree.get_root_id() is None:
2918
2676
        skip_root = True
2922
2680
        deferred_files = []
2923
2681
        for id_num, (file_id, path, changed_content, versioned, parent, name,
2924
2682
                kind, executable) in enumerate(change_list):
2925
 
            target_path, wt_path = path
2926
 
            target_versioned, wt_versioned = versioned
2927
 
            target_parent, wt_parent = parent
2928
 
            target_name, wt_name = name
2929
 
            target_kind, wt_kind = kind
2930
 
            target_executable, wt_executable = executable
2931
 
            if skip_root and wt_parent is None:
 
2683
            if skip_root and file_id[0] is not None and parent[0] is None:
2932
2684
                continue
2933
2685
            trans_id = tt.trans_id_file_id(file_id)
2934
2686
            mode_id = None
2935
2687
            if changed_content:
2936
2688
                keep_content = False
2937
 
                if wt_kind == 'file' and (backups or target_kind is None):
 
2689
                if kind[0] == 'file' and (backups or kind[1] is None):
2938
2690
                    wt_sha1 = working_tree.get_file_sha1(file_id)
2939
2691
                    if merge_modified.get(file_id) != wt_sha1:
2940
2692
                        # acquire the basis tree lazily to prevent the
2943
2695
                        if basis_tree is None:
2944
2696
                            basis_tree = working_tree.basis_tree()
2945
2697
                            basis_tree.lock_read()
2946
 
                        if basis_tree.has_id(file_id):
 
2698
                        if file_id in basis_tree:
2947
2699
                            if wt_sha1 != basis_tree.get_file_sha1(file_id):
2948
2700
                                keep_content = True
2949
 
                        elif target_kind is None and not target_versioned:
 
2701
                        elif kind[1] is None and not versioned[1]:
2950
2702
                            keep_content = True
2951
 
                if wt_kind is not None:
 
2703
                if kind[0] is not None:
2952
2704
                    if not keep_content:
2953
2705
                        tt.delete_contents(trans_id)
2954
 
                    elif target_kind is not None:
2955
 
                        parent_trans_id = tt.trans_id_file_id(wt_parent)
2956
 
                        backup_name = tt._available_backup_name(
2957
 
                            wt_name, parent_trans_id)
 
2706
                    elif kind[1] is not None:
 
2707
                        parent_trans_id = tt.trans_id_file_id(parent[0])
 
2708
                        by_parent = tt.by_parent()
 
2709
                        backup_name = _get_backup_name(name[0], by_parent,
 
2710
                                                       parent_trans_id, tt)
2958
2711
                        tt.adjust_path(backup_name, parent_trans_id, trans_id)
2959
 
                        new_trans_id = tt.create_path(wt_name, parent_trans_id)
2960
 
                        if wt_versioned and target_versioned:
 
2712
                        new_trans_id = tt.create_path(name[0], parent_trans_id)
 
2713
                        if versioned == (True, True):
2961
2714
                            tt.unversion_file(trans_id)
2962
2715
                            tt.version_file(file_id, new_trans_id)
2963
2716
                        # New contents should have the same unix perms as old
2964
2717
                        # contents
2965
2718
                        mode_id = trans_id
2966
2719
                        trans_id = new_trans_id
2967
 
                if target_kind in ('directory', 'tree-reference'):
 
2720
                if kind[1] in ('directory', 'tree-reference'):
2968
2721
                    tt.create_directory(trans_id)
2969
 
                    if target_kind == 'tree-reference':
 
2722
                    if kind[1] == 'tree-reference':
2970
2723
                        revision = target_tree.get_reference_revision(file_id,
2971
 
                                                                      target_path)
 
2724
                                                                      path[1])
2972
2725
                        tt.set_tree_reference(revision, trans_id)
2973
 
                elif target_kind == 'symlink':
 
2726
                elif kind[1] == 'symlink':
2974
2727
                    tt.create_symlink(target_tree.get_symlink_target(file_id),
2975
2728
                                      trans_id)
2976
 
                elif target_kind == 'file':
 
2729
                elif kind[1] == 'file':
2977
2730
                    deferred_files.append((file_id, (trans_id, mode_id)))
2978
2731
                    if basis_tree is None:
2979
2732
                        basis_tree = working_tree.basis_tree()
2980
2733
                        basis_tree.lock_read()
2981
2734
                    new_sha1 = target_tree.get_file_sha1(file_id)
2982
 
                    if (basis_tree.has_id(file_id) and
2983
 
                        new_sha1 == basis_tree.get_file_sha1(file_id)):
 
2735
                    if (file_id in basis_tree and new_sha1 ==
 
2736
                        basis_tree.get_file_sha1(file_id)):
2984
2737
                        if file_id in merge_modified:
2985
2738
                            del merge_modified[file_id]
2986
2739
                    else:
2987
2740
                        merge_modified[file_id] = new_sha1
2988
2741
 
2989
2742
                    # preserve the execute bit when backing up
2990
 
                    if keep_content and wt_executable == target_executable:
2991
 
                        tt.set_executability(target_executable, trans_id)
2992
 
                elif target_kind is not None:
2993
 
                    raise AssertionError(target_kind)
2994
 
            if not wt_versioned and target_versioned:
 
2743
                    if keep_content and executable[0] == executable[1]:
 
2744
                        tt.set_executability(executable[1], trans_id)
 
2745
                elif kind[1] is not None:
 
2746
                    raise AssertionError(kind[1])
 
2747
            if versioned == (False, True):
2995
2748
                tt.version_file(file_id, trans_id)
2996
 
            if wt_versioned and not target_versioned:
 
2749
            if versioned == (True, False):
2997
2750
                tt.unversion_file(trans_id)
2998
 
            if (target_name is not None and
2999
 
                (wt_name != target_name or wt_parent != target_parent)):
3000
 
                if target_name == '' and target_parent is None:
 
2751
            if (name[1] is not None and
 
2752
                (name[0] != name[1] or parent[0] != parent[1])):
 
2753
                if name[1] == '' and parent[1] is None:
3001
2754
                    parent_trans = ROOT_PARENT
3002
2755
                else:
3003
 
                    parent_trans = tt.trans_id_file_id(target_parent)
3004
 
                if wt_parent is None and wt_versioned:
3005
 
                    tt.adjust_root_path(target_name, parent_trans)
 
2756
                    parent_trans = tt.trans_id_file_id(parent[1])
 
2757
                if parent[0] is None and versioned[0]:
 
2758
                    tt.adjust_root_path(name[1], parent_trans)
3006
2759
                else:
3007
 
                    tt.adjust_path(target_name, parent_trans, trans_id)
3008
 
            if wt_executable != target_executable and target_kind == "file":
3009
 
                tt.set_executability(target_executable, trans_id)
 
2760
                    tt.adjust_path(name[1], parent_trans, trans_id)
 
2761
            if executable[0] != executable[1] and kind[1] == "file":
 
2762
                tt.set_executability(executable[1], trans_id)
3010
2763
        if working_tree.supports_content_filtering():
3011
2764
            for index, ((trans_id, mode_id), bytes) in enumerate(
3012
2765
                target_tree.iter_files_bytes(deferred_files)):
3083
2836
 
3084
2837
        elif c_type == 'missing parent':
3085
2838
            trans_id = conflict[1]
3086
 
            if trans_id in tt._removed_contents:
3087
 
                cancel_deletion = True
3088
 
                orphans = tt._get_potential_orphans(trans_id)
3089
 
                if orphans:
3090
 
                    cancel_deletion = False
3091
 
                    # All children are orphans
3092
 
                    for o in orphans:
3093
 
                        try:
3094
 
                            tt.new_orphan(o, trans_id)
3095
 
                        except OrphaningError:
3096
 
                            # Something bad happened so we cancel the directory
3097
 
                            # deletion which will leave it in place with a
3098
 
                            # conflict. The user can deal with it from there.
3099
 
                            # Note that this also catch the case where we don't
3100
 
                            # want to create orphans and leave the directory in
3101
 
                            # place.
3102
 
                            cancel_deletion = True
3103
 
                            break
3104
 
                if cancel_deletion:
3105
 
                    # Cancel the directory deletion
3106
 
                    tt.cancel_deletion(trans_id)
3107
 
                    new_conflicts.add(('deleting parent', 'Not deleting',
3108
 
                                       trans_id))
3109
 
            else:
 
2839
            try:
 
2840
                tt.cancel_deletion(trans_id)
 
2841
                new_conflicts.add(('deleting parent', 'Not deleting',
 
2842
                                   trans_id))
 
2843
            except KeyError:
3110
2844
                create = True
3111
2845
                try:
3112
2846
                    tt.final_name(trans_id)
3115
2849
                        file_id = tt.final_file_id(trans_id)
3116
2850
                        if file_id is None:
3117
2851
                            file_id = tt.inactive_file_id(trans_id)
3118
 
                        _, entry = path_tree.iter_entries_by_dir(
3119
 
                            [file_id]).next()
 
2852
                        entry = path_tree.inventory[file_id]
3120
2853
                        # special-case the other tree root (move its
3121
2854
                        # children to current root)
3122
2855
                        if entry.parent_id is None:
3137
2870
        elif c_type == 'unversioned parent':
3138
2871
            file_id = tt.inactive_file_id(conflict[1])
3139
2872
            # special-case the other tree root (move its children instead)
3140
 
            if path_tree and path_tree.has_id(file_id):
3141
 
                if path_tree.path2id('') == file_id:
3142
 
                    # This is the root entry, skip it
 
2873
            if path_tree and file_id in path_tree:
 
2874
                if path_tree.inventory[file_id].parent_id is None:
3143
2875
                    continue
3144
2876
            tt.version_file(file_id, conflict[1])
3145
2877
            new_conflicts.add((c_type, 'Versioned directory', conflict[1]))
3161
2893
 
3162
2894
def cook_conflicts(raw_conflicts, tt):
3163
2895
    """Generate a list of cooked conflicts, sorted by file path"""
 
2896
    from bzrlib.conflicts import Conflict
3164
2897
    conflict_iter = iter_cook_conflicts(raw_conflicts, tt)
3165
 
    return sorted(conflict_iter, key=conflicts.Conflict.sort_key)
 
2898
    return sorted(conflict_iter, key=Conflict.sort_key)
3166
2899
 
3167
2900
 
3168
2901
def iter_cook_conflicts(raw_conflicts, tt):
 
2902
    from bzrlib.conflicts import Conflict
3169
2903
    fp = FinalPaths(tt)
3170
2904
    for conflict in raw_conflicts:
3171
2905
        c_type = conflict[0]
3173
2907
        modified_path = fp.get_path(conflict[2])
3174
2908
        modified_id = tt.final_file_id(conflict[2])
3175
2909
        if len(conflict) == 3:
3176
 
            yield conflicts.Conflict.factory(
3177
 
                c_type, action=action, path=modified_path, file_id=modified_id)
 
2910
            yield Conflict.factory(c_type, action=action, path=modified_path,
 
2911
                                     file_id=modified_id)
3178
2912
 
3179
2913
        else:
3180
2914
            conflicting_path = fp.get_path(conflict[3])
3181
2915
            conflicting_id = tt.final_file_id(conflict[3])
3182
 
            yield conflicts.Conflict.factory(
3183
 
                c_type, action=action, path=modified_path,
3184
 
                file_id=modified_id,
3185
 
                conflict_path=conflicting_path,
3186
 
                conflict_file_id=conflicting_id)
 
2916
            yield Conflict.factory(c_type, action=action, path=modified_path,
 
2917
                                   file_id=modified_id,
 
2918
                                   conflict_path=conflicting_path,
 
2919
                                   conflict_file_id=conflicting_id)
3187
2920
 
3188
2921
 
3189
2922
class _FileMover(object):
3196
2929
    def rename(self, from_, to):
3197
2930
        """Rename a file from one path to another."""
3198
2931
        try:
3199
 
            os.rename(from_, to)
3200
 
        except OSError, e:
 
2932
            osutils.rename(from_, to)
 
2933
        except (IOError, OSError), e:
3201
2934
            if e.errno in (errno.EEXIST, errno.ENOTEMPTY):
3202
2935
                raise errors.FileExists(to, str(e))
3203
2936
            # normal OSError doesn't include filenames so it's hard to see where
3219
2952
        """Reverse all renames that have been performed"""
3220
2953
        for from_, to in reversed(self.past_renames):
3221
2954
            try:
3222
 
                os.rename(to, from_)
3223
 
            except OSError, e:
3224
 
                raise errors.TransformRenameFailed(to, from_, str(e), e.errno)
 
2955
                osutils.rename(to, from_)
 
2956
            except (OSError, IOError), e:
 
2957
                raise errors.TransformRenameFailed(to, from_, str(e), e.errno)                
3225
2958
        # after rollback, don't reuse _FileMover
3226
2959
        past_renames = None
3227
2960
        pending_deletions = None