~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transform.py

  • Committer: Zearin
  • Date: 2010-11-12 22:36:19 UTC
  • mto: (5570.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5572.
  • Revision ID: zearin@users.sourceforge.net-20101112223619-1i2oscfgg1xgzuqk
Continued capitalization fixes ([S]FTP, SSH).

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
23
23
    errors,
24
24
    lazy_import,
25
25
    registry,
26
 
    trace,
27
 
    tree,
28
26
    )
29
27
lazy_import.lazy_import(globals(), """
30
28
from bzrlib import (
32
30
    bencode,
33
31
    bzrdir,
34
32
    commit,
35
 
    conflicts,
36
33
    delta,
37
34
    errors,
38
35
    inventory,
39
36
    multiparent,
40
37
    osutils,
41
38
    revision as _mod_revision,
 
39
    trace,
42
40
    ui,
43
 
    urlutils,
44
41
    )
45
42
""")
46
43
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
48
45
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
49
46
                           UnableCreateSymlink)
50
47
from bzrlib.filters import filtered_output_bytes, ContentFilterContext
 
48
from bzrlib.inventory import InventoryEntry
51
49
from bzrlib.osutils import (
52
50
    delete_any,
53
51
    file_kind,
54
52
    has_symlinks,
 
53
    lexists,
55
54
    pathjoin,
56
55
    sha_file,
57
56
    splitpath,
58
57
    supports_executable,
59
 
    )
 
58
)
60
59
from bzrlib.progress import ProgressPhase
61
60
from bzrlib.symbol_versioning import (
62
 
    deprecated_function,
63
 
    deprecated_in,
64
 
    deprecated_method,
65
 
    )
 
61
        deprecated_function,
 
62
        deprecated_in,
 
63
        deprecated_method,
 
64
        )
 
65
from bzrlib.trace import mutter, warning
 
66
from bzrlib import tree
 
67
import bzrlib.ui
 
68
import bzrlib.urlutils as urlutils
66
69
 
67
70
 
68
71
ROOT_PARENT = "root-parent"
103
106
        self._new_parent = {}
104
107
        # mapping of trans_id with new contents -> new file_kind
105
108
        self._new_contents = {}
106
 
        # mapping of trans_id => (sha1 of content, stat_value)
107
 
        self._observed_sha1s = {}
108
109
        # Set of trans_ids whose contents will be removed
109
110
        self._removed_contents = set()
110
111
        # Mapping of trans_id -> new execute-bit value
129
130
            self._new_root = self.trans_id_tree_file_id(root_id)
130
131
        else:
131
132
            self._new_root = None
132
 
        # Indicator of whether the transform has been applied
 
133
        # Indictor of whether the transform has been applied
133
134
        self._done = False
134
135
        # A progress bar
135
136
        self._pb = pb
138
139
        # A counter of how many files have been renamed
139
140
        self.rename_count = 0
140
141
 
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
142
    def finalize(self):
150
143
        """Release the working tree lock, if held.
151
144
 
226
219
        This means that the old root trans-id becomes obsolete, so it is
227
220
        recommended only to invoke this after the root trans-id has become
228
221
        irrelevant.
229
 
 
230
222
        """
231
223
        new_roots = [k for k, v in self._new_parent.iteritems() if v is
232
224
                     ROOT_PARENT]
233
225
        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
226
            return
240
227
        if len(new_roots) != 1:
241
228
            raise ValueError('A tree cannot have two roots!')
243
230
            self._new_root = new_roots[0]
244
231
            return
245
232
        old_new_root = new_roots[0]
 
233
        # TODO: What to do if a old_new_root is present, but self._new_root is
 
234
        #       not listed as being removed? This code explicitly unversions
 
235
        #       the old root and versions it with the new file_id. Though that
 
236
        #       seems like an incomplete delta
 
237
 
246
238
        # 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)
 
239
        file_id = self.final_file_id(old_new_root)
