~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: 2009-04-09 23:12:55 UTC
  • mfrom: (3920.2.37 dpush)
  • Revision ID: pqm@pqm.ubuntu.com-20090409231255-o8w1g2q3igiyf8b2
(Jelmer) Add the dpush command.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
17
17
import os
18
18
import errno
19
19
from stat import S_ISREG, S_IEXEC
20
 
import time
21
20
 
22
21
from bzrlib.lazy_import import lazy_import
23
22
lazy_import(globals(), """
24
23
from bzrlib import (
25
24
    annotate,
26
 
    bencode,
27
25
    bzrdir,
28
 
    commit,
29
26
    delta,
30
27
    errors,
31
28
    inventory,
32
29
    multiparent,
33
30
    osutils,
34
31
    revision as _mod_revision,
35
 
    ui,
36
32
    )
 
33
from bzrlib.util import bencode
37
34
""")
38
35
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
39
 
                           ReusingTransform, CantMoveRoot,
 
36
                           ReusingTransform, NotVersionedError, CantMoveRoot,
40
37
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
41
38
                           UnableCreateSymlink)
42
39
from bzrlib.filters import filtered_output_bytes, ContentFilterContext
51
48
    splitpath,
52
49
    supports_executable,
53
50
)
54
 
from bzrlib.progress import ProgressPhase
 
