/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/transform.py

  • Committer: Vincent Ladeuil
  • Date: 2011-08-16 13:12:40 UTC
  • mfrom: (6071 +trunk)
  • mto: This revision was merged to the branch mainline in revision 6076.
  • Revision ID: v.ladeuil+lp@free.fr-20110816131240-gcyn9cik86dxwgz3
Merge into trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
from stat import S_ISREG, S_IEXEC
20
20
import time
21
21
 
22
 
import bzrlib
23
22
from bzrlib import (
24
23
    errors,
25
24
    lazy_import,
26
25
    registry,
 
26
    trace,
27
27
    tree,
28
28
    )
29
29
lazy_import.lazy_import(globals(), """
32
32
    bencode,
33
33
    bzrdir,
34
34
    commit,
 
35
    conflicts,
35
36
    delta,
36
37
    errors,
37
38
    inventory,
38
39
    multiparent,
39
40
    osutils,
40
41
    revision as _mod_revision,
41
 
    trace,
42
42
    ui,
43
43
    urlutils,
44
44
    )
48
48
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
49
49
                           UnableCreateSymlink)
50
50
from bzrlib.filters import filtered_output_bytes, ContentFilterContext
51
 
from bzrlib.inventory import InventoryEntry
52
51
from bzrlib.osutils import (
53
52
    delete_any,
54
53
    file_kind,
64
63
    deprecated_in,
65
64
    deprecated_method,
66
65
    )
67
 
from bzrlib.trace import warning
68
66
 
69
67
 
70
68
ROOT_PARENT = "root-parent"
105
103
        self._new_parent = {}
106
104
        # mapping of trans_id with new contents -> new file_kind
107
105
        self._new_contents = {}
 
106
        # mapping of trans_id => (sha1 of content, stat_value)
 
107
        self._observed_sha1s = {}
108
108
        # Set of trans_ids whose contents will be removed
109
109
        self._removed_contents = set()
110
110
        # Mapping of trans_id -> new execute-bit value
138
138
        # A counter of how many files have been renamed
139
139
        self.rename_count = 0
140
140
 
 
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
 
141
149
    def finalize(self):
142
150
        """Release the working tree lock, if held.
143
151
 
218
226
        This means that the old root trans-id becomes obsolete, so it is
219
227
        recommended only to invoke this after the root trans-id has become
220
228
        irrelevant.
 
229
 
221
230
        """
222
231
        new_roots = [k for k, v in self._new_parent.iteritems() if v is
223
232
                     ROOT_PARENT]
229
238
            self._new_root = new_roots[0]
230
239
            return
231
240
        old_new_root = new_roots[0]
232
 
        # TODO: What to do if a old_new_root is present, but self._new_root is
233
 
        #       not listed as being removed? This code explicitly unversions
234
 
        #       the old root and versions it with the new file_id. Though that
235
 
        #       seems like an incomplete delta
236
 
 
237
241
        # unversion the new root's directory.
238
 
        file_id = self.final_file_id(old_new_root)
 
242
        if self.final_kind(self._new_root) is None:
 
243
            file_id = self.final_file_id(old_new_root)
 
244
        else:
 
245
            file_id = self.final_file_id(self._new_root)
239
246
        if old_new_root in self._new_id:
240
247
            self.cancel_versioning(old_new_root)
241
248
        else:
245
252
        if (self.tree_file_id(self._new_root) is not None and
246
253
            self._new_root not in self._removed_id):
247
254
            self.unversion_file(self._new_root)
248
 
        self.version_file(file_id, self._new_root)
 
255
        if file_id is not None:
 
256
            self.version_file(file_id, self._new_root)
249
257
 
250
258
        # Now move children of new root into old root directory.
251
259
        # Ensure all children are registered with the transaction, but don't
385
393
        return sorted(FinalPaths(self).get_paths(new_ids))
386
394
 
387
395
    def _inventory_altered(self):
388
 
        """Get the trans_ids and paths of files needing new inv entries."""
389
 
        new_ids = set()
390
 
        for id_set in [self._new_name, self._new_parent, self._new_id,
 
396
        """Determine which trans_ids need new Inventory entries.
 
397
 
 
398
        An new entry is needed when anything that would be reflected by an
 
399
        inventory entry changes, including file name, file_id, parent file_id,
 
400
        file kind, and the execute bit.
 
401
 
 
402
        Some care is taken to return entries with real changes, not cases
 
403
        where the value is deleted and then restored to its original value,
 
404
        but some actually unchanged values may be returned.
 
405
 
 
406
        :returns: A list of (path, trans_id) for all items requiring an
 
407
            inventory change. Ordered by path.
 
408
        """
 
409
        changed_ids = set()
 
410
        # Find entries whose file_ids are new (or changed).
 
411
        new_file_id = set(t for t in self._new_id
 
412
                          if self._new_id[t] != self.tree_file_id(t))
 
413
        for id_set in [self._new_name, self._new_parent, new_file_id,
391
414
                       self._new_executability]:
392
 
            new_ids.update(id_set)
 
415
            changed_ids.update(id_set)
 
416
        # removing implies a kind change
393
417
        changed_kind = set(self._removed_contents)
 
418
        # so does adding
394
419
        changed_kind.intersection_update(self._new_contents)
395
 
        changed_kind.difference_update(new_ids)
 
420
        # Ignore entries that are already known to have changed.
 
421
        changed_kind.difference_update(changed_ids)
 
422
        #  to keep only the truly changed ones
396
423
        changed_kind = (t for t in changed_kind
397
424
                        if self.tree_kind(t) != self.final_kind(t))
398
 
        new_ids.update(changed_kind)
399
 
        return sorted(FinalPaths(self).get_paths(new_ids))
 
425
        # all kind changes will alter the inventory
 
426
        changed_ids.update(changed_kind)
 
427
        # To find entries with changed parent_ids, find parents which existed,
 
428
        # but changed file_id.
 
429
        changed_file_id = set(t for t in new_file_id if t in self._removed_id)
 
430
        # Now add all their children to the set.
 
431
        for parent_trans_id in new_file_id:
 
432
            changed_ids.update(self.iter_tree_children(parent_trans_id))
 
433
        return sorted(FinalPaths(self).get_paths(changed_ids))
400
434
 
401
435
    def final_kind(self, trans_id):
402
436
        """Determine the final file kind, after any changes applied.
629
663
            if kind is None:
630
664
                conflicts.append(('versioning no contents', trans_id))
631
665
                continue
632
 
            if not InventoryEntry.versionable_kind(kind):
 
666
            if not inventory.InventoryEntry.versionable_kind(kind):
633
667
                conflicts.append(('versioning bad kind', trans_id, kind))
634
668
        return conflicts
635
669
 
754
788
        return trans_id
755
789
 
756
790
    def new_file(self, name, parent_id, contents, file_id=None,
757
 
                 executable=None):
 
791
                 executable=None, sha1=None):