251
240
        if old_new_root in self._new_id:
252
241
            self.cancel_versioning(old_new_root)
253
242
        else:
257
246
        if (self.tree_file_id(self._new_root) is not None and
258
247
            self._new_root not in self._removed_id):
259
248
            self.unversion_file(self._new_root)
260
 
        if file_id is not None:
261
 
            self.version_file(file_id, self._new_root)
 
249
        self.version_file(file_id, self._new_root)
262
250
 
263
251
        # Now move children of new root into old root directory.
264
252
        # Ensure all children are registered with the transaction, but don't
398
386
        return sorted(FinalPaths(self).get_paths(new_ids))
399
387
 
400
388
    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,
 
389
        """Get the trans_ids and paths of files needing new inv entries."""
 
390
        new_ids = set()
 
391
        for id_set in [self._new_name, self._new_parent, self._new_id,
419
392
                       self._new_executability]:
420
 
            changed_ids.update(id_set)
421
 
        # removing implies a kind change
 
393
            new_ids.update(id_set)
422
394
        changed_kind = set(self._removed_contents)
423
 
        # so does adding
424
395
        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
 
396
        changed_kind.difference_update(new_ids)
428
397
        changed_kind = (t for t in changed_kind
429
398
                        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))
 
399
        new_ids.update(changed_kind)
 
400
        return sorted(FinalPaths(self).get_paths(new_ids))
439
401
 
440
402
    def final_kind(self, trans_id):
441
403
        """Determine the final file kind, after any changes applied.
566
528
        for trans_id in self._removed_id:
567
529
            file_id = self.tree_file_id(trans_id)
568
530
            if file_id is not None:
569
 
                # XXX: This seems like something that should go via a different
570
 
                #      indirection.
571
531
                if self._tree.inventory[file_id].kind == 'directory':
572
532
                    parents.append(trans_id)
573
533
            elif self.tree_kind(trans_id) == 'directory':
668
628
            if kind is None:
669
629
                conflicts.append(('versioning no contents', trans_id))
670
630
                continue
671
 
            if not inventory.InventoryEntry.versionable_kind(kind):
 
631
            if not InventoryEntry.versionable_kind(kind):
672
632
                conflicts.append(('versioning bad kind', trans_id, kind))
673
633
        return conflicts
674
634
 
743
703
        return conflicts
744
704
 
745
705
    def _parent_type_conflicts(self, by_parent):
746
 
        """Children must have a directory parent"""
 
706
        """parents must have directory 'contents'."""
747
707
        conflicts = []
748
708
        for parent_id, children in by_parent.iteritems():
749
709
            if parent_id is ROOT_PARENT:
750
710
                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:
 
711
            if not self._any_contents(children):
757
712
                continue
758
 
            # There is at least a child, so we need an existing directory to
759
 
            # contain it.
760
713
            kind = self.final_kind(parent_id)
761
714
            if kind is None:
762
 
                # The directory will be deleted
763
715
                conflicts.append(('missing parent', parent_id))
764
716
            elif kind != "directory":
765
 
                # Meh, we need a *directory* to put something in it
766
717
                conflicts.append(('non-directory parent', parent_id))
767
718
        return conflicts
768
719
 
 
720
    def _any_contents(self, trans_ids):
 
721
        """Return true if any of the trans_ids, will have contents."""
 
722
        for trans_id in trans_ids:
 
723
            if self.final_kind(trans_id) is not None:
 
724
                return True
 
725
        return False
 
726
 
769
727
    def _set_executability(self, path, trans_id):
770
728
        """Set the executability of versioned files """
771
729
        if supports_executable():
793
751
        return trans_id
794
752
 
795
753
    def new_file(self, name, parent_id, contents, file_id=None,
796
 
                 executable=None, sha1=None):
 
754
                 executable=None):
797
755
        """Convenience method to create files.
798
756
 