51
from bzrlib.progress import DummyProgress, ProgressPhase
55
52
from bzrlib.symbol_versioning import (
56
53
        deprecated_function,
57
54
        deprecated_in,
79
76
 
80
77
 
81
78
class TreeTransformBase(object):
82
 
    """The base class for TreeTransform and its kin."""
 
79
    """The base class for TreeTransform and TreeTransformBase"""
83
80
 
84
 
    def __init__(self, tree, pb=None,
 
81
    def __init__(self, tree, limbodir, pb=DummyProgress(),
85
82
                 case_sensitive=True):
86
83
        """Constructor.
87
84
 
88
85
        :param tree: The tree that will be transformed, but not necessarily
89
86
            the output tree.
90
 
        :param pb: ignored
 
87
        :param limbodir: A directory where new files can be stored until
 
88
            they are installed in their proper places
 
89
        :param pb: A ProgressBar indicating how much progress is being made
91
90
        :param case_sensitive: If True, the target of the transform is
92
91
            case sensitive, not just case preserving.
93
92
        """
94
93
        object.__init__(self)
95
94
        self._tree = tree
 
95
        self._limbodir = limbodir
 
96
        self._deletiondir = None
96
97
        self._id_number = 0
97
98
        # mapping of trans_id -> new basename
98
99
        self._new_name = {}
100
101
        self._new_parent = {}
101
102
        # mapping of trans_id with new contents -> new file_kind
102
103
        self._new_contents = {}
 
104
        # A mapping of transform ids to their limbo filename
 
105
        self._limbo_files = {}
 
106
        # A mapping of transform ids to a set of the transform ids of children
 
107
        # that their limbo directory has
 
108
        self._limbo_children = {}
 
109
        # Map transform ids to maps of child filename to child transform id
 
110
        self._limbo_children_names = {}
 
111
        # List of transform ids that need to be renamed from limbo into place
 
112
        self._needs_rename = set()
103
113
        # Set of trans_ids whose contents will be removed
104
114
        self._removed_contents = set()
105
115
        # Mapping of trans_id -> new execute-bit value
118
128
        self._tree_path_ids = {}
119
129
        # Mapping trans_id -> path in old tree
120
130
        self._tree_id_paths = {}
 
131
        # Cache of realpath results, to speed up canonical_path
 
132
        self._realpaths = {}
 
133
        # Cache of relpath results, to speed up canonical_path
 
134
        self._relpaths = {}
121
135
        # The trans_id that will be used as the tree root
122
136
        root_id = tree.get_root_id()
123
137
        if root_id is not None:
133
147
        # A counter of how many files have been renamed
134
148
        self.rename_count = 0
135
149
 
136
 
    def finalize(self):
137
 
        """Release the working tree lock, if held.
138
 
 
139
 
        This is required if apply has not been invoked, but can be invoked
140
 
        even after apply.
141
 
        """
142
 
        if self._tree is None:
143
 
            return
144
 
        self._tree.unlock()
145
 
        self._tree = None
146
 
 
147
150
    def __get_root(self):
148
151
        return self._new_root
149
152
 
150
153
    root = property(__get_root)
151
154
 
 
155
    def finalize(self):
 
156
        """Release the working tree lock, if held, clean up limbo dir.
 
157
 
 
158
        This is required if apply has not been invoked, but can be invoked
 
159
        even after apply.
 
160
        """
 
161
        if self._tree is None:
 
162
            return
 
163
        try:
 
164
            entries = [(self._limbo_name(t), t, k) for t, k in
 
165
                       self._new_contents.iteritems()]
 
166
            entries.sort(reverse=True)
 
167
            for path, trans_id, kind in entries:
 
168
                if kind == "directory":
 
169
                    os.rmdir(path)
 
170
                else:
 
171
                    os.unlink(path)
 
172
            try:
 
173
                os.rmdir(self._limbodir)
 
174
            except OSError:
 
175
                # We don't especially care *why* the dir is immortal.
 
176
                raise ImmortalLimbo(self._limbodir)
 
177
            try:
 
178
                if self._deletiondir is not None:
 
179
                    os.rmdir(self._deletiondir)
 
180
            except OSError:
 
181
                raise errors.ImmortalPendingDeletion(self._deletiondir)
 
182
        finally:
 
183
            self._tree.unlock()
 
184
            self._tree = None
 
185
 
152
186
    def _assign_id(self):
153
187
        """Produce a new tranform id"""
154
188
        new_id = "new-%s" % self._id_number
164
198
 
165
199
    def adjust_path(self, name, parent, trans_id):
166
200
        """Change the path that is assigned to a transaction id."""
167
 
        if parent is None:
168
 
            raise ValueError("Parent trans-id may not be None")
169
201
        if trans_id == self._new_root:
170
202
            raise CantMoveRoot
 
203
        previous_parent = self._new_parent.get(trans_id)
 
204
        previous_name = self._new_name.get(trans_id)
171
205
        self._new_name[trans_id] = name
172
206
        self._new_parent[trans_id] = parent
 
207
        if parent == ROOT_PARENT:
 
208
            if self._new_root is not None:
 
209
                raise ValueError("Cannot have multiple roots.")
 
210
            self._new_root = trans_id
 
211
        if (trans_id in self._limbo_files and
 
212
            trans_id not in self._needs_rename):
 
213
            self._rename_in_limbo([trans_id])
 
214
            self._limbo_children[previous_parent].remove(trans_id)
 
215
            del self._limbo_children_names[previous_parent][previous_name]
 
216
 
 
217
    def _rename_in_limbo(self, trans_ids):
 
218
        """Fix limbo names so that the right final path is produced.
 
219
 
 
220
        This means we outsmarted ourselves-- we tried to avoid renaming
 
221
        these files later by creating them with their final names in their
 
222
        final parents.  But now the previous name or parent is no longer
 
223
        suitable, so we have to rename them.
 
224
 
 
225
        Even for trans_ids that have no new contents, we must remove their
 
226
        entries from _limbo_files, because they are now stale.
 
227
        """
 
228
        for trans_id in trans_ids:
 
229
            old_path = self._limbo_files.pop(trans_id)
 
230
            if trans_id not in self._new_contents:
 
231
                continue
 
232
            new_path = self._limbo_name(trans_id)
 
233
            os.rename(old_path, new_path)
173
234
 
174
235
    def adjust_root_path(self, name, parent):
175
236
        """Emulate moving the root by moving all children, instead.
203
264
        self.version_file(old_root_file_id, old_root)
204
265
        self.unversion_file(self._new_root)
205
266
 
206
 
    def fixup_new_roots(self):
207
 
        """Reinterpret requests to change the root directory
208
 
 
209
 
        Instead of creating a root directory, or moving an existing directory,
210
 
        all the attributes and children of the new root are applied to the
211
 
        existing root directory.
212
 
 
213
 
        This means that the old root trans-id becomes obsolete, so it is
214
 
        recommended only to invoke this after the root trans-id has become
215
 
        irrelevant.
216
 
        """
217
 
        new_roots = [k for k, v in self._new_parent.iteritems() if v is
218
 
                     ROOT_PARENT]
219
 
        if len(new_roots) < 1:
220
 
            return
221
 
        if len(new_roots) != 1:
222
 
            raise ValueError('A tree cannot have two roots!')
223
 
        if self._new_root is None:
224
 
            self._new_root = new_roots[0]
225
 
            return
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
 
 
232
 
        # unversion the new root's directory.
233
 
        file_id = self.final_file_id(old_new_root)
234
 
        if old_new_root in self._new_id:
235
 
            self.cancel_versioning(old_new_root)
236
 
        else:
237
 
            self.unversion_file(old_new_root)
238
 
        # if, at this stage, root still has an old file_id, zap it so we can
239
 
        # stick a new one in.
240
 
        if (self.tree_file_id(self._new_root) is not None and
241
 
            self._new_root not in self._removed_id):
242
 
            self.unversion_file(self._new_root)
243
 
        self.version_file(file_id, self._new_root)
244
 
 
245
 
        # Now move children of new root into old root directory.
246
 
        # Ensure all children are registered with the transaction, but don't
247
 
        # use directly-- some tree children have new parents
248
 
        list(self.iter_tree_children(old_new_root))
249
 
        # Move all children of new root into old root directory.
250
 
        for child in self.by_parent().get(old_new_root, []):
251
 
            self.adjust_path(self.final_name(child), self._new_root, child)
252
 
 
253
 
        # Ensure old_new_root has no directory.
254
 
        if old_new_root in self._new_contents:
255
 
            self.cancel_creation(old_new_root)
256
 
        else:
257
 
            self.delete_contents(old_new_root)
258
 
 
259
 
        # prevent deletion of root directory.
260
 
        if self._new_root in self._removed_contents:
261
 
            self.cancel_deletion(self._new_root)
262
 
 
263
 
        # destroy path info for old_new_root.
264
 
        del self._new_parent[old_new_root]
265
 
        del self._new_name[old_new_root]
266
 
 
267
267
    def trans_id_tree_file_id(self, inventory_id):
268
268
        """Determine the transaction id of a working tree file.
269
269
 
298
298
            else:
299
299
                return self.trans_id_tree_file_id(file_id)
300
300
 
 
301
    def canonical_path(self, path):
 
302
        """Get the canonical tree-relative path"""
 
303
        # don't follow final symlinks
 
304
        abs = self._tree.abspath(path)
 
305
        if abs in self._relpaths:
 
306
            return self._relpaths[abs]
 
307
        dirname, basename = os.path.split(abs)
 
308
        if dirname not in self._realpaths:
 
309
            self._realpaths[dirname] = os.path.realpath(dirname)
 
310
        dirname = self._realpaths[dirname]
 
311
        abs = pathjoin(dirname, basename)
 
312
        if dirname in self._relpaths:
 
313
            relpath = pathjoin(self._relpaths[dirname], basename)
 
314
            relpath = relpath.rstrip('/\\')
 
315
        else:
 
316
            relpath = self._tree.relpath(abs)
 
317
        self._relpaths[abs] = relpath
 
318
        return relpath
 
319
 
301
320
    def trans_id_tree_path(self, path):
302
321
        """Determine (and maybe set) the transaction ID for a tree path."""
303
322
        path = self.canonical_path(path)
313
332
            return ROOT_PARENT
314
333
        return self.trans_id_tree_path(os.path.dirname(path))
315
334
 
 
335
    def create_file(self, contents, trans_id, mode_id=None):
 
336
        """Schedule creation of a new file.
 
337
 
 
338
        See also new_file.
 
339
 
 
340
        Contents is an iterator of strings, all of which will be written
 
341
        to the target destination.
 
342
 
 
343
        New file takes the permissions of any existing file with that id,
 
344
        unless mode_id is specified.
 
345
        """
 
346
        name = self._limbo_name(trans_id)
 
347
        f = open(name, 'wb')
 
348
        try:
 
349
            try:
 
350
                unique_add(self._new_contents, trans_id, 'file')
 
351
            except:
 
352
                # Clean up the file, it never got registered so
 
353
                # TreeTransform.finalize() won't clean it up.
 
354
                f.close()
 
355
                os.unlink(name)
 
356
                raise
 
357
 
 
358
            f.writelines(contents)
 
359
        finally:
 
360
            f.close()
 
361
        self._set_mode(trans_id, mode_id, S_ISREG)
 
362
 
 
363
    def _set_mode(self, trans_id, mode_id, typefunc):
 
364
        """Set the mode of new file contents.
 
365
        The mode_id is the existing file to get the mode from (often the same
 
366
        as trans_id).  The operation is only performed if there's a mode match
 
367
        according to typefunc.
 
368
        """
 
369
        if mode_id is None:
 
370
            mode_id = trans_id
 
371
        try:
 
372
            old_path = self._tree_id_paths[mode_id]
 
373
        except KeyError:
 
374
            return
 
375
        try:
 
376
            mode = os.stat(self._tree.abspath(old_path)).st_mode
 
377
        except OSError, e:
 
378
            if e.errno in (errno.ENOENT, errno.ENOTDIR):
 
379
                # Either old_path doesn't exist, or the parent of the
 
380
                # target is not a directory (but will be one eventually)
 
381
                # Either way, we know it doesn't exist *right now*
 
382
                # See also bug #248448
 
383
                return
 
384
            else:
 
385
                raise
 
386
        if typefunc(mode):
 
387
            os.chmod(self._limbo_name(trans_id), mode)
 
388
 
 
389
    def create_hardlink(self, path, trans_id):
 
390
        """Schedule creation of a hard link"""
 
391
        name = self._limbo_name(trans_id)
 
392
        try:
 
393
            os.link(path, name)
 
394
        except OSError, e:
 
395
            if e.errno != errno.EPERM:
 
396
                raise
 
397
            raise errors.HardLinkNotSupported(path)
 
398
        try:
 
399
            unique_add(self._new_contents, trans_id, 'file')
 
400
        except:
 
401
            # Clean up the file, it never got registered so
 
402
            # TreeTransform.finalize() won't clean it up.
 
403
            os.unlink(name)
 
404
            raise
 
405
 
 
406
    def create_directory(self, trans_id):
 
407
        """Schedule creation of a new directory.
 
408
 
 
409
        See also new_directory.
 
410
        """
 
411
        os.mkdir(self._limbo_name(trans_id))
 
412
        unique_add(self._new_contents, trans_id, 'directory')
 
413
 
 
414
    def create_symlink(self, target, trans_id):
 
415
        """Schedule creation of a new symbolic link.
 
416
 
 
417
        target is a bytestring.
 
418
        See also new_symlink.
 
419
        """
 
420
        if has_symlinks():
 
421
            os.symlink(target, self._limbo_name(trans_id))
 
422
            unique_add(self._new_contents, trans_id, 'symlink')
 
423
        else:
 
424
            try:
 
425
                path = FinalPaths(self).get_path(trans_id)
 
426
            except KeyError:
 
427
                path = None
 
428
            raise UnableCreateSymlink(path=path)
 
429
 
 
430
    def cancel_creation(self, trans_id):
 
431
        """Cancel the creation of new file contents."""
 
432
        del self._new_contents[trans_id]
 
433
        children = self._limbo_children.get(trans_id)
 
434
        # if this is a limbo directory with children, move them before removing
 
435
        # the directory
 
436
        if children is not None:
 
437
            self._rename_in_limbo(children)
 
438
            del self._limbo_children[trans_id]
 
439
            del self._limbo_children_names[trans_id]
 
440
        delete_any(self._limbo_name(trans_id))
 
441
 
316
442
    def delete_contents(self, trans_id):
317
443
        """Schedule the contents of a path entry for deletion"""
318
 
        # Ensure that the object exists in the WorkingTree, this will raise an
319
 
        # exception if there is a problem
320
444
        self.tree_kind(trans_id)
321
445
        self._removed_contents.add(trans_id)
322
446
 
394
518
        new_ids.update(changed_kind)
395
519
        return sorted(FinalPaths(self).get_paths(new_ids))
396
520
 
 
521
    def tree_kind(self, trans_id):
 
522
        """Determine the file kind in the working tree.
 
523
 
 
524
        Raises NoSuchFile if the file does not exist
 
525
        """
 
526
        path = self._tree_id_paths.get(trans_id)
 
527
        if path is None:
 
528
            raise NoSuchFile(None)
 
529
        try:
 
530
            return file_kind(self._tree.abspath(path))
 
531
        except OSError, e:
 
532
            if e.errno != errno.ENOENT:
 
533
                raise
 
534
            else:
 
535
                raise NoSuchFile(path)
 
536
 
397
537
    def final_kind(self, trans_id):
398
538
        """Determine the final file kind, after any changes applied.
399
539
 
506
646
        conflicts.extend(self._overwrite_conflicts())
507
647
        return conflicts
508
648
 
509
 
    def _check_malformed(self):
510
 
        conflicts = self.find_conflicts()
511
 
        if len(conflicts) != 0:
512
 
            raise MalformedTransform(conflicts=conflicts)
513
 
 
514
649
    def _add_tree_children(self):
515
650
        """Add all the children of all active parents to the known paths.
516
651
 
532
667
            # ensure that all children are registered with the transaction
533
668
            list(self.iter_tree_children(parent_id))
534
669
 
 
670
    def iter_tree_children(self, parent_id):
 
671
        """Iterate through the entry's tree children, if any"""
 
672
        try:
 
673
            path = self._tree_id_paths[parent_id]
 
674
        except KeyError:
 
675
            return
 
676
        try:
 
677
            children = os.listdir(self._tree.abspath(path))
 
678
        except OSError, e:
 
679
            if not (osutils._is_error_enotdir(e)
 
680
                    or e.errno in (errno.ENOENT, errno.ESRCH)):
 
681
                raise
 
682
            return
 
683
 
 
684
        for child in children:
 
685
            childpath = joinpath(path, child)
 
686
            if self._tree.is_control_filename(childpath):
 
687
                continue
 
688
            yield self.trans_id_tree_path(childpath)
 
689
 
535
690
    def has_named_child(self, by_parent, parent_id, name):
536
691
        try:
537
692
            children = by_parent[parent_id]
712
867
            return True
713
868
        return False
714
869
 
 
870
    def _limbo_name(self, trans_id):
 
871
        """Generate the limbo name of a file"""
 
872
        limbo_name = self._limbo_files.get(trans_id)
 
873
        if limbo_name is not None:
 
874
            return limbo_name
 
875
        parent = self._new_parent.get(trans_id)
 
876
        # if the parent directory is already in limbo (e.g. when building a
 
877
        # tree), choose a limbo name inside the parent, to reduce further
 
878
        # renames.
 
879
        use_direct_path = False
 
880
        if self._new_contents.get(parent) == 'directory':
 
881
            filename = self._new_name.get(trans_id)
 
882
            if filename is not None:
 
883
                if parent not in self._limbo_children:
 
884
                    self._limbo_children[parent] = set()
 
885
                    self._limbo_children_names[parent] = {}
 
886
                    use_direct_path = True
 
887
                # the direct path can only be used if no other file has
 
888
                # already taken this pathname, i.e. if the name is unused, or
 
889
                # if it is already associated with this trans_id.
 
890
                elif self._case_sensitive_target:
 
891
                    if (self._limbo_children_names[parent].get(filename)
 
892
                        in (trans_id, None)):
 
893
                        use_direct_path = True
 
894
                else:
 
895
                    for l_filename, l_trans_id in\
 
896
                        self._limbo_children_names[parent].iteritems():
 
897
                        if l_trans_id == trans_id:
 
898
                            continue
 
899
                        if l_filename.lower() == filename.lower():
 
900
                            break
 
901
                    else:
 
902
                        use_direct_path = True
 
903
 
 
904
        if use_direct_path:
 
905
            limbo_name = pathjoin(self._limbo_files[parent], filename)
 
906
            self._limbo_children[parent].add(trans_id)
 
907
            self._limbo_children_names[parent][filename] = trans_id
 
908
        else:
 
909
            limbo_name = pathjoin(self._limbodir, trans_id)
 
910
            self._needs_rename.add(trans_id)
 
911
        self._limbo_files[trans_id] = limbo_name
 
912
        return limbo_name
 
913
 
715
914
    def _set_executability(self, path, trans_id):
716
915
        """Set the executability of versioned files """
717
916
        if supports_executable():
923
1122
    def get_preview_tree(self):
924
1123
        """Return a tree representing the result of the transform.
925
1124
 
926
 
        The tree is a snapshot, and altering the TreeTransform will invalidate
927
 
        it.
 
1125
        This tree only supports the subset of Tree functionality required
 
1126
        by show_diff_trees.  It must only be compared to tt._tree.
928
1127
        """
929
1128
        return _PreviewTree(self)
930
1129
 
931
 
    def commit(self, branch, message, merge_parents=None, strict=False,
932
 
               timestamp=None, timezone=None, committer=None, authors=None,
933
 
               revprops=None, revision_id=None):
934
 
        """Commit the result of this TreeTransform to a branch.
935
 
 
936
 
        :param branch: The branch to commit to.
937
 
        :param message: The message to attach to the commit.
938
 
        :param merge_parents: Additional parent revision-ids specified by
939
 
            pending merges.
940
 
        :param strict: If True, abort the commit if there are unversioned
941
 
            files.
942
 
        :param timestamp: if not None, seconds-since-epoch for the time and
943
 
            date.  (May be a float.)
944
 
        :param timezone: Optional timezone for timestamp, as an offset in
945
 
            seconds.
946
 
        :param committer: Optional committer in email-id format.
947
 
            (e.g. "J Random Hacker <jrandom@example.com>")
948
 
        :param authors: Optional list of authors in email-id format.
949
 
        :param revprops: Optional dictionary of revision properties.
950
 
        :param revision_id: Optional revision id.  (Specifying a revision-id
951
 
            may reduce performance for some non-native formats.)
952
 
        :return: The revision_id of the revision committed.
953
 
        """
954
 
        self._check_malformed()
955
 
        if strict:
956
 
            unversioned = set(self._new_contents).difference(set(self._new_id))
957
 
            for trans_id in unversioned:
958
 
                if self.final_file_id(trans_id) is None:
959
 
                    raise errors.StrictCommitFailed()
960
 
 
961
 
        revno, last_rev_id = branch.last_revision_info()
962
 
        if last_rev_id == _mod_revision.NULL_REVISION:
963
 
            if merge_parents is not None:
964
 
                raise ValueError('Cannot supply merge parents for first'
965
 
                                 ' commit.')
966
 
            parent_ids = []
967
 
        else:
968
 
            parent_ids = [last_rev_id]
969
 
            if merge_parents is not None:
970
 
                parent_ids.extend(merge_parents)
971
 
        if self._tree.get_revision_id() != last_rev_id:
972
 
            raise ValueError('TreeTransform not based on branch basis: %s' %
973
 
                             self._tree.get_revision_id())
974
 
        revprops = commit.Commit.update_revprops(revprops, branch, authors)
975
 
        builder = branch.get_commit_builder(parent_ids,
976
 
                                            timestamp=timestamp,
977
 
                                            timezone=timezone,
978
 
                                            committer=committer,
979
 
                                            revprops=revprops,
980
 
                                            revision_id=revision_id)
981
 
        preview = self.get_preview_tree()
982
 
        list(builder.record_iter_changes(preview, last_rev_id,
983
 
                                         self.iter_changes()))
984
 
        builder.finish_inventory()
985
 
        revision_id = builder.commit(message)
986
 
        branch.set_last_revision_info(revno + 1, revision_id)
987
 
        return revision_id
988
 
 
989
1130
    def _text_parent(self, trans_id):
990
1131
        file_id = self.tree_file_id(trans_id)
991
1132
        try:
1035
1176
                                      (('attribs',),))
1036
1177
        for trans_id, kind in self._new_contents.items():
1037
1178
            if kind == 'file':
1038
 
                lines = osutils.chunks_to_lines(
1039
 
                    self._read_file_chunks(trans_id))
 
1179
                cur_file = open(self._limbo_name(trans_id), 'rb')
 
1180
                try:
 
1181
                    lines = osutils.chunks_to_lines(cur_file.readlines())
 
1182
                finally:
 
1183
                    cur_file.close()
1040
1184
                parents = self._get_parents_lines(trans_id)
1041
1185
                mpdiff = multiparent.MultiParent.from_lines(lines, parents)
1042
1186
                content = ''.join(mpdiff.to_patch())
1043
1187
            if kind == 'directory':
1044
1188
                content = ''
1045
1189
            if kind == 'symlink':
1046
 
                content = self._read_symlink_target(trans_id)
 
1190
                content = os.readlink(self._limbo_name(trans_id))
1047
1191
            yield serializer.bytes_record(content, ((trans_id, kind),))
1048
1192
 
 
1193
 
1049
1194
    def deserialize(self, records):
1050
1195
        """Deserialize a stored TreeTransform.
1051
1196
 
1082
1227
                self.create_symlink(content.decode('utf-8'), trans_id)
1083
1228
 
1084
1229
 
1085
 
class DiskTreeTransform(TreeTransformBase):
1086
 
    """Tree transform storing its contents on disk."""
1087
 
 
1088
 
    def __init__(self, tree, limbodir, pb=None,
1089
 
                 case_sensitive=True):
1090
 
        """Constructor.
1091
 
        :param tree: The tree that will be transformed, but not necessarily
1092
 
            the output tree.
1093
 
        :param limbodir: A directory where new files can be stored until
1094
 
            they are installed in their proper places
1095
 
        :param pb: ignored
1096
 
        :param case_sensitive: If True, the target of the transform is
1097
 
            case sensitive, not just case preserving.
1098
 
        """
1099
 
        TreeTransformBase.__init__(self, tree, pb, case_sensitive)
1100
 
        self._limbodir = limbodir
1101
 
        self._deletiondir = None
1102
 
        # A mapping of transform ids to their limbo filename
1103
 
        self._limbo_files = {}
1104
 
        # A mapping of transform ids to a set of the transform ids of children
1105
 
        # that their limbo directory has
1106
 
        self._limbo_children = {}
1107
 
        # Map transform ids to maps of child filename to child transform id
1108
 
        self._limbo_children_names = {}
1109
 
        # List of transform ids that need to be renamed from limbo into place
1110
 
        self._needs_rename = set()
1111
 
        self._creation_mtime = None
1112
 
 
1113
 
    def finalize(self):
1114
 
        """Release the working tree lock, if held, clean up limbo dir.
1115
 
 
1116
 
        This is required if apply has not been invoked, but can be invoked
1117
 
        even after apply.
1118
 
        """
1119
 
        if self._tree is None:
1120
 
            return
1121
 
        try:
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)
1127
 
            try:
1128
 
                delete_any(self._limbodir)
1129
 
            except OSError:
1130
 
                # We don't especially care *why* the dir is immortal.
1131
 
                raise ImmortalLimbo(self._limbodir)
1132
 
            try:
1133
 
                if self._deletiondir is not None:
1134
 
                    delete_any(self._deletiondir)
1135
 
            except OSError:
1136
 
                raise errors.ImmortalPendingDeletion(self._deletiondir)
1137
 
        finally:
1138
 
            TreeTransformBase.finalize(self)
1139
 
 
1140
 
    def _limbo_name(self, trans_id):
1141
 
        """Generate the limbo name of a file"""
1142
 
        limbo_name = self._limbo_files.get(trans_id)
1143
 
        if limbo_name is None:
1144
 
            limbo_name = self._generate_limbo_path(trans_id)
1145
 
            self._limbo_files[trans_id] = limbo_name
1146
 
        return limbo_name
1147
 
 
1148
 
    def _generate_limbo_path(self, trans_id):
1149
 
        """Generate a limbo path using the trans_id as the relative path.
1150
 
 
1151
 
        This is suitable as a fallback, and when the transform should not be
1152
 
        sensitive to the path encoding of the limbo directory.
1153
 
        """
1154
 
        self._needs_rename.add(trans_id)
1155
 
        return pathjoin(self._limbodir, trans_id)
1156
 
 
1157
 
    def adjust_path(self, name, parent, trans_id):
1158
 
        previous_parent = self._new_parent.get(trans_id)
1159
 
        previous_name = self._new_name.get(trans_id)
1160
 
        TreeTransformBase.adjust_path(self, name, parent, trans_id)
1161
 
        if (trans_id in self._limbo_files and
1162
 
            trans_id not in self._needs_rename):
1163
 
            self._rename_in_limbo([trans_id])
1164
 
            if previous_parent != parent:
1165
 
                self._limbo_children[previous_parent].remove(trans_id)
1166
 
            if previous_parent != parent or previous_name != name:
1167
 
                del self._limbo_children_names[previous_parent][previous_name]
1168
 
 
1169
 
    def _rename_in_limbo(self, trans_ids):
1170
 
        """Fix limbo names so that the right final path is produced.
1171
 
 
1172
 
        This means we outsmarted ourselves-- we tried to avoid renaming
1173
 
        these files later by creating them with their final names in their
1174
 
        final parents.  But now the previous name or parent is no longer
1175
 
        suitable, so we have to rename them.
1176
 
 
1177
 
        Even for trans_ids that have no new contents, we must remove their
1178
 
        entries from _limbo_files, because they are now stale.
1179
 
        """
1180
 
        for trans_id in trans_ids:
1181
 
            old_path = self._limbo_files.pop(trans_id)
1182
 
            if trans_id not in self._new_contents:
1183
 
                continue
1184
 
            new_path = self._limbo_name(trans_id)
1185
 
            osutils.rename(old_path, new_path)
1186
 
            for descendant in self._limbo_descendants(trans_id):
1187
 
                desc_path = self._limbo_files[descendant]
1188
 
                desc_path = new_path + desc_path[len(old_path):]
1189
 
                self._limbo_files[descendant] = desc_path
1190
 
 
1191
 
    def _limbo_descendants(self, trans_id):
1192
 
        """Return the set of trans_ids whose limbo paths descend from this."""
1193
 
        descendants = set(self._limbo_children.get(trans_id, []))
1194
 
        for descendant in list(descendants):
1195
 
            descendants.update(self._limbo_descendants(descendant))
1196
 
        return descendants
1197
 
 
1198
 
    def create_file(self, contents, trans_id, mode_id=None):
1199
 
        """Schedule creation of a new file.
1200
 
 
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.
1208
 
        """
1209
 
        name = self._limbo_name(trans_id)
1210
 
        f = open(name, 'wb')
1211
 
        try:
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
 
 
1221
 
            f.writelines(contents)
1222
 
        finally:
1223
 
            f.close()
1224
 
        self._set_mtime(name)
1225
 
        self._set_mode(trans_id, mode_id, S_ISREG)
1226
 
 
1227
 
    def _read_file_chunks(self, trans_id):
1228
 
        cur_file = open(self._limbo_name(trans_id), 'rb')
1229
 
        try:
1230
 
            return cur_file.readlines()
1231
 
        finally:
1232
 
            cur_file.close()
1233
 
 
1234
 
    def _read_symlink_target(self, trans_id):
1235
 
        return os.readlink(self._limbo_name(trans_id))
1236
 
 
1237
 
    def _set_mtime(self, path):
1238
 
        """All files that are created get the same mtime.
1239
 
 
1240
 
        This time is set by the first object to be created.
1241
 
        """
1242
 
        if self._creation_mtime is None:
1243
 
            self._creation_mtime = time.time()
1244
 
        os.utime(path, (self._creation_mtime, self._creation_mtime))
1245
 
 
1246
 
    def create_hardlink(self, path, trans_id):
1247
 
        """Schedule creation of a hard link"""
1248
 
        name = self._limbo_name(trans_id)
1249
 
        try:
1250
 
            os.link(path, name)
1251
 
        except OSError, e:
1252
 
            if e.errno != errno.EPERM:
1253
 
                raise
1254
 
            raise errors.HardLinkNotSupported(path)
1255
 
        try:
1256
 
            unique_add(self._new_contents, trans_id, 'file')
1257
 
        except:
1258
 
            # Clean up the file, it never got registered so
1259
 
            # TreeTransform.finalize() won't clean it up.
1260
 
            os.unlink(name)
1261
 
            raise
1262
 
 
1263
 
    def create_directory(self, trans_id):
1264
 
        """Schedule creation of a new directory.
1265
 
 
1266
 
        See also new_directory.
1267
 
        """
1268
 
        os.mkdir(self._limbo_name(trans_id))
1269
 
        unique_add(self._new_contents, trans_id, 'directory')
1270
 
 
1271
 
    def create_symlink(self, target, trans_id):
1272
 
        """Schedule creation of a new symbolic link.
1273
 
 
1274
 
        target is a bytestring.
1275
 
        See also new_symlink.
1276
 
        """
1277
 
        if has_symlinks():
1278
 
            os.symlink(target, self._limbo_name(trans_id))
1279
 
            unique_add(self._new_contents, trans_id, 'symlink')
1280
 
        else:
1281
 
            try:
1282
 
                path = FinalPaths(self).get_path(trans_id)
1283
 
            except KeyError:
1284
 
                path = None
1285
 
            raise UnableCreateSymlink(path=path)
1286
 
 
1287
 
    def cancel_creation(self, trans_id):
1288
 
        """Cancel the creation of new file contents."""
1289
 
        del self._new_contents[trans_id]
1290
 
        children = self._limbo_children.get(trans_id)
1291
 
        # if this is a limbo directory with children, move them before removing
1292
 
        # the directory
1293
 
        if children is not None:
1294
 
            self._rename_in_limbo(children)
1295
 
            del self._limbo_children[trans_id]
1296
 
            del self._limbo_children_names[trans_id]
1297
 
        delete_any(self._limbo_name(trans_id))
1298
 
 
1299
 
 
1300
 
class TreeTransform(DiskTreeTransform):
 
1230
class TreeTransform(TreeTransformBase):
1301
1231
    """Represent a tree transformation.
1302
1232
 
1303
1233
    This object is designed to support incremental generation of the transform,
1362
1292
    FileMover does not delete files until it is sure that a rollback will not
1363
1293
    happen.
1364
1294
    """
1365
 
    def __init__(self, tree, pb=None):
 
1295
    def __init__(self, tree, pb=DummyProgress()):
1366
1296
        """Note: a tree_write lock is taken on the tree.
1367
1297
 
1368
1298
        Use TreeTransform.finalize() to release the lock (can be omitted if
1389
1319
            tree.unlock()
1390
1320
            raise
1391
1321
 
1392
 
        # Cache of realpath results, to speed up canonical_path
1393
 
        self._realpaths = {}
1394
 
        # Cache of relpath results, to speed up canonical_path
1395
 
        self._relpaths = {}
1396
 
        DiskTreeTransform.__init__(self, tree, limbodir, pb,
 
1322
        TreeTransformBase.__init__(self, tree, limbodir, pb,
1397
1323
                                   tree.case_sensitive)
1398
1324
        self._deletiondir = deletiondir
1399
1325
 
1400
 
    def canonical_path(self, path):
1401
 
        """Get the canonical tree-relative path"""
1402
 
        # don't follow final symlinks
1403
 
        abs = self._tree.abspath(path)
1404
 
        if abs in self._relpaths:
1405
 
            return self._relpaths[abs]
1406
 
        dirname, basename = os.path.split(abs)
1407
 
        if dirname not in self._realpaths:
1408
 
            self._realpaths[dirname] = os.path.realpath(dirname)
1409
 
        dirname = self._realpaths[dirname]
1410
 
        abs = pathjoin(dirname, basename)
1411
 
        if dirname in self._relpaths:
1412
 
            relpath = pathjoin(self._relpaths[dirname], basename)
1413
 
            relpath = relpath.rstrip('/\\')
1414
 
        else:
1415
 
            relpath = self._tree.relpath(abs)
1416
 
        self._relpaths[abs] = relpath
1417
 
        return relpath
1418
 
 
1419
 
    def tree_kind(self, trans_id):
1420
 
        """Determine the file kind in the working tree.
1421
 
 
1422
 
        Raises NoSuchFile if the file does not exist
1423
 
        """
1424
 
        path = self._tree_id_paths.get(trans_id)
1425
 
        if path is None:
1426
 
            raise NoSuchFile(None)
1427
 
        try:
1428
 
            return file_kind(self._tree.abspath(path))
1429
 
        except OSError, e:
1430
 
            if e.errno != errno.ENOENT:
1431
 
                raise
1432
 
            else:
1433
 
                raise NoSuchFile(path)
1434
 
 
1435
 
    def _set_mode(self, trans_id, mode_id, typefunc):
1436
 
        """Set the mode of new file contents.
1437
 
        The mode_id is the existing file to get the mode from (often the same
1438
 
        as trans_id).  The operation is only performed if there's a mode match
1439
 
        according to typefunc.
1440
 
        """
1441
 
        if mode_id is None:
1442
 
            mode_id = trans_id
1443
 
        try:
1444
 
            old_path = self._tree_id_paths[mode_id]
1445
 
        except KeyError:
1446
 
            return
1447
 
        try:
1448
 
            mode = os.stat(self._tree.abspath(old_path)).st_mode
1449
 
        except OSError, e:
1450
 
            if e.errno in (errno.ENOENT, errno.ENOTDIR):
1451
 
                # Either old_path doesn't exist, or the parent of the
1452
 
                # target is not a directory (but will be one eventually)
1453
 
                # Either way, we know it doesn't exist *right now*
1454
 
                # See also bug #248448
1455
 
                return
1456
 
            else:
1457
 
                raise
1458
 
        if typefunc(mode):
1459
 
            os.chmod(self._limbo_name(trans_id), mode)
1460
 
 
1461
 
    def iter_tree_children(self, parent_id):
1462
 
        """Iterate through the entry's tree children, if any"""
1463
 
        try:
1464
 
            path = self._tree_id_paths[parent_id]
1465
 
        except KeyError:
1466
 
            return
1467
 
        try:
1468
 
            children = os.listdir(self._tree.abspath(path))
1469
 
        except OSError, e:
1470
 
            if not (osutils._is_error_enotdir(e)
1471
 
                    or e.errno in (errno.ENOENT, errno.ESRCH)):
1472
 
                raise
1473
 
            return
1474
 
 
1475
 
        for child in children:
1476
 
            childpath = joinpath(path, child)
1477
 
            if self._tree.is_control_filename(childpath):
1478
 
                continue
1479
 
            yield self.trans_id_tree_path(childpath)
1480
 
 
1481
 
    def _generate_limbo_path(self, trans_id):
1482
 
        """Generate a limbo path using the final path if possible.
1483
 
 
1484
 
        This optimizes the performance of applying the tree transform by
1485
 
        avoiding renames.  These renames can be avoided only when the parent
1486
 
        directory is already scheduled for creation.
1487
 
 
1488
 
        If the final path cannot be used, falls back to using the trans_id as
1489
 
        the relpath.
1490
 
        """
1491
 
        parent = self._new_parent.get(trans_id)
1492
 
        # if the parent directory is already in limbo (e.g. when building a
1493
 
        # tree), choose a limbo name inside the parent, to reduce further
1494
 
        # renames.
1495
 
        use_direct_path = False
1496
 
        if self._new_contents.get(parent) == 'directory':
1497
 
            filename = self._new_name.get(trans_id)
1498
 
            if filename is not None:
1499
 
                if parent not in self._limbo_children:
1500
 
                    self._limbo_children[parent] = set()
1501
 
                    self._limbo_children_names[parent] = {}
1502
 
                    use_direct_path = True
1503
 
                # the direct path can only be used if no other file has
1504
 
                # already taken this pathname, i.e. if the name is unused, or
1505
 
                # if it is already associated with this trans_id.
1506
 
                elif self._case_sensitive_target:
1507
 
                    if (self._limbo_children_names[parent].get(filename)
1508
 
                        in (trans_id, None)):
1509
 
                        use_direct_path = True
1510
 
                else:
1511
 
                    for l_filename, l_trans_id in\
1512
 
                        self._limbo_children_names[parent].iteritems():
1513
 
                        if l_trans_id == trans_id:
1514
 
                            continue
1515
 
                        if l_filename.lower() == filename.lower():
1516
 
                            break
1517
 
                    else:
1518
 
                        use_direct_path = True
1519
 
 
1520
 
        if not use_direct_path:
1521
 
            return DiskTreeTransform._generate_limbo_path(self, trans_id)
1522
 
 
1523
 
        limbo_name = pathjoin(self._limbo_files[parent], filename)
1524
 
        self._limbo_children[parent].add(trans_id)
1525
 
        self._limbo_children_names[parent][filename] = trans_id
1526
 
        return limbo_name
1527
 
 
1528
 
 
1529
1326
    def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
1530
1327
        """Apply all changes to the inventory and filesystem.
1531
1328
 
1541
1338
        :param _mover: Supply an alternate FileMover, for testing
1542
1339
        """
1543
1340
        if not no_conflicts:
1544
 
            self._check_malformed()
 
1341
            conflicts = self.find_conflicts()
 
1342
            if len(conflicts) != 0:
 
1343
                raise MalformedTransform(conflicts=conflicts)
1545
1344
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1546
1345
        try:
1547
1346
            if precomputed_delta is None:
1651
1450
                child_pb.update('removing file', num, len(tree_paths))
1652
1451
                full_path = self._tree.abspath(path)
1653
1452
                if trans_id in self._removed_contents:
1654
 
                    delete_path = os.path.join(self._deletiondir, trans_id)
1655
 
                    mover.pre_delete(full_path, delete_path)
1656
 
                elif (trans_id in self._new_name
1657
 
                      or trans_id in self._new_parent):
 
1453
                    mover.pre_delete(full_path, os.path.join(self._deletiondir,
 
1454
                                     trans_id))
 
1455
                elif trans_id in self._new_name or trans_id in \
 
1456
                    self._new_parent:
1658
1457
                    try:
1659
1458
                        mover.rename(full_path, self._limbo_name(trans_id))
1660
 
                    except errors.TransformRenameFailed, e:
 
1459
                    except OSError, e:
1661
1460
                        if e.errno != errno.ENOENT:
1662
1461
                            raise
1663
1462
                    else:
1688
1487
                if trans_id in self._needs_rename:
1689
1488
                    try:
1690
1489
                        mover.rename(self._limbo_name(trans_id), full_path)
1691
 
                    except errors.TransformRenameFailed, e:
 
1490
                    except OSError, e:
1692
1491
                        # We may be renaming a dangling inventory id
1693
1492
                        if e.errno != errno.ENOENT:
1694
1493
                            raise
1706
1505
        return modified_paths
1707
1506
 
1708
1507
 
1709
 
class TransformPreview(DiskTreeTransform):
 
1508
class TransformPreview(TreeTransformBase):
1710
1509
    """A TreeTransform for generating preview trees.
1711
1510
 
1712
1511
    Unlike TreeTransform, this version works when the input tree is a
1714
1513
    unversioned files in the input tree.
1715
1514
    """
1716
1515
 
1717
 
    def __init__(self, tree, pb=None, case_sensitive=True):
 
1516
    def __init__(self, tree, pb=DummyProgress(), case_sensitive=True):
1718
1517
        tree.lock_read()
1719
1518
        limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
1720
 
        DiskTreeTransform.__init__(self, tree, limbodir, pb, case_sensitive)
 
1519
        TreeTransformBase.__init__(self, tree, limbodir, pb, case_sensitive)
1721
1520
 
1722
1521
    def canonical_path(self, path):
1723
1522
        return path
1765
1564
        self._all_children_cache = {}
1766
1565
        self._path2trans_id_cache = {}
1767
1566
        self._final_name_cache = {}
1768
 
        self._iter_changes_cache = dict((c[0], c) for c in
1769
 
                                        self._transform.iter_changes())
 
1567
 
 
1568
    def _changes(self, file_id):
 
1569
        for changes in self._transform.iter_changes():
 
1570
            if changes[0] == file_id:
 
1571
                return changes
1770
1572
 
1771
1573
    def _content_change(self, file_id):
1772
1574
        """Return True if the content of this file changed"""
1773
 
        changes = self._iter_changes_cache.get(file_id)
 
1575
        changes = self._changes(file_id)
1774
1576
        # changes[2] is true if the file content changed.  See
1775
1577
        # InterTree.iter_changes.
1776
1578
        return (changes is not None and changes[2])
1792
1594
        parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
1793
1595
                       self._iter_parent_trees()]
1794
1596
        vf.add_lines((file_id, tree_revision), parent_keys,
1795
 
                     self.get_file_lines(file_id))
 
1597
                     self.get_file(file_id).readlines())
1796
1598
        repo = self._get_repository()
1797
1599
        base_vf = repo.texts
1798
1600
        if base_vf not in vf.fallback_versionedfiles:
1820
1622
            executable = self.is_executable(file_id, path)
1821
1623
        return kind, executable, None
1822
1624
 
1823
 
    def is_locked(self):
1824
 
        return False
1825
 
 
1826
1625
    def lock_read(self):
1827
1626
        # Perhaps in theory, this should lock the TreeTransform?
1828
 
        return self
 
1627
        pass
1829
1628
 
1830
1629
    def unlock(self):
1831
1630
        pass
1848
1647
    def __iter__(self):
1849
1648
        return iter(self.all_file_ids())
1850
1649
 
1851
 
    def _has_id(self, file_id, fallback_check):
 
1650
    def has_id(self, file_id):
1852
1651
        if file_id in self._transform._r_new_id:
1853
1652
            return True
1854
1653
        elif file_id in set([self._transform.tree_file_id(trans_id) for
1855
1654
            trans_id in self._transform._removed_id]):
1856
1655
            return False
1857
1656
        else:
1858
 
            return fallback_check(file_id)
1859
 
 
1860
 
    def has_id(self, file_id):
1861
 
        return self._has_id(file_id, self._transform._tree.has_id)
1862
 
 
1863
 
    def has_or_had_id(self, file_id):
1864
 
        return self._has_id(file_id, self._transform._tree.has_or_had_id)
 
1657
            return self._transform._tree.has_id(file_id)
1865
1658
 
1866
1659
    def _path2trans_id(self, path):
1867
1660
        # We must not use None here, because that is a valid value to store.
1920
1713
            if self._transform.final_file_id(trans_id) is None:
1921
1714
                yield self._final_paths._determine_path(trans_id)
1922
1715
 
1923
 
    def _make_inv_entries(self, ordered_entries, specific_file_ids=None,
1924
 
        yield_parents=False):
 
1716
    def _make_inv_entries(self, ordered_entries, specific_file_ids):
1925
1717
        for trans_id, parent_file_id in ordered_entries:
1926
1718
            file_id = self._transform.final_file_id(trans_id)
1927
1719
            if file_id is None:
1953
1745
                ordered_ids.append((trans_id, parent_file_id))
1954
1746
        return ordered_ids
1955
1747
 
1956
 
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
 
1748
    def iter_entries_by_dir(self, specific_file_ids=None):
1957
1749
        # This may not be a maximally efficient implementation, but it is
1958
1750
        # reasonably straightforward.  An implementation that grafts the
1959
1751
        # TreeTransform changes onto the tree's iter_entries_by_dir results
1961
1753
        # position.
1962
1754
        ordered_ids = self._list_files_by_dir()
1963
1755
        for entry, trans_id in self._make_inv_entries(ordered_ids,
1964
 
            specific_file_ids, yield_parents=yield_parents):
1965
 
            yield unicode(self._final_paths.get_path(trans_id)), entry
1966
 
 
1967
 
    def _iter_entries_for_dir(self, dir_path):
1968
 
        """Return path, entry for items in a directory without recursing down."""
1969
 
        dir_file_id = self.path2id(dir_path)
1970
 
        ordered_ids = []
1971
 
        for file_id in self.iter_children(dir_file_id):
1972
 
            trans_id = self._transform.trans_id_file_id(file_id)
1973
 
            ordered_ids.append((trans_id, file_id))
1974
 
        for entry, trans_id in self._make_inv_entries(ordered_ids):
1975
 
            yield unicode(self._final_paths.get_path(trans_id)), entry
1976
 
 
1977
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
1978
 
        """See WorkingTree.list_files."""
 
1756
                                                      specific_file_ids):
 