758
792
        """Convenience method to create files.
759
793
 
760
794
        name is the name of the file to create.
767
801
        trans_id = self._new_entry(name, parent_id, file_id)
768
802
        # TODO: rather than scheduling a set_executable call,
769
803
        # have create_file create the file with the right mode.
770
 
        self.create_file(contents, trans_id)
 
804
        self.create_file(contents, trans_id, sha1=sha1)
771
805
        if executable is not None:
772
806
            self.set_executability(executable, trans_id)
773
807
        return trans_id
1155
1189
        self._deletiondir = None
1156
1190
        # A mapping of transform ids to their limbo filename
1157
1191
        self._limbo_files = {}
 
1192
        self._possibly_stale_limbo_files = set()
1158
1193
        # A mapping of transform ids to a set of the transform ids of children
1159
1194
        # that their limbo directory has
1160
1195
        self._limbo_children = {}
1173
1208
        if self._tree is None:
1174
1209
            return
1175
1210
        try:
1176
 
            entries = [(self._limbo_name(t), t, k) for t, k in
1177
 
                       self._new_contents.iteritems()]
1178
 
            entries.sort(reverse=True)
1179
 
            for path, trans_id, kind in entries:
1180
 
                delete_any(path)
 
1211
            limbo_paths = self._limbo_files.values() + list(
 
1212
                self._possibly_stale_limbo_files)
 
1213
            limbo_paths = sorted(limbo_paths, reverse=True)
 
1214
            for path in limbo_paths:
 
1215
                try:
 
1216
                    delete_any(path)
 
1217
                except OSError, e:
 
1218
                    if e.errno != errno.ENOENT:
 
1219
                        raise
 
1220
                    # XXX: warn? perhaps we just got interrupted at an
 
1221
                    # inconvenient moment, but perhaps files are disappearing
 
1222
                    # from under us?
1181
1223
            try:
1182
1224
                delete_any(self._limbodir)
1183
1225
            except OSError:
1232
1274
        entries from _limbo_files, because they are now stale.
1233
1275
        """