799
757
        name is the name of the file to create.
806
764
        trans_id = self._new_entry(name, parent_id, file_id)
807
765
        # TODO: rather than scheduling a set_executable call,
808
766
        # have create_file create the file with the right mode.
809
 
        self.create_file(contents, trans_id, sha1=sha1)
 
767
        self.create_file(contents, trans_id)
810
768
        if executable is not None:
811
769
            self.set_executability(executable, trans_id)
812
770
        return trans_id
862
820
        """
863
821
        orphans = []
864
822
        # 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)
 
823
        for c in self.by_parent()[dir_id]:
 
824
            if self.final_file_id(c) is None:
 
825
                orphans.append(c)
873
826
            else:
874
827
                # We have a versioned file here, searching for orphans is
875
828
                # meaningless.
1194
1147
        self._deletiondir = None
1195
1148
        # A mapping of transform ids to their limbo filename
1196
1149
        self._limbo_files = {}
1197
 
        self._possibly_stale_limbo_files = set()
1198
1150
        # A mapping of transform ids to a set of the transform ids of children
1199
1151
        # that their limbo directory has
1200
1152
        self._limbo_children = {}
1213
1165
        if self._tree is None:
1214
1166
            return
1215
1167
        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?
 
1168
            entries = [(self._limbo_name(t), t, k) for t, k in
 
1169
                       self._new_contents.iteritems()]
 
1170
            entries.sort(reverse=True)
 
1171
            for path, trans_id, kind in entries:
 
1172
                delete_any(path)
1228
1173
            try:
1229
1174
                delete_any(self._limbodir)
1230
1175
            except OSError:
1279
1224
        entries from _limbo_files, because they are now stale.
1280
1225
        """
1281
1226
        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]
 
1227
            old_path = self._limbo_files.pop(trans_id)
1285
1228
            if trans_id not in self._new_contents:
1286
1229
                continue
1287
1230
            new_path = self._limbo_name(trans_id)
1288
1231
            os.rename(old_path, new_path)
1289
 
            self._possibly_stale_limbo_files.remove(old_path)
1290
1232
            for descendant in self._limbo_descendants(trans_id):
1291
1233
                desc_path = self._limbo_files[descendant]
1292
1234
                desc_path = new_path + desc_path[len(old_path):]
1299
1241
            descendants.update(self._limbo_descendants(descendant))
1300
1242
        return descendants
1301
1243
 
1302
 
    def create_file(self, contents, trans_id, mode_id=None, sha1=None):
 
1244
    def create_file(self, contents, trans_id, mode_id=None):
1303
1245
        """Schedule creation of a new file.
1304
1246
 
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.
 
1247
        See also new_file.
 
1248
 
 
1249
        Contents is an iterator of strings, all of which will be written
 
1250
        to the target destination.
 
1251
 
 
1252
        New file takes the permissions of any existing file with that id,
 
1253
        unless mode_id is specified.
1315
1254
        """
1316
1255
        name = self._limbo_name(trans_id)
1317
1256
        f = open(name, 'wb')
1318
1257
        try:
1319
 
            unique_add(self._new_contents, trans_id, 'file')
 
1258
            try:
 
1259
                unique_add(self._new_contents, trans_id, 'file')
 
1260
            except:
 
1261
                # Clean up the file, it never got registered so
 
1262
                # TreeTransform.finalize() won't clean it up.
 
1263
                f.close()
 
1264
                os.unlink(name)
 
1265
                raise
 
1266
 
1320
1267
            f.writelines(contents)
1321
1268
        finally:
1322
1269
            f.close()
1323
1270
        self._set_mtime(name)
1324
1271
        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
1272
 
1331
1273
    def _read_file_chunks(self, trans_id):
1332
1274
        cur_file = open(self._limbo_name(trans_id), 'rb')
1391
1333
    def cancel_creation(self, trans_id):
1392
1334
        """Cancel the creation of new file contents."""