1757
            yield unicode(self._final_paths.get_path(trans_id)), entry
 
1758
 
 
1759
    def list_files(self, include_root=False):
 
1760
        """See Tree.list_files."""
1979
1761
        # XXX This should behave like WorkingTree.list_files, but is really
1980
1762
        # more like RevisionTree.list_files.
1981
 
        if recursive:
1982
 
            prefix = None
1983
 
            if from_dir:
1984
 
                prefix = from_dir + '/'
1985
 
            entries = self.iter_entries_by_dir()
1986
 
            for path, entry in entries:
1987
 
                if entry.name == '' and not include_root:
1988
 
                    continue
1989
 
                if prefix:
1990
 
                    if not path.startswith(prefix):
1991
 
                        continue
1992
 
                    path = path[len(prefix):]
1993
 
                yield path, 'V', entry.kind, entry.file_id, entry
1994
 
        else:
1995
 
            if from_dir is None and include_root is True:
1996
 
                root_entry = inventory.make_entry('directory', '',
1997
 
                    ROOT_PARENT, self.get_root_id())
1998
 
                yield '', 'V', 'directory', root_entry.file_id, root_entry
1999
 
            entries = self._iter_entries_for_dir(from_dir or '')
2000
 
            for path, entry in entries:
2001
 
                yield path, 'V', entry.kind, entry.file_id, entry
 