1234
1276
        for trans_id in trans_ids:
1235
 
            old_path = self._limbo_files.pop(trans_id)
 
1277
            old_path = self._limbo_files[trans_id]
 
1278
            self._possibly_stale_limbo_files.add(old_path)
 
1279
            del self._limbo_files[trans_id]
1236
1280
            if trans_id not in self._new_contents:
1237
1281
                continue
1238
1282
            new_path = self._limbo_name(trans_id)
1239
1283
            os.rename(old_path, new_path)
 
1284
            self._possibly_stale_limbo_files.remove(old_path)
1240
1285
            for descendant in self._limbo_descendants(trans_id):
1241
1286
                desc_path = self._limbo_files[descendant]
1242
1287
                desc_path = new_path + desc_path[len(old_path):]
1249
1294
            descendants.update(self._limbo_descendants(descendant))
1250
1295
        return descendants
1251
1296
 
1252
 
    def create_file(self, contents, trans_id, mode_id=None):
 
1297
    def create_file(self, contents, trans_id, mode_id=None, sha1=None):
1253
1298
        """Schedule creation of a new file.
1254
1299
 
1255
 
        See also new_file.
1256
 
 
1257
 
        Contents is an iterator of strings, all of which will be written
1258
 
        to the target destination.
1259
 
 
1260
 
        New file takes the permissions of any existing file with that id,
1261
 
        unless mode_id is specified.
 
1300
        :seealso: new_file.
 
1301
 
 
1302
        :param contents: an iterator of strings, all of which will be written
 
1303
            to the target destination.
 
1304
        :param trans_id: TreeTransform handle
 
1305
        :param mode_id: If not None, force the mode of the target file to match
 
1306
            the mode of the object referenced by mode_id.
 
1307
            Otherwise, we will try to preserve mode bits of an existing file.
 
1308
        :param sha1: If the sha1 of this content is already known, pass it in.
 
1309
            We can use it to prevent future sha1 computations.
1262
1310
        """
1263
1311
        name = self._limbo_name(trans_id)
1264
1312
        f = open(name, 'wb')
1265
1313
        try:
1266
 
            try:
1267
 
                unique_add(self._new_contents, trans_id, 'file')
1268
 
            except:
1269
 
                # Clean up the file, it never got registered so
1270
 
                # TreeTransform.finalize() won't clean it up.
1271
 
                f.close()
1272
 
                os.unlink(name)
1273
 
                raise
1274
 
 
 
1314
            unique_add(self._new_contents, trans_id, 'file')
1275
1315
            f.writelines(contents)
1276
1316
        finally:
1277
1317
            f.close()
1278
1318
        self._set_mtime(name)
1279
1319
        self._set_mode(trans_id, mode_id, S_ISREG)
 
1320
        # It is unfortunate we have to use lstat instead of fstat, but we just
 
1321
        # used utime and chmod on the file, so we need the accurate final
 
1322
        # details.
 
1323
        if sha1 is not None:
 
1324
            self._observed_sha1s[trans_id] = (sha1, osutils.lstat(name))
1280
1325
 
1281
1326
    def _read_file_chunks(self, trans_id):
1282
1327
        cur_file = open(self._limbo_name(trans_id), 'rb')
1341
1386
    def cancel_creation(self, trans_id):
1342
1387
        """Cancel the creation of new file contents."""
1343
1388
        del self._new_contents[trans_id]
 
1389
        if trans_id in self._observed_sha1s:
 
1390
            del self._observed_sha1s[trans_id]
1344
1391
        children = self._limbo_children.get(trans_id)
1345
1392
        # if this is a limbo directory with children, move them before removing
1346
1393
        # the directory
1362
1409
        if orphan_policy is None:
1363
1410
            orphan_policy = default_policy
1364
1411
        if orphan_policy not in orphaning_registry:
1365
 
            trace.warning('%s (from %s) is not a known policy, defaulting to %s'
1366
 
                          % (orphan_policy, conf_var_name, default_policy))
 
1412
            trace.warning('%s (from %s) is not a known policy, defaulting '
 
1413
                'to %s' % (orphan_policy, conf_var_name, default_policy))
1367
1414
            orphan_policy = default_policy
1368
1415
        handle_orphan = orphaning_registry.get(orphan_policy)
1369
1416
        handle_orphan(self, trans_id, parent_id)
1701
1748
                mover.apply_deletions()
1702
1749
        finally:
1703
1750
            child_pb.finished()
 