1393
1335
        del self._new_contents[trans_id]
1394
 
        if trans_id in self._observed_sha1s:
1395
 
            del self._observed_sha1s[trans_id]
1396
1336
        children = self._limbo_children.get(trans_id)
1397
1337
        # if this is a limbo directory with children, move them before removing
1398
1338
        # the directory
1414
1354
        if orphan_policy is None:
1415
1355
            orphan_policy = default_policy
1416
1356
        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))
 
1357
            trace.warning('%s (from %s) is not a known policy, defaulting to %s'
 
1358
                          % (orphan_policy, conf_var_name, default_policy))
1419
1359
            orphan_policy = default_policy
1420
1360
        handle_orphan = orphaning_registry.get(orphan_policy)
1421
1361
        handle_orphan(self, trans_id, parent_id)
1728
1668
        """
1729
1669
        if not no_conflicts:
1730
1670
            self._check_malformed()
1731
 
        child_pb = ui.ui_factory.nested_progress_bar()
 
1671
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1732
1672
        try:
1733
1673
            if precomputed_delta is None:
1734
1674
                child_pb.update('Apply phase', 0, 2)
1754
1694
        finally:
1755
1695
            child_pb.finished()
1756
1696
        self._tree.apply_inventory_delta(inventory_delta)
1757
 
        self._apply_observed_sha1s()
1758
1697
        self._done = True
1759
1698
        self.finalize()
1760
1699
        return _TransformResults(modified_paths, self.rename_count)
1762
1701
    def _generate_inventory_delta(self):
1763
1702
        """Generate an inventory delta for the current transform."""
1764
1703
        inventory_delta = []
1765
 
        child_pb = ui.ui_factory.nested_progress_bar()
 
1704
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1766
1705
        new_paths = self._inventory_altered()
1767
1706
        total_entries = len(new_paths) + len(self._removed_id)
1768
1707
        try:
1830
1769
        """
1831
1770
        tree_paths = list(self._tree_path_ids.iteritems())
1832
1771
        tree_paths.sort(reverse=True)
1833
 
        child_pb = ui.ui_factory.nested_progress_bar()
 
1772
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1834
1773
        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
 
1774
            for num, data in enumerate(tree_paths):
 
1775
                path, trans_id = data
1839
1776
                child_pb.update('removing file', num, len(tree_paths))
1840
1777
                full_path = self._tree.abspath(path)
1841
1778
                if trans_id in self._removed_contents:
1867
1804
        modified_paths = []
1868
1805
        new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1869
1806
                                 new_paths)
1870
 
        child_pb = ui.ui_factory.nested_progress_bar()
 
1807
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1871
1808
        try:
1872
1809
            for num, (path, trans_id) in enumerate(new_paths):
1873
1810
                if (num % 10) == 0:
1882
1819
                            raise
1883
1820
                    else:
1884
1821
                        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
1822
                if (trans_id in self._new_contents or
1889
1823
                    self.path_changed(trans_id)):
1890
1824
                    if trans_id in self._new_contents:
1891
1825
                        modified_paths.append(full_path)
1892
1826
                if trans_id in self._new_executability:
1893
1827
                    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
1828
        finally:
1899
1829
            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
1830
        self._new_contents.clear()
1906
1831
        return modified_paths
1907
1832
 
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
1833
 
1932
1834
class TransformPreview(DiskTreeTransform):
1933
1835
    """A TreeTransform for generating preview trees.
1949
1851
        path = self._tree_id_paths.get(trans_id)
1950
1852
        if path is None:
1951
1853
            return None
1952
 
        kind = self._tree.path_content_summary(path)[0]
1953
 
        if kind == 'missing':
1954
 
            kind = None
1955
 
        return kind
 
1854
        file_id = self._tree.path2id(path)
 
1855
        try:
 
1856
            return self._tree.kind(file_id)
 
1857
        except errors.NoSuchFile:
 
1858
            return None
1956
1859
 
1957
1860
    def _set_mode(self, trans_id, mode_id, typefunc):
1958
1861
        """Set the mode of new file contents.