1763
        for path, entry in self.iter_entries_by_dir():
 
1764
            if entry.name == '' and not include_root:
 
1765
                continue
 
1766
            yield path, 'V', entry.kind, entry.file_id, entry
2002
1767
 
2003
1768
    def kind(self, file_id):
2004
1769
        trans_id = self._transform.trans_id_file_id(file_id)
2014
1779
    def get_file_mtime(self, file_id, path=None):
2015
1780
        """See Tree.get_file_mtime"""
2016
1781
        if not self._content_change(file_id):
2017
 
            return self._transform._tree.get_file_mtime(file_id)
 
1782
            return self._transform._tree.get_file_mtime(file_id, path)
2018
1783
        return self._stat_limbo_file(file_id).st_mtime
2019
1784
 
2020
1785
    def _file_size(self, entry, stat_value):
2074
1839
                statval = os.lstat(limbo_name)
2075
1840
                size = statval.st_size
2076
1841
                if not supports_executable():
2077
 
                    executable = False
 
1842
                    executable = None
2078
1843
                else:
2079
1844
                    executable = statval.st_mode & S_IEXEC
2080
1845
            else:
2082
1847
                executable = None
2083
1848
            if kind == 'symlink':
2084
1849
                link_or_sha1 = os.readlink(limbo_name).decode(osutils._fs_enc)