1751
        if self.final_file_id(self.root) is None:
 
1752
            inventory_delta = [e for e in inventory_delta if e[0] != '']
1704
1753
        self._tree.apply_inventory_delta(inventory_delta)
 
1754
        self._apply_observed_sha1s()
1705
1755
        self._done = True
1706
1756
        self.finalize()
1707
1757
        return _TransformResults(modified_paths, self.rename_count)
1779
1829
        tree_paths.sort(reverse=True)
1780
1830
        child_pb = ui.ui_factory.nested_progress_bar()
1781
1831
        try:
1782
 
            for num, data in enumerate(tree_paths):
1783
 
                path, trans_id = data
 
1832
            for num, (path, trans_id) in enumerate(tree_paths):
 
1833
                # do not attempt to move root into a subdirectory of itself.
 
1834
                if path == '':
 
1835
                    continue
1784
1836
                child_pb.update('removing file', num, len(tree_paths))
1785
1837
                full_path = self._tree.abspath(path)
1786
1838
                if trans_id in self._removed_contents:
1827
1879
                            raise
1828
1880
                    else:
1829
1881
                        self.rename_count += 1
 
1882
                    # TODO: if trans_id in self._observed_sha1s, we should
 
1883
                    #       re-stat the final target, since ctime will be
 
1884
                    #       updated by the change.
1830
1885
                if (trans_id in self._new_contents or
1831
1886
                    self.path_changed(trans_id)):
1832
1887
                    if trans_id in self._new_contents:
1833
1888
                        modified_paths.append(full_path)
1834
1889
                if trans_id in self._new_executability:
1835
1890
                    self._set_executability(path, trans_id)
 
1891
                if trans_id in self._observed_sha1s:
 
1892
                    o_sha1, o_st_val = self._observed_sha1s[trans_id]
 
1893
                    st = osutils.lstat(full_path)
 
1894
                    self._observed_sha1s[trans_id] = (o_sha1, st)
1836
1895
        finally:
1837
1896
            child_pb.finished()
 
1897
        for path, trans_id in new_paths:
 
1898
            # new_paths includes stuff like workingtree conflicts. Only the
 
1899
            # stuff in new_contents actually comes from limbo.
 
1900
            if trans_id in self._limbo_files:
 
1901
                del self._limbo_files[trans_id]
1838
1902
        self._new_contents.clear()
1839
1903
        return modified_paths
1840
1904
 
 
1905
    def _apply_observed_sha1s(self):
 
1906
        """After we have finished renaming everything, update observed sha1s
 
1907
 
 
1908
        This has to be done after self._tree.apply_inventory_delta, otherwise
 
1909
        it doesn't know anything about the files we are updating. Also, we want
 
1910
        to do this as late as possible, so that most entries end up cached.
 
1911
        """
 
1912
        # TODO: this doesn't update the stat information for directories. So
 
1913
        #       the first 'bzr status' will still need to rewrite
 
1914
        #       .bzr/checkout/dirstate. However, we at least don't need to
 
1915
        #       re-read all of the files.
 
1916
        # TODO: If the operation took a while, we could do a time.sleep(3) here
 
1917
        #       to allow the clock to tick over and ensure we won't have any
 
1918
        #       problems. (we could observe start time, and finish time, and if
 
1919
        #       it is less than eg 10% overhead, add a sleep call.)
 
1920
        paths = FinalPaths(self)
 
1921
        for trans_id, observed in self._observed_sha1s.iteritems():
 
1922
            path = paths.get_path(trans_id)
 
1923
            # We could get the file_id, but dirstate prefers to use the path
 
1924
            # anyway, and it is 'cheaper' to determine.
 
1925
            # file_id = self._new_id[trans_id]
 
1926
            self._tree._observed_sha1(None, path, observed)
 
1927
 
1841
1928
 
1842
1929
class TransformPreview(DiskTreeTransform):
1843
1930
    """A TreeTransform for generating preview trees.
1859
1946
        path = self._tree_id_paths.get(trans_id)
1860
1947
        if path is None:
1861
1948
            return None
1862
 
        file_id = self._tree.path2id(path)
1863
 
        try:
1864
 
            return self._tree.kind(file_id)
1865
 
        except errors.NoSuchFile:
1866
 
            return None
 
1949
        kind = self._tree.path_content_summary(path)[0]
 
1950
        if kind == 'missing':
 
1951
            kind = None
 
1952
        return kind
1867
1953
 
1868
1954
    def _set_mode(self, trans_id, mode_id, typefunc):
1869
1955
        """Set the mode of new file contents.