1982
1885
        raise NotImplementedError(self.new_orphan)
1983
1886
 
1984
1887
 
1985
 
class _PreviewTree(tree.InventoryTree):
 
1888
class _PreviewTree(tree.Tree):
1986
1889
    """Partial implementation of Tree to support show_diff_trees"""
1987
1890
 
1988
1891
    def __init__(self, transform):
2017
1920
                yield self._get_repository().revision_tree(revision_id)
2018
1921
 
2019
1922
    def _get_file_revision(self, file_id, vf, tree_revision):
2020
 
        parent_keys = [(file_id, t.get_file_revision(file_id)) for t in
 
1923
        parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
2021
1924
                       self._iter_parent_trees()]
2022
1925
        vf.add_lines((file_id, tree_revision), parent_keys,
2023
1926
                     self.get_file_lines(file_id))
2027
1930
            vf.fallback_versionedfiles.append(base_vf)
2028
1931
        return tree_revision
2029
1932
 
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)
 
1933
    def _stat_limbo_file(self, file_id):
 
1934
        trans_id = self._transform.trans_id_file_id(file_id)
2033
1935
        name = self._transform._limbo_name(trans_id)
2034
1936
        return os.lstat(name)
2035
1937
 
2250
2152
 
2251
2153
    def get_file_size(self, file_id):