2085
 
        executable = tt._new_executability.get(trans_id, executable)
 
1850
        if supports_executable():
 
1851
            executable = tt._new_executability.get(trans_id, executable)
2086
1852
        return kind, size, executable, link_or_sha1
2087
1853
 
2088
1854
    def iter_changes(self, from_tree, include_unchanged=False,
2114
1880
        name = self._transform._limbo_name(trans_id)
2115
1881
        return open(name, 'rb')
2116
1882
 
2117
 
    def get_file_with_stat(self, file_id, path=None):
2118
 
        return self.get_file(file_id, path), None
2119
 
 
2120
1883
    def annotate_iter(self, file_id,
2121
1884
                      default_revision=_mod_revision.CURRENT_REVISION):
2122
 
        changes = self._iter_changes_cache.get(file_id)
 
1885
        changes = self._changes(file_id)
2123
1886
        if changes is None:
2124
1887
            get_old = True
2125
1888
        else:
2137
1900
            return old_annotation
2138
1901
        if not changed_content:
2139
1902
            return old_annotation
2140
 
        # TODO: This is doing something similar to what WT.annotate_iter is
2141
 
        #       doing, however it fails slightly because it doesn't know what
2142
 
        #       the *other* revision_id is, so it doesn't know how to give the
2143
 
        #       other as the origin for some lines, they all get
2144
 
        #       'default_revision'
2145
 
        #       It would be nice to be able to use the new Annotator based
2146
 
        #       approach, as well.
2147
1903
        return annotate.reannotate([old_annotation],
2148
1904
                                   self.get_file(file_id).readlines(),
2149
1905
                                   default_revision)
2154
1910
            return self._transform._tree.get_symlink_target(file_id)
2155
1911
        trans_id = self._transform.trans_id_file_id(file_id)
2156
1912
        name = self._transform._limbo_name(trans_id)
2157
 
        return osutils.readlink(name)
 
1913
        return os.readlink(name)
2158
1914
 
2159
1915
    def walkdirs(self, prefix=''):
2160
1916
        pending = [self._transform.root]
2215
1971
        self.transform = transform
2216
1972
 
2217
1973
    def _determine_path(self, trans_id):
2218
 
        if (trans_id == self.transform.root or trans_id == ROOT_PARENT):
 
1974
        if trans_id == self.transform.root:
2219
1975
            return ""
2220
1976
        name = self.transform.final_name(trans_id)
2221
1977
        parent_id = self.transform.final_parent(trans_id)
2291
2047
    for num, _unused in enumerate(wt.all_file_ids()):
2292
2048
        if num > 0:  # more than just a root
2293
2049
            raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
 
2050
    existing_files = set()
 
2051
    for dir, files in wt.walkdirs():
 
2052
        existing_files.update(f[0] for f in files)
2294
2053
    file_trans_id = {}
2295
2054
    top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2296
2055
    pp = ProgressPhase("Build phase", 2, top_pb)
2320
2079
                precomputed_delta = []
2321
2080
            else:
2322
2081
                precomputed_delta = None
2323
 
            # Check if tree inventory has content. If so, we populate
2324
 
            # existing_files with the directory content. If there are no
2325
 
            # entries we skip populating existing_files as its not used.
2326
 
            # This improves performance and unncessary work on large
2327
 
            # directory trees. (#501307)
2328
 
            if total > 0:
2329
 
                existing_files = set()
2330
 
                for dir, files in wt.walkdirs():
2331
 
                    existing_files.update(f[0] for f in files)
2332
2082
            for num, (tree_path, entry) in \
2333
2083
                enumerate(tree.inventory.iter_entries_by_dir()):
2334
2084
                pb.update("Building tree", num - len(deferred_contents), total)
2407
2157
        new_desired_files = desired_files
2408
2158
    else:
2409
2159
        iter = accelerator_tree.iter_changes(tree, include_unchanged=True)
2410
 
        unchanged = [(f, p[1]) for (f, p, c, v, d, n, k, e)
2411
 
                     in iter if not (c or e[0] != e[1])]
2412
 
        if accelerator_tree.supports_content_filtering():
2413
 
            unchanged = [(f, p) for (f, p) in unchanged
2414
 
                         if not accelerator_tree.iter_search_rules([p]).next()]
2415
 
        unchanged = dict(unchanged)
 
2160
        unchanged = dict((f, p[1]) for (f, p, c, v, d, n, k, e)
 
2161
                         in iter if not (c or e[0] != e[1]))
2416
2162
        new_desired_files = []
2417
2163
        count = 0
2418
2164
        for file_id, (trans_id, tree_path) in desired_files:
2466
2212
    if entry.kind == "directory":
2467
2213
        return True
2468
2214
    if entry.kind == "file":
2469
 
        f = file(target_path, 'rb')
2470
 
        try:
2471
 
            if tree.get_file_text(file_id) == f.read():
2472
 
                return True
2473
 
        finally:
2474
 
            f.close()
 
2215
        if tree.get_file(file_id).read() == file(target_path, 'rb').read():
 
2216
            return True
2475
2217
    elif entry.kind == "symlink":
2476
2218
        if tree.get_symlink_target(file_id) == os.readlink(target_path):
2477
2219
            return True
2545
2287
        tt.create_directory(trans_id)
2546
2288
 
2547
2289
 
2548
 
def create_from_tree(tt, trans_id, tree, file_id, bytes=None,
2549
 
    filter_tree_path=None):
2550
 
    """Create new file contents according to tree contents.
2551
 
    
2552
 
    :param filter_tree_path: the tree path to use to lookup
2553
 
      content filters to apply to the bytes output in the working tree.
2554
 
      This only applies if the working tree supports content filtering.
2555
 
    """
 
2290
def create_from_tree(tt, trans_id, tree, file_id, bytes=None):
 
2291
    """Create new file contents according to tree contents."""
2556
2292
    kind = tree.kind(file_id)
2557
2293
    if kind == 'directory':
2558
2294
        tt.create_directory(trans_id)
2563
2299
                bytes = tree_file.readlines()
2564
2300
            finally:
2565
2301
                tree_file.close()
2566
 
        wt = tt._tree
2567
 
        if wt.supports_content_filtering() and filter_tree_path is not None:
2568
 
            filters = wt._content_filter_stack(filter_tree_path)
2569
 
            bytes = filtered_output_bytes(bytes, filters,
2570
 
                ContentFilterContext(filter_tree_path, tree))
2571
2302
        tt.create_file(bytes, trans_id)
2572
2303
    elif kind == "symlink":
2573
2304
        tt.create_symlink(tree.get_symlink_target(file_id), trans_id)
2625
2356
 
2626
2357
 
2627
2358
def revert(working_tree, target_tree, filenames, backups=False,
2628
 
           pb=None, change_reporter=None):
 
2359
           pb=DummyProgress(), change_reporter=None):