1893
1979
        raise NotImplementedError(self.new_orphan)
1894
1980
 
1895
1981
 
1896
 
class _PreviewTree(tree.Tree):
 
1982
class _PreviewTree(tree.InventoryTree):
1897
1983
    """Partial implementation of Tree to support show_diff_trees"""
1898
1984
 
1899
1985
    def __init__(self, transform):
1928
2014
                yield self._get_repository().revision_tree(revision_id)
1929
2015
 
1930
2016
    def _get_file_revision(self, file_id, vf, tree_revision):
1931
 
        parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
 
2017
        parent_keys = [(file_id, t.get_file_revision(file_id)) for t in
1932
2018
                       self._iter_parent_trees()]
1933
2019
        vf.add_lines((file_id, tree_revision), parent_keys,
1934
2020
                     self.get_file_lines(file_id))
1938
2024
            vf.fallback_versionedfiles.append(base_vf)
1939
2025
        return tree_revision
1940
2026
 
1941
 
    def _stat_limbo_file(self, file_id):
1942
 
        trans_id = self._transform.trans_id_file_id(file_id)
 
2027
    def _stat_limbo_file(self, file_id=None, trans_id=None):
 
2028
        if trans_id is None:
 
2029
            trans_id = self._transform.trans_id_file_id(file_id)
1943
2030
        name = self._transform._limbo_name(trans_id)
1944
2031
        return os.lstat(name)
1945
2032
 
2160
2247
 
2161
2248
    def get_file_size(self, file_id):
2162
2249
        """See Tree.get_file_size"""
 
2250
        trans_id = self._transform.trans_id_file_id(file_id)
 
2251
        kind = self._transform.final_kind(trans_id)
 
2252
        if kind != 'file':
 
2253
            return None
 
2254
        if trans_id in self._transform._new_contents:
 
2255
            return self._stat_limbo_file(trans_id=trans_id).st_size
2163
2256
        if self.kind(file_id) == 'file':
2164
2257
            return self._transform._tree.get_file_size(file_id)
2165
2258
        else:
2166
2259
            return None
2167
2260
 
 
2261
    def get_file_verifier(self, file_id, path=None, stat_value=None):
 
2262
        trans_id = self._transform.trans_id_file_id(file_id)
 
2263
        kind = self._transform._new_contents.get(trans_id)
 
2264
        if kind is None:
 
2265
            return self._transform._tree.get_file_verifier(file_id)
 
2266
        if kind == 'file':
 
2267
            fileobj = self.get_file(file_id)
 
2268
            try:
 
2269
                return ("SHA1", sha_file(fileobj))
 
2270
            finally:
 
2271
                fileobj.close()
 
2272
 
2168
2273
    def get_file_sha1(self, file_id, path=None, stat_value=None):
2169
2274
        trans_id = self._transform.trans_id_file_id(file_id)
2170
2275
        kind = self._transform._new_contents.get(trans_id)
2193
2298
            except errors.NoSuchId:
2194
2299
                return False
2195
2300
 
 
2301
    def has_filename(self, path):
 
2302
        trans_id = self._path2trans_id(path)
 
2303
        if trans_id in self._transform._new_contents:
 
2304
            return True
 
2305
        elif trans_id in self._transform._removed_contents:
 
2306
            return False
 
2307
        else:
 
2308
            return self._transform._tree.has_filename(path)
 
2309
 
2196
2310
    def path_content_summary(self, path):
2197
2311
        trans_id = self._path2trans_id(path)
2198
2312
        tt = self._transform
2286
2400
                                   self.get_file(file_id).readlines(),
2287
2401
                                   default_revision)
2288
2402
 
2289
 
    def get_symlink_target(self, file_id):
 
2403
    def get_symlink_target(self, file_id, path=None):
2290
2404
        """See Tree.get_symlink_target"""
2291
2405
        if not self._content_change(file_id):
2292
2406
            return self._transform._tree.get_symlink_target(file_id)
2502
2616
                    executable = tree.is_executable(file_id, tree_path)
2503
2617
                    if executable:
2504
2618
                        tt.set_executability(executable, trans_id)
2505
 
                    trans_data = (trans_id, tree_path)
 
2619
                    trans_data = (trans_id, tree_path, entry.text_sha1)
2506
2620
                    deferred_contents.append((file_id, trans_data))
2507
2621
                else:
2508
2622
                    file_trans_id[file_id] = new_by_entry(tt, entry, parent_id,
2524
2638
            precomputed_delta = None
2525
2639
        conflicts = cook_conflicts(raw_conflicts, tt)
2526
2640
        for conflict in conflicts:
2527
 
            warning(conflict)
 
2641
            trace.warning(unicode(conflict))
2528
2642
        try:
2529
2643
            wt.add_conflicts(conflicts)
2530
2644
        except errors.UnsupportedOperation:
2553
2667
        unchanged = dict(unchanged)
2554
2668
        new_desired_files = []
2555
2669
        count = 0
2556
 
        for file_id, (trans_id, tree_path) in desired_files:
 
2670
        for file_id, (trans_id, tree_path, text_sha1) in desired_files:
2557
2671
            accelerator_path = unchanged.get(file_id)
2558
2672
            if accelerator_path is None:
2559
 
                new_desired_files.append((file_id, (trans_id, tree_path)))
 
2673
                new_desired_files.append((file_id,
 
2674
                    (trans_id, tree_path, text_sha1)))
2560
2675
                continue
2561
2676
            pb.update('Adding file contents', count + offset, total)
2562
2677
            if hardlink:
2569
2684
                    contents = filtered_output_bytes(contents, filters,
2570
2685
                        ContentFilterContext(tree_path, tree))
2571
2686
                try:
2572
 
                    tt.create_file(contents, trans_id)
 
2687
                    tt.create_file(contents, trans_id, sha1=text_sha1)
2573
2688
                finally:
2574
2689
                    try:
2575
2690
                        contents.close()
2578
2693
                        pass
2579
2694
            count += 1
2580
2695
        offset += count
2581
 
    for count, ((trans_id, tree_path), contents) in enumerate(
 
2696
    for count, ((trans_id, tree_path, text_sha1), contents) in enumerate(
2582
2697
            tree.iter_files_bytes(new_desired_files)):
2583
2698
        if wt.supports_content_filtering():
2584
2699
            filters = wt._content_filter_stack(tree_path)
2585
2700
            contents = filtered_output_bytes(contents, filters,
2586
2701
                ContentFilterContext(tree_path, tree))
2587
 
        tt.create_file(contents, trans_id)
 
2702
        tt.create_file(contents, trans_id, sha1=text_sha1)
2588
2703
        pb.update('Adding file contents', count + offset, total)
2589
2704
 
2590
2705
 
2765
2880
                unversioned_filter=working_tree.is_ignored)
2766
2881
            delta.report_changes(tt.iter_changes(), change_reporter)
2767
2882
        for conflict in conflicts:
2768
 
            warning(conflict)
 
2883
            trace.warning(unicode(conflict))
2769
2884
        pp.next_phase()
2770
2885
        tt.apply()
2771
2886
        working_tree.set_merge_modified(merge_modified)
2802
2917
                 backups, merge_modified, basis_tree=None):
2803
2918
    if basis_tree is not None:
2804
2919
        basis_tree.lock_read()
2805
 
    change_list = target_tree.iter_changes(working_tree,
 
2920
    # We ask the working_tree for its changes relative to the target, rather
 
2921
    # than the target changes relative to the working tree. Because WT4 has an
 
2922
    # optimizer to compare itself to a target, but no optimizer for the
 
2923
    # reverse.
 
2924
    change_list = working_tree.iter_changes(target_tree,
2806
2925
        specific_files=specific_files, pb=pb)
2807
2926
    if target_tree.get_root_id() is None:
2808
2927
        skip_root = True
2812
2931
        deferred_files = []
2813
2932
        for id_num, (file_id, path, changed_content, versioned, parent, name,
2814
2933
                kind, executable) in enumerate(change_list):
2815
 
            if skip_root and file_id[0] is not None and parent[0] is None:
 
2934
            target_path, wt_path = path
 
2935
            target_versioned, wt_versioned = versioned
 
2936
            target_parent, wt_parent = parent
 
2937
            target_name, wt_name = name
 
2938
            target_kind, wt_kind = kind
 
2939
            target_executable, wt_executable = executable
 
2940
            if skip_root and wt_parent is None:
2816
2941
                continue
2817
2942
            trans_id = tt.trans_id_file_id(file_id)
2818
2943
            mode_id = None
2819
2944
            if changed_content:
2820
2945
                keep_content = False
2821
 
                if kind[0] == 'file' and (backups or kind[1] is None):
 
2946
                if wt_kind == 'file' and (backups or target_kind is None):
2822
2947
                    wt_sha1 = working_tree.get_file_sha1(file_id)
2823
2948
                    if merge_modified.get(file_id) != wt_sha1:
2824
2949
                        # acquire the basis tree lazily to prevent the
2827
2952
                        if basis_tree is None:
2828
2953
                            basis_tree = working_tree.basis_tree()
2829
2954
                            basis_tree.lock_read()
2830
 
                        if file_id in basis_tree:
 
2955
                        if basis_tree.has_id(file_id):
2831
2956
                            if wt_sha1 != basis_tree.get_file_sha1(file_id):
2832
2957
                                keep_content = True
2833
 
                        elif kind[1] is None and not versioned[1]:
 
2958
                        elif target_kind is None and not target_versioned:
2834
2959
                            keep_content = True
2835
 
                if kind[0] is not None:
 
2960
                if wt_kind is not None:
2836
2961
                    if not keep_content:
2837
2962
                        tt.delete_contents(trans_id)
2838
 
                    elif kind[1] is not None:
2839
 
                        parent_trans_id = tt.trans_id_file_id(parent[0])
 
2963
                    elif target_kind is not None:
 
2964
                        parent_trans_id = tt.trans_id_file_id(wt_parent)
2840
2965
                        backup_name = tt._available_backup_name(
2841
 
                            name[0], parent_trans_id)
 
2966
                            wt_name, parent_trans_id)