2252
2154
        """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
2155
        if self.kind(file_id) == 'file':
2260
2156
            return self._transform._tree.get_file_size(file_id)
2261
2157
        else:
2289
2185
            except errors.NoSuchId:
2290
2186
                return False
2291
2187
 
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
2188
    def path_content_summary(self, path):
2302
2189
        trans_id = self._path2trans_id(path)
2303
2190
        tt = self._transform
2391
2278
                                   self.get_file(file_id).readlines(),
2392
2279
                                   default_revision)
2393
2280
 
2394
 
    def get_symlink_target(self, file_id, path=None):
 
2281
    def get_symlink_target(self, file_id):
2395
2282
        """See Tree.get_symlink_target"""
2396
2283
        if not self._content_change(file_id):
2397
2284
            return self._transform._tree.get_symlink_target(file_id)
2535
2422
        if num > 0:  # more than just a root
2536
2423
            raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
2537
2424
    file_trans_id = {}
2538
 
    top_pb = ui.ui_factory.nested_progress_bar()
 
2425
    top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2539
2426
    pp = ProgressPhase("Build phase", 2, top_pb)
2540
2427
    if tree.inventory.root is not None:
2541
2428
        # This is kind of a hack: we should be altering the root
2554
2441
        pp.next_phase()
2555
2442
        file_trans_id[wt.get_root_id()] = \
2556
2443
            tt.trans_id_tree_file_id(wt.get_root_id())
2557
 
        pb = ui.ui_factory.nested_progress_bar()
 
2444
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
2558
2445
        try:
2559
2446
            deferred_contents = []
2560
2447
            num = 0
2607
2494
                    executable = tree.is_executable(file_id, tree_path)
2608
2495
                    if executable:
2609
2496
                        tt.set_executability(executable, trans_id)
2610
 
                    trans_data = (trans_id, tree_path, entry.text_sha1)
 
2497
                    trans_data = (trans_id, tree_path)
2611
2498
                    deferred_contents.append((file_id, trans_data))
2612
2499
                else:
2613
2500
                    file_trans_id[file_id] = new_by_entry(tt, entry, parent_id,
2629
2516
            precomputed_delta = None
2630
2517
        conflicts = cook_conflicts(raw_conflicts, tt)
2631
2518
        for conflict in conflicts:
2632
 
            trace.warning(unicode(conflict))
 
2519
            warning(conflict)
2633
2520
        try:
2634
2521
            wt.add_conflicts(conflicts)
2635
2522
        except errors.UnsupportedOperation:
2658
2545
        unchanged = dict(unchanged)
2659
2546
        new_desired_files = []
2660
2547
        count = 0
2661
 
        for file_id, (trans_id, tree_path, text_sha1) in desired_files:
 
2548
        for file_id, (trans_id, tree_path) in desired_files:
2662
2549
            accelerator_path = unchanged.get(file_id)
2663
2550
            if accelerator_path is None:
2664
 
                new_desired_files.append((file_id,
2665
 
                    (trans_id, tree_path, text_sha1)))
 
2551
                new_desired_files.append((file_id, (trans_id, tree_path)))
2666
2552
                continue
2667
2553
            pb.update('Adding file contents', count + offset, total)
2668
2554
            if hardlink:
2675
2561
                    contents = filtered_output_bytes(contents, filters,
2676
2562
                        ContentFilterContext(tree_path, tree))
2677
2563
                try:
2678
 
                    tt.create_file(contents, trans_id, sha1=text_sha1)
 
2564
                    tt.create_file(contents, trans_id)
2679
2565
                finally:
2680
2566
                    try:
2681
2567
                        contents.close()
2684
2570
                        pass
2685
2571
            count += 1
2686
2572
        offset += count
2687
 
    for count, ((trans_id, tree_path, text_sha1), contents) in enumerate(
 
2573
    for count, ((trans_id, tree_path), contents) in enumerate(
2688
2574
            tree.iter_files_bytes(new_desired_files)):
2689
2575
        if wt.supports_content_filtering():
2690
2576
            filters = wt._content_filter_stack(tree_path)
2691
2577
            contents = filtered_output_bytes(contents, filters,
2692
2578
                ContentFilterContext(tree_path, tree))
2693
 
        tt.create_file(contents, trans_id, sha1=text_sha1)
 
2579
        tt.create_file(contents, trans_id)
2694
2580
        pb.update('Adding file contents', count + offset, total)
2695
2581
 
2696
2582
 
2871
2757
                unversioned_filter=working_tree.is_ignored)
2872
2758
            delta.report_changes(tt.iter_changes(), change_reporter)
2873
2759
        for conflict in conflicts:
2874
 
            trace.warning(unicode(conflict))
 
2760
            warning(conflict)
2875
2761
        pp.next_phase()
2876
2762
        tt.apply()
2877
2763
        working_tree.set_merge_modified(merge_modified)
2885
2771
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
2886
2772
                              backups, pp, basis_tree=None,
2887
2773
                              merge_modified=None):
2888
 
    child_pb = ui.ui_factory.nested_progress_bar()
 
2774
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2889
2775
    try:
2890
2776
        if merge_modified is None:
2891
2777
            merge_modified = working_tree.merge_modified()
2894
2780
                                      merge_modified, basis_tree)
2895
2781
    finally:
2896
2782
        child_pb.finished()
2897
 
    child_pb = ui.ui_factory.nested_progress_bar()
 
2783
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2898
2784
    try:
2899
2785
        raw_conflicts = resolve_conflicts(tt, child_pb,
2900
2786
            lambda t, c: conflict_pass(t, c, target_tree))
2908
2794
                 backups, merge_modified, basis_tree=None):
2909
2795
    if basis_tree is not None:
2910
2796
        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,
 
2797
    change_list = target_tree.iter_changes(working_tree,
2916
2798
        specific_files=specific_files, pb=pb)
2917
2799
    if target_tree.get_root_id() is None:
2918
2800
        skip_root = True
2922
2804
        deferred_files = []
2923
2805
        for id_num, (file_id, path, changed_content, versioned, parent, name,
2924
2806
                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:
 
2807
            if skip_root and file_id[0] is not None and parent[0] is None:
2932
2808
                continue
2933
2809
            trans_id = tt.trans_id_file_id(file_id)
2934
2810
            mode_id = None
2935
2811
            if changed_content:
2936
2812
                keep_content = False
2937
 
                if wt_kind == 'file' and (backups or target_kind is None):
 
2813
                if kind[0] == 'file' and (backups or kind[1] is None):
2938
2814
                    wt_sha1 = working_tree.get_file_sha1(file_id)
2939
2815
                    if merge_modified.get(file_id) != wt_sha1:
2940
2816
                        # acquire the basis tree lazily to prevent the
2943
2819
                        if basis_tree is None:
2944
2820
                            basis_tree = working_tree.basis_tree()
2945
2821
                            basis_tree.lock_read()
2946
 
                        if basis_tree.has_id(file_id):
 
2822
                        if file_id in basis_tree:
2947
2823
                            if wt_sha1 != basis_tree.get_file_sha1(file_id):
2948
2824
                                keep_content = True
2949
 
                        elif target_kind is None and not target_versioned:
 
2825
                        elif kind[1] is None and not versioned[1]:
2950
2826
                            keep_content = True
2951
 
                if wt_kind is not None:
 
2827
                if kind[0] is not None:
2952
2828
                    if not keep_content:
2953
2829
                        tt.delete_contents(trans_id)
2954
 
                    elif target_kind is not None:
2955
 
                        parent_trans_id = tt.trans_id_file_id(wt_parent)
 
2830
                    elif kind[1] is not None:
 
2831
                        parent_trans_id = tt.trans_id_file_id(parent[0])
2956
2832
                        backup_name = tt._available_backup_name(
2957
 
                            wt_name, parent_trans_id)
 
2833
                            name[0], parent_trans_id)
2958
2834
                        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:
 
2835
                        new_trans_id = tt.create_path(name[0], parent_trans_id)
 
2836
                        if versioned == (True, True):
2961
2837
                            tt.unversion_file(trans_id)
2962
2838
                            tt.version_file(file_id, new_trans_id)
2963
2839
                        # New contents should have the same unix perms as old
2964
2840
                        # contents
2965
2841
                        mode_id = trans_id
2966
2842
                        trans_id = new_trans_id
2967
 
                if target_kind in ('directory', 'tree-reference'):
 
2843
                if kind[1] in ('directory', 'tree-reference'):
2968
2844
                    tt.create_directory(trans_id)
2969
 
                    if target_kind == 'tree-reference':
 
2845
                    if kind[1] == 'tree-reference':
2970
2846
                        revision = target_tree.get_reference_revision(file_id,
2971
 
                                                                      target_path)
 
2847
                                                                      path[1])
2972
2848
                        tt.set_tree_reference(revision, trans_id)
2973
 
                elif target_kind == 'symlink':
 
2849
                elif kind[1] == 'symlink':
2974
2850
                    tt.create_symlink(target_tree.get_symlink_target(file_id),
2975
2851
                                      trans_id)
2976
 
                elif target_kind == 'file':
 
2852
                elif kind[1] == 'file':
2977
2853
                    deferred_files.append((file_id, (trans_id, mode_id)))
2978
2854
                    if basis_tree is None:
2979
2855
                        basis_tree = working_tree.basis_tree()
2980
2856
                        basis_tree.lock_read()
2981
2857
                    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)):
 
2858
                    if (file_id in basis_tree and new_sha1 ==
 
2859
                        basis_tree.get_file_sha1(file_id)):
2984
2860
                        if file_id in merge_modified:
2985
2861
                            del merge_modified[file_id]
2986
2862
                    else:
2987
2863
                        merge_modified[file_id] = new_sha1
2988
2864
 
2989
2865
                    # 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:
 
2866
                    if keep_content and executable[0] == executable[1]:
 
2867
                        tt.set_executability(executable[1], trans_id)
 
2868
                elif kind[1] is not None:
 
2869
                    raise AssertionError(kind[1])
 
2870
            if versioned == (False, True):
2995
2871
                tt.version_file(file_id, trans_id)
2996
 
            if wt_versioned and not target_versioned:
 
2872
            if versioned == (True, False):
2997
2873
                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:
 
2874
            if (name[1] is not None and
 
2875
                (name[0] != name[1] or parent[0] != parent[1])):
 
2876
                if name[1] == '' and parent[1] is None:
3001
2877
                    parent_trans = ROOT_PARENT
3002
2878
                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)
 
2879
                    parent_trans = tt.trans_id_file_id(parent[1])
 
2880
                if parent[0] is None and versioned[0]:
 
2881
                    tt.adjust_root_path(name[1], parent_trans)
3006
2882
                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)
 
2883
                    tt.adjust_path(name[1], parent_trans, trans_id)
 
2884
            if executable[0] != executable[1] and kind[1] == "file":
 
2885
                tt.set_executability(executable[1], trans_id)
3010
2886
        if working_tree.supports_content_filtering():
3011
2887
            for index, ((trans_id, mode_id), bytes) in enumerate(
3012
2888
                target_tree.iter_files_bytes(deferred_files)):
3115
2991
                        file_id = tt.final_file_id(trans_id)
3116
2992
                        if file_id is None:
3117
2993
                            file_id = tt.inactive_file_id(trans_id)
3118
 
                        _, entry = path_tree.iter_entries_by_dir(
3119
 
                            [file_id]).next()
 
2994
                        entry = path_tree.inventory[file_id]
3120
2995
                        # special-case the other tree root (move its
3121
2996
                        # children to current root)
3122
2997
                        if entry.parent_id is None:
3137
3012
        elif c_type == 'unversioned parent':
3138
3013
            file_id = tt.inactive_file_id(conflict[1])
3139
3014
            # 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
 
3015
            if path_tree and file_id in path_tree:
 
3016
                if path_tree.inventory[file_id].parent_id is None:
3143
3017
                    continue
3144
3018
            tt.version_file(file_id, conflict[1])
3145
3019
            new_conflicts.add((c_type, 'Versioned directory', conflict[1]))
3161
3035
 
3162
3036
def cook_conflicts(raw_conflicts, tt):
3163
3037
    """Generate a list of cooked conflicts, sorted by file path"""
 
3038
    from bzrlib.conflicts import Conflict
3164
3039
    conflict_iter = iter_cook_conflicts(raw_conflicts, tt)
3165
 
    return sorted(conflict_iter, key=conflicts.Conflict.sort_key)
 
3040
    return sorted(conflict_iter, key=Conflict.sort_key)
3166
3041
 
3167
3042
 
3168
3043
def iter_cook_conflicts(raw_conflicts, tt):
 
3044
    from bzrlib.conflicts import Conflict
3169
3045
    fp = FinalPaths(tt)
3170
3046
    for conflict in raw_conflicts:
3171
3047
        c_type = conflict[0]
3173
3049
        modified_path = fp.get_path(conflict[2])
3174
3050
        modified_id = tt.final_file_id(conflict[2])
3175
3051
        if len(conflict) == 3:
3176
 
            yield conflicts.Conflict.factory(
3177
 
                c_type, action=action, path=modified_path, file_id=modified_id)
 
3052
            yield Conflict.factory(c_type, action=action, path=modified_path,
 
3053
                                     file_id=modified_id)
3178
3054
 
3179
3055
        else:
3180
3056
            conflicting_path = fp.get_path(conflict[3])
3181
3057
            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)
 
3058
            yield Conflict.factory(c_type, action=action, path=modified_path,
 
3059
                                   file_id=modified_id,
 
3060
                                   conflict_path=conflicting_path,
 
3061
                                   conflict_file_id=conflicting_id)
3187
3062
 
3188
3063
 
3189
3064
class _FileMover(object):