2629
2360
    """Revert a working tree's contents to those of a target tree."""
2630
2361
    target_tree.lock_read()
2631
 
    pb = ui.ui_factory.nested_progress_bar()
2632
2362
    tt = TreeTransform(working_tree, pb)
2633
2363
    try:
2634
2364
        pp = ProgressPhase("Revert phase", 3, pb)
2653
2383
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
2654
2384
                              backups, pp, basis_tree=None,
2655
2385
                              merge_modified=None):
 
2386
    pp.next_phase()
2656
2387
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2657
2388
    try:
2658
2389
        if merge_modified is None:
2662
2393
                                      merge_modified, basis_tree)
2663
2394
    finally:
2664
2395
        child_pb.finished()
 
2396
    pp.next_phase()
2665
2397
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2666
2398
    try:
2667
2399
        raw_conflicts = resolve_conflicts(tt, child_pb,
2760
2492
                    parent_trans = ROOT_PARENT
2761
2493
                else:
2762
2494
                    parent_trans = tt.trans_id_file_id(parent[1])
2763
 
                if parent[0] is None and versioned[0]:
2764
 
                    tt.adjust_root_path(name[1], parent_trans)
2765
 
                else:
2766
 
                    tt.adjust_path(name[1], parent_trans, trans_id)
 
2495
                tt.adjust_path(name[1], parent_trans, trans_id)
2767
2496
            if executable[0] != executable[1] and kind[1] == "file":
2768
2497
                tt.set_executability(executable[1], trans_id)
2769
 
        if working_tree.supports_content_filtering():
2770
 
            for index, ((trans_id, mode_id), bytes) in enumerate(
2771
 
                target_tree.iter_files_bytes(deferred_files)):
2772
 
                file_id = deferred_files[index][0]
2773
 
                # We're reverting a tree to the target tree so using the
2774
 
                # target tree to find the file path seems the best choice
2775
 
                # here IMO - Ian C 27/Oct/2009
2776
 
                filter_tree_path = target_tree.id2path(file_id)
2777
 
                filters = working_tree._content_filter_stack(filter_tree_path)
2778
 
                bytes = filtered_output_bytes(bytes, filters,
2779
 
                    ContentFilterContext(filter_tree_path, working_tree))
2780
 
                tt.create_file(bytes, trans_id, mode_id)
2781
 
        else:
2782
 
            for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
2783
 
                deferred_files):