2842
2967
                        tt.adjust_path(backup_name, parent_trans_id, trans_id)
2843
 
                        new_trans_id = tt.create_path(name[0], parent_trans_id)
2844
 
                        if versioned == (True, True):
 
2968
                        new_trans_id = tt.create_path(wt_name, parent_trans_id)
 
2969
                        if wt_versioned and target_versioned:
2845
2970
                            tt.unversion_file(trans_id)
2846
2971
                            tt.version_file(file_id, new_trans_id)
2847
2972
                        # New contents should have the same unix perms as old
2848
2973
                        # contents
2849
2974
                        mode_id = trans_id
2850
2975
                        trans_id = new_trans_id
2851
 
                if kind[1] in ('directory', 'tree-reference'):
 
2976
                if target_kind in ('directory', 'tree-reference'):
2852
2977
                    tt.create_directory(trans_id)
2853
 
                    if kind[1] == 'tree-reference':
 
2978
                    if target_kind == 'tree-reference':
2854
2979
                        revision = target_tree.get_reference_revision(file_id,
2855
 
                                                                      path[1])
 
2980
                                                                      target_path)
2856
2981
                        tt.set_tree_reference(revision, trans_id)
2857
 
                elif kind[1] == 'symlink':
 
2982
                elif target_kind == 'symlink':
2858
2983
                    tt.create_symlink(target_tree.get_symlink_target(file_id),
2859
2984
                                      trans_id)
2860
 
                elif kind[1] == 'file':
 
2985
                elif target_kind == 'file':
2861
2986
                    deferred_files.append((file_id, (trans_id, mode_id)))
2862
2987
                    if basis_tree is None:
2863
2988
                        basis_tree = working_tree.basis_tree()
2864
2989
                        basis_tree.lock_read()
2865
2990
                    new_sha1 = target_tree.get_file_sha1(file_id)
2866
 
                    if (file_id in basis_tree and new_sha1 ==
2867
 
                        basis_tree.get_file_sha1(file_id)):
 
2991
                    if (basis_tree.has_id(file_id) and
 
2992
                        new_sha1 == basis_tree.get_file_sha1(file_id)):
2868
2993
                        if file_id in merge_modified:
2869
2994
                            del merge_modified[file_id]
2870
2995
                    else:
2871
2996
                        merge_modified[file_id] = new_sha1
2872
2997
 
2873
2998
                    # preserve the execute bit when backing up
2874
 
                    if keep_content and executable[0] == executable[1]:
2875
 
                        tt.set_executability(executable[1], trans_id)
2876
 
                elif kind[1] is not None:
2877
 
                    raise AssertionError(kind[1])
2878
 
            if versioned == (False, True):
 
2999
                    if keep_content and wt_executable == target_executable:
 
3000
                        tt.set_executability(target_executable, trans_id)
 
3001
                elif target_kind is not None:
 
3002
                    raise AssertionError(target_kind)
 
3003
            if not wt_versioned and target_versioned:
2879
3004
                tt.version_file(file_id, trans_id)
2880
 
            if versioned == (True, False):
 
3005
            if wt_versioned and not target_versioned:
2881
3006
                tt.unversion_file(trans_id)