2784
 
                tt.create_file(bytes, trans_id, mode_id)
2785
 
        tt.fixup_new_roots()
 
2498
        for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
 
2499
            deferred_files):
 
2500
            tt.create_file(bytes, trans_id, mode_id)
2786
2501
    finally:
2787
2502
        if basis_tree is not None:
2788
2503
            basis_tree.unlock()
2789
2504
    return merge_modified
2790
2505
 
2791
2506
 
2792
 
def resolve_conflicts(tt, pb=None, pass_func=None):
 
2507
def resolve_conflicts(tt, pb=DummyProgress(), pass_func=None):
2793
2508
    """Make many conflict-resolution attempts, but die if they fail"""
2794
2509
    if pass_func is None:
2795
2510
        pass_func = conflict_pass
2796
2511
    new_conflicts = set()
2797
 
    pb = ui.ui_factory.nested_progress_bar()
2798
2512
    try:
2799
2513
        for n in range(10):
2800
2514
            pb.update('Resolution pass', n+1, 10)
2804
2518
            new_conflicts.update(pass_func(tt, conflicts))
2805
2519
        raise MalformedTransform(conflicts=conflicts)
2806
2520
    finally:
2807
 
        pb.finished()
 
2521
        pb.clear()
2808
2522
 
2809
2523
 
2810
2524
def conflict_pass(tt, conflicts, path_tree=None):
2859
2573
                        # special-case the other tree root (move its
2860
2574
                        # children to current root)
2861
2575
                        if entry.parent_id is None:
2862
 
                            create = False
 
2576
                            create=False
2863
2577
                            moved = _reparent_transform_children(
2864
2578
                                tt, trans_id, tt.root)
2865
2579
                            for child in moved:
2933
2647
        self.pending_deletions = []
2934
2648
 
2935
2649
    def rename(self, from_, to):
2936
 
        """Rename a file from one path to another."""
 
2650
        """Rename a file from one path to another.  Functions like os.rename"""
2937
2651
        try:
2938
 
            osutils.rename(from_, to)
2939
 
        except (IOError, OSError), e:
 
2652
            os.rename(from_, to)
 
2653
        except OSError, e:
2940
2654
            if e.errno in (errno.EEXIST, errno.ENOTEMPTY):
2941
2655
                raise errors.FileExists(to, str(e))
2942
 
            # normal OSError doesn't include filenames so it's hard to see where
2943
 
            # the problem is, see https://bugs.launchpad.net/bzr/+bug/491763
2944
 
            raise errors.TransformRenameFailed(from_, to, str(e), e.errno)
 
2656
            raise
2945
2657
        self.past_renames.append((from_, to))
2946
2658
 
2947
2659
    def pre_delete(self, from_, to):
2957
2669
    def rollback(self):
2958
2670
        """Reverse all renames that have been performed"""
2959
2671
        for from_, to in reversed(self.past_renames):
2960
 
            try:
2961
 
                osutils.rename(to, from_)
2962
 
            except (OSError, IOError), e:
2963
 
                raise errors.TransformRenameFailed(to, from_, str(e), e.errno)                
 
2672
            os.rename(to, from_)
2964
2673
        # after rollback, don't reuse _FileMover
2965
2674
        past_renames = None
2966
2675
        pending_deletions = None