2882
 
            if (name[1] is not None and
2883
 
                (name[0] != name[1] or parent[0] != parent[1])):
2884
 
                if name[1] == '' and parent[1] is None:
 
3007
            if (target_name is not None and
 
3008
                (wt_name != target_name or wt_parent != target_parent)):
 
3009
                if target_name == '' and target_parent is None:
2885
3010
                    parent_trans = ROOT_PARENT
2886
3011
                else:
2887
 
                    parent_trans = tt.trans_id_file_id(parent[1])
2888
 
                if parent[0] is None and versioned[0]:
2889
 
                    tt.adjust_root_path(name[1], parent_trans)
 
3012
                    parent_trans = tt.trans_id_file_id(target_parent)
 
3013
                if wt_parent is None and wt_versioned:
 
3014
                    tt.adjust_root_path(target_name, parent_trans)
2890
3015
                else:
2891
 
                    tt.adjust_path(name[1], parent_trans, trans_id)
2892
 
            if executable[0] != executable[1] and kind[1] == "file":
2893
 
                tt.set_executability(executable[1], trans_id)
 
3016
                    tt.adjust_path(target_name, parent_trans, trans_id)
 
3017
            if wt_executable != target_executable and target_kind == "file":
 
3018
                tt.set_executability(target_executable, trans_id)
2894
3019
        if working_tree.supports_content_filtering():
2895
3020
            for index, ((trans_id, mode_id), bytes) in enumerate(
2896
3021
                target_tree.iter_files_bytes(deferred_files)):
2999
3124
                        file_id = tt.final_file_id(trans_id)
3000
3125
                        if file_id is None:
3001
3126
                            file_id = tt.inactive_file_id(trans_id)
3002
 
                        entry = path_tree.inventory[file_id]
 
3127
                        _, entry = path_tree.iter_entries_by_dir(
 
3128
                            [file_id]).next()
3003
3129
                        # special-case the other tree root (move its
3004
3130
                        # children to current root)
3005
3131
                        if entry.parent_id is None:
3020
3146
        elif c_type == 'unversioned parent':
3021
3147
            file_id = tt.inactive_file_id(conflict[1])
3022
3148
            # special-case the other tree root (move its children instead)
3023
 
            if path_tree and file_id in path_tree:
 
3149
            if path_tree and path_tree.has_id(file_id):
3024
3150
                if path_tree.path2id('') == file_id:
3025
3151
                    # This is the root entry, skip it
3026
3152
                    continue
3044
3170
 
3045
3171
def cook_conflicts(raw_conflicts, tt):
3046
3172
    """Generate a list of cooked conflicts, sorted by file path"""
3047
 
    from bzrlib.conflicts import Conflict
3048
3173
    conflict_iter = iter_cook_conflicts(raw_conflicts, tt)
3049
 
    return sorted(conflict_iter, key=Conflict.sort_key)
 
3174
    return sorted(conflict_iter, key=conflicts.Conflict.sort_key)
3050
3175
 
3051
3176
 
3052
3177
def iter_cook_conflicts(raw_conflicts, tt):
3053
 
    from bzrlib.conflicts import Conflict
3054
3178
    fp = FinalPaths(tt)
3055
3179
    for conflict in raw_conflicts:
3056
3180
        c_type = conflict[0]
3058
3182
        modified_path = fp.get_path(conflict[2])
3059
3183
        modified_id = tt.final_file_id(conflict[2])
3060
3184
        if len(conflict) == 3:
3061
 
            yield Conflict.factory(c_type, action=action, path=modified_path,
3062
 
                                     file_id=modified_id)
 
3185
            yield conflicts.Conflict.factory(
 
3186
                c_type, action=action, path=modified_path, file_id=modified_id)
3063
3187
 
3064
3188
        else:
3065
3189
            conflicting_path = fp.get_path(conflict[3])
3066
3190
            conflicting_id = tt.final_file_id(conflict[3])
3067
 
            yield Conflict.factory(c_type, action=action, path=modified_path,
3068
 
                                   file_id=modified_id,
3069
 
                                   conflict_path=conflicting_path,
3070
 
                                   conflict_file_id=conflicting_id)
 
3191
            yield conflicts.Conflict.factory(
 
3192
                c_type, action=action, path=modified_path,
 
3193
                file_id=modified_id,
 
3194
                conflict_path=conflicting_path,
 
3195
                conflict_file_id=conflicting_id)
3071
3196
 
3072
3197
 
3073
3198
class _FileMover(object):