/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

Initial commit for russian version of documents.

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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
import os
18
18
import errno
19
19
from stat import S_ISREG, S_IEXEC
20
 
import time
 
20
import tempfile
21
21
 
22
22
from bzrlib.lazy_import import lazy_import
23
23
lazy_import(globals(), """
24
24
from bzrlib import (
25
25
    annotate,
26
 
    bencode,
27
26
    bzrdir,
28
 
    commit,
29
27
    delta,
30
28
    errors,
31
29
    inventory,
32
 
    multiparent,
33
30
    osutils,
34
31
    revision as _mod_revision,
35
 
    ui,
36
32
    )
37
33
""")
38
34
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
39
 
                           ReusingTransform, CantMoveRoot,
 
35
                           ReusingTransform, NotVersionedError, CantMoveRoot,
40
36
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
41
37
                           UnableCreateSymlink)
42
 
from bzrlib.filters import filtered_output_bytes, ContentFilterContext
43
38
from bzrlib.inventory import InventoryEntry
44
39
from bzrlib.osutils import (
45
40
    delete_any,
47
42
    has_symlinks,
48
43
    lexists,
49
44
    pathjoin,
50
 
    sha_file,
51
45
    splitpath,
52
46
    supports_executable,
53
47
)
54
 
from bzrlib.progress import ProgressPhase
 
48
from bzrlib.progress import DummyProgress, ProgressPhase
55
49
from bzrlib.symbol_versioning import (
56
50
        deprecated_function,
57
 
        deprecated_in,
58
51
        )
59
52
from bzrlib.trace import mutter, warning
60
53
from bzrlib import tree
79
72
 
80
73
 
81
74
class TreeTransformBase(object):
82
 
    """The base class for TreeTransform and its kin."""
 
75
    """The base class for TreeTransform and TreeTransformBase"""
83
76
 
84
 
    def __init__(self, tree, pb=None,
 
77
    def __init__(self, tree, limbodir, pb=DummyProgress(),
85
78
                 case_sensitive=True):
86
79
        """Constructor.
87
80
 
88
81
        :param tree: The tree that will be transformed, but not necessarily
89
82
            the output tree.
90
 
        :param pb: ignored
 
83
        :param limbodir: A directory where new files can be stored until
 
84
            they are installed in their proper places
 
85
        :param pb: A ProgressBar indicating how much progress is being made
91
86
        :param case_sensitive: If True, the target of the transform is
92
87
            case sensitive, not just case preserving.
93
88
        """
94
89
        object.__init__(self)
95
90
        self._tree = tree
 
91
        self._limbodir = limbodir
 
92
        self._deletiondir = None
96
93
        self._id_number = 0
97
94
        # mapping of trans_id -> new basename
98
95
        self._new_name = {}
100
97
        self._new_parent = {}
101
98
        # mapping of trans_id with new contents -> new file_kind
102
99
        self._new_contents = {}
 
100
        # A mapping of transform ids to their limbo filename
 
101
        self._limbo_files = {}
 
102
        # A mapping of transform ids to a set of the transform ids of children
 
103
        # that their limbo directory has
 
104
        self._limbo_children = {}
 
105
        # Map transform ids to maps of child filename to child transform id
 
106
        self._limbo_children_names = {}
 
107
        # List of transform ids that need to be renamed from limbo into place
 
108
        self._needs_rename = set()
103
109
        # Set of trans_ids whose contents will be removed
104
110
        self._removed_contents = set()
105
111
        # Mapping of trans_id -> new execute-bit value
112
118
        self._non_present_ids = {}
113
119
        # Mapping of new file_id -> trans_id
114
120
        self._r_new_id = {}
115
 
        # Set of trans_ids that will be removed
 
121
        # Set of file_ids that will be removed
116
122
        self._removed_id = set()
117
123
        # Mapping of path in old tree -> trans_id
118
124
        self._tree_path_ids = {}
119
125
        # Mapping trans_id -> path in old tree
120
126
        self._tree_id_paths = {}
 
127
        # Cache of realpath results, to speed up canonical_path
 
128
        self._realpaths = {}
 
129
        # Cache of relpath results, to speed up canonical_path
 
130
        self._relpaths = {}
121
131
        # The trans_id that will be used as the tree root
122
 
        root_id = tree.get_root_id()
123
 
        if root_id is not None:
124
 
            self._new_root = self.trans_id_tree_file_id(root_id)
125
 
        else:
126
 
            self._new_root = None
 
132
        self._new_root = self.trans_id_tree_file_id(tree.get_root_id())
127
133
        # Indictor of whether the transform has been applied
128
134
        self._done = False
129
135
        # A progress bar
133
139
        # A counter of how many files have been renamed
134
140
        self.rename_count = 0
135
141
 
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
142
    def __get_root(self):
148
143
        return self._new_root
149
144
 
150
145
    root = property(__get_root)
151
146
 
 
147
    def finalize(self):
 
148
        """Release the working tree lock, if held, clean up limbo dir.
 
149
 
 
150
        This is required if apply has not been invoked, but can be invoked
 
151
        even after apply.
 
152
        """
 
153
        if self._tree is None:
 
154
            return
 
155
        try:
 
156
            entries = [(self._limbo_name(t), t, k) for t, k in
 
157
                       self._new_contents.iteritems()]
 
158
            entries.sort(reverse=True)
 
159
            for path, trans_id, kind in entries:
 
160
                if kind == "directory":
 
161
                    os.rmdir(path)
 
162
                else:
 
163
                    os.unlink(path)
 
164
            try:
 
165
                os.rmdir(self._limbodir)
 
166
            except OSError:
 
167
                # We don't especially care *why* the dir is immortal.
 
168
                raise ImmortalLimbo(self._limbodir)
 
169
            try:
 
170
                if self._deletiondir is not None:
 
171
                    os.rmdir(self._deletiondir)
 
172
            except OSError:
 
173
                raise errors.ImmortalPendingDeletion(self._deletiondir)
 
174
        finally:
 
175
            self._tree.unlock()
 
176
            self._tree = None
 
177
 
152
178
    def _assign_id(self):
153
179
        """Produce a new tranform id"""
154
180
        new_id = "new-%s" % self._id_number
164
190
 
165
191
    def adjust_path(self, name, parent, trans_id):
166
192
        """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
193
        if trans_id == self._new_root:
170
194
            raise CantMoveRoot
 
195
        previous_parent = self._new_parent.get(trans_id)
 
196
        previous_name = self._new_name.get(trans_id)
171
197
        self._new_name[trans_id] = name
172
198
        self._new_parent[trans_id] = parent
 
199
        if (trans_id in self._limbo_files and
 
200
            trans_id not in self._needs_rename):
 
201
            self._rename_in_limbo([trans_id])
 
202
            self._limbo_children[previous_parent].remove(trans_id)
 
203
            del self._limbo_children_names[previous_parent][previous_name]
 
204
 
 
205
    def _rename_in_limbo(self, trans_ids):
 
206
        """Fix limbo names so that the right final path is produced.
 
207
 
 
208
        This means we outsmarted ourselves-- we tried to avoid renaming
 
209
        these files later by creating them with their final names in their
 
210
        final parents.  But now the previous name or parent is no longer
 
211
        suitable, so we have to rename them.
 
212
 
 
213
        Even for trans_ids that have no new contents, we must remove their
 
214
        entries from _limbo_files, because they are now stale.
 
215
        """
 
216
        for trans_id in trans_ids:
 
217
            old_path = self._limbo_files.pop(trans_id)
 
218
            if trans_id not in self._new_contents:
 
219
                continue
 
220
            new_path = self._limbo_name(trans_id)
 
221
            os.rename(old_path, new_path)
173
222
 
174
223
    def adjust_root_path(self, name, parent):
175
224
        """Emulate moving the root by moving all children, instead.
176
 
 
 
225
        
177
226
        We do this by undoing the association of root's transaction id with the
178
227
        current tree.  This allows us to create a new directory with that
179
 
        transaction id.  We unversion the root directory and version the
 
228
        transaction id.  We unversion the root directory and version the 
180
229
        physically new directory, and hope someone versions the tree root
181
230
        later.
182
231
        """
185
234
        # force moving all children of root
186
235
        for child_id in self.iter_tree_children(old_root):
187
236
            if child_id != parent:
188
 
                self.adjust_path(self.final_name(child_id),
 
237
                self.adjust_path(self.final_name(child_id), 
189
238
                                 self.final_parent(child_id), child_id)
190
239
            file_id = self.final_file_id(child_id)
191
240
            if file_id is not None:
192
241
                self.unversion_file(child_id)
193
242
            self.version_file(file_id, child_id)
194
 
 
 
243
        
195
244
        # the physical root needs a new transaction id
196
245
        self._tree_path_ids.pop("")
197
246
        self._tree_id_paths.pop(old_root)
203
252
        self.version_file(old_root_file_id, old_root)
204
253
        self.unversion_file(self._new_root)
205
254
 
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
255
    def trans_id_tree_file_id(self, inventory_id):
268
256
        """Determine the transaction id of a working tree file.
269
 
 
 
257
        
270
258
        This reflects only files that already exist, not ones that will be
271
259
        added by transactions.
272
260
        """
273
 
        if inventory_id is None:
274
 
            raise ValueError('None is not a valid file id')
275
261
        path = self._tree.id2path(inventory_id)
276
262
        return self.trans_id_tree_path(path)
277
263
 
281
267
        a transaction has been unversioned, it is deliberately still returned.
282
268
        (this will likely lead to an unversioned parent conflict.)
283
269
        """
284
 
        if file_id is None:
285
 
            raise ValueError('None is not a valid file id')
286
270
        if file_id in self._r_new_id and self._r_new_id[file_id] is not None:
287
271
            return self._r_new_id[file_id]
288
 
        else:
289
 
            try:
290
 
                self._tree.iter_entries_by_dir([file_id]).next()
291
 
            except StopIteration:
292
 
                if file_id in self._non_present_ids:
293
 
                    return self._non_present_ids[file_id]
294
 
                else:
295
 
                    trans_id = self._assign_id()
296
 
                    self._non_present_ids[file_id] = trans_id
297
 
                    return trans_id
298
 
            else:
299
 
                return self.trans_id_tree_file_id(file_id)
 
272
        elif file_id in self._tree.inventory:
 
273
            return self.trans_id_tree_file_id(file_id)
 
274
        elif file_id in self._non_present_ids:
 
275
            return self._non_present_ids[file_id]
 
276
        else:
 
277
            trans_id = self._assign_id()
 
278
            self._non_present_ids[file_id] = trans_id
 
279
            return trans_id
 
280
 
 
281
    def canonical_path(self, path):
 
282
        """Get the canonical tree-relative path"""
 
283
        # don't follow final symlinks
 
284
        abs = self._tree.abspath(path)
 
285
        if abs in self._relpaths:
 
286
            return self._relpaths[abs]
 
287
        dirname, basename = os.path.split(abs)
 
288
        if dirname not in self._realpaths:
 
289
            self._realpaths[dirname] = os.path.realpath(dirname)
 
290
        dirname = self._realpaths[dirname]
 
291
        abs = pathjoin(dirname, basename)
 
292
        if dirname in self._relpaths:
 
293
            relpath = pathjoin(self._relpaths[dirname], basename)
 
294
            relpath = relpath.rstrip('/\\')
 
295
        else:
 
296
            relpath = self._tree.relpath(abs)
 
297
        self._relpaths[abs] = relpath
 
298
        return relpath
300
299
 
301
300
    def trans_id_tree_path(self, path):
302
301
        """Determine (and maybe set) the transaction ID for a tree path."""
313
312
            return ROOT_PARENT
314
313
        return self.trans_id_tree_path(os.path.dirname(path))
315
314
 
 
315
    def create_file(self, contents, trans_id, mode_id=None):
 
316
        """Schedule creation of a new file.
 
317
 
 
318
        See also new_file.
 
319
        
 
320
        Contents is an iterator of strings, all of which will be written
 
321
        to the target destination.
 
322
 
 
323
        New file takes the permissions of any existing file with that id,
 
324
        unless mode_id is specified.
 
325
        """
 
326
        name = self._limbo_name(trans_id)
 
327
        f = open(name, 'wb')
 
328
        try:
 
329
            try:
 
330
                unique_add(self._new_contents, trans_id, 'file')
 
331
            except:
 
332
                # Clean up the file, it never got registered so
 
333
                # TreeTransform.finalize() won't clean it up.
 
334
                f.close()
 
335
                os.unlink(name)
 
336
                raise
 
337
 
 
338
            f.writelines(contents)
 
339
        finally:
 
340
            f.close()
 
341
        self._set_mode(trans_id, mode_id, S_ISREG)
 
342
 
 
343
    def _set_mode(self, trans_id, mode_id, typefunc):
 
344
        """Set the mode of new file contents.
 
345
        The mode_id is the existing file to get the mode from (often the same
 
346
        as trans_id).  The operation is only performed if there's a mode match
 
347
        according to typefunc.
 
348
        """
 
349
        if mode_id is None:
 
350
            mode_id = trans_id
 
351
        try:
 
352
            old_path = self._tree_id_paths[mode_id]
 
353
        except KeyError:
 
354
            return
 
355
        try:
 
356
            mode = os.stat(self._tree.abspath(old_path)).st_mode
 
357
        except OSError, e:
 
358
            if e.errno in (errno.ENOENT, errno.ENOTDIR):
 
359
                # Either old_path doesn't exist, or the parent of the
 
360
                # target is not a directory (but will be one eventually)
 
361
                # Either way, we know it doesn't exist *right now*
 
362
                # See also bug #248448
 
363
                return
 
364
            else:
 
365
                raise
 
366
        if typefunc(mode):
 
367
            os.chmod(self._limbo_name(trans_id), mode)
 
368
 
 
369
    def create_hardlink(self, path, trans_id):
 
370
        """Schedule creation of a hard link"""
 
371
        name = self._limbo_name(trans_id)
 
372
        try:
 
373
            os.link(path, name)
 
374
        except OSError, e:
 
375
            if e.errno != errno.EPERM:
 
376
                raise
 
377
            raise errors.HardLinkNotSupported(path)
 
378
        try:
 
379
            unique_add(self._new_contents, trans_id, 'file')
 
380
        except:
 
381
            # Clean up the file, it never got registered so
 
382
            # TreeTransform.finalize() won't clean it up.
 
383
            os.unlink(name)
 
384
            raise
 
385
 
 
386
    def create_directory(self, trans_id):
 
387
        """Schedule creation of a new directory.
 
388
        
 
389
        See also new_directory.
 
390
        """
 
391
        os.mkdir(self._limbo_name(trans_id))
 
392
        unique_add(self._new_contents, trans_id, 'directory')
 
393
 
 
394
    def create_symlink(self, target, trans_id):
 
395
        """Schedule creation of a new symbolic link.
 
396
 
 
397
        target is a bytestring.
 
398
        See also new_symlink.
 
399
        """
 
400
        if has_symlinks():
 
401
            os.symlink(target, self._limbo_name(trans_id))
 
402
            unique_add(self._new_contents, trans_id, 'symlink')
 
403
        else:
 
404
            try:
 
405
                path = FinalPaths(self).get_path(trans_id)
 
406
            except KeyError:
 
407
                path = None
 
408
            raise UnableCreateSymlink(path=path)
 
409
 
 
410
    def cancel_creation(self, trans_id):
 
411
        """Cancel the creation of new file contents."""
 
412
        del self._new_contents[trans_id]
 
413
        children = self._limbo_children.get(trans_id)
 
414
        # if this is a limbo directory with children, move them before removing
 
415
        # the directory
 
416
        if children is not None:
 
417
            self._rename_in_limbo(children)
 
418
            del self._limbo_children[trans_id]
 
419
            del self._limbo_children_names[trans_id]
 
420
        delete_any(self._limbo_name(trans_id))
 
421
 
316
422
    def delete_contents(self, trans_id):
317
423
        """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
424
        self.tree_kind(trans_id)
321
425
        self._removed_contents.add(trans_id)
322
426
 
394
498
        new_ids.update(changed_kind)
395
499
        return sorted(FinalPaths(self).get_paths(new_ids))
396
500
 
 
501
    def tree_kind(self, trans_id):
 
502
        """Determine the file kind in the working tree.
 
503
 
 
504
        Raises NoSuchFile if the file does not exist
 
505
        """
 
506
        path = self._tree_id_paths.get(trans_id)
 
507
        if path is None:
 
508
            raise NoSuchFile(None)
 
509
        try:
 
510
            return file_kind(self._tree.abspath(path))
 
511
        except OSError, e:
 
512
            if e.errno != errno.ENOENT:
 
513
                raise
 
514
            else:
 
515
                raise NoSuchFile(path)
 
516
 
397
517
    def final_kind(self, trans_id):
398
518
        """Determine the final file kind, after any changes applied.
399
 
 
 
519
        
400
520
        Raises NoSuchFile if the file does not exist/has no contents.
401
521
        (It is conceivable that a path would be created without the
402
522
        corresponding contents insertion command)
418
538
        # the file is old; the old id is still valid
419
539
        if self._new_root == trans_id:
420
540
            return self._tree.get_root_id()
421
 
        return self._tree.path2id(path)
 
541
        return self._tree.inventory.path2id(path)
422
542
 
423
543
    def final_file_id(self, trans_id):
424
544
        """Determine the file id after any changes are applied, or None.
425
 
 
 
545
        
426
546
        None indicates that the file will not be versioned after changes are
427
547
        applied.
428
548
        """
467
587
 
468
588
    def by_parent(self):
469
589
        """Return a map of parent: children for known parents.
470
 
 
 
590
        
471
591
        Only new paths and parents of tree files with assigned ids are used.
472
592
        """
473
593
        by_parent = {}
474
594
        items = list(self._new_parent.iteritems())
475
 
        items.extend((t, self.final_parent(t)) for t in
 
595
        items.extend((t, self.final_parent(t)) for t in 
476
596
                      self._tree_id_paths.keys())
477
597
        for trans_id, parent_id in items:
478
598
            if parent_id not in by_parent:
506
626
        conflicts.extend(self._overwrite_conflicts())
507
627
        return conflicts
508
628
 
509
 
    def _check_malformed(self):
510
 
        conflicts = self.find_conflicts()
511
 
        if len(conflicts) != 0:
512
 
            raise MalformedTransform(conflicts=conflicts)
513
 
 
514
629
    def _add_tree_children(self):
515
630
        """Add all the children of all active parents to the known paths.
516
631
 
518
633
        removed.  This is a necessary first step in detecting conflicts.
519
634
        """
520
635
        parents = self.by_parent().keys()
521
 
        parents.extend([t for t in self._removed_contents if
 
636
        parents.extend([t for t in self._removed_contents if 
522
637
                        self.tree_kind(t) == 'directory'])
523
638
        for trans_id in self._removed_id:
524
639
            file_id = self.tree_file_id(trans_id)
532
647
            # ensure that all children are registered with the transaction
533
648
            list(self.iter_tree_children(parent_id))
534
649
 
 
650
    def iter_tree_children(self, parent_id):
 
651
        """Iterate through the entry's tree children, if any"""
 
652
        try:
 
653
            path = self._tree_id_paths[parent_id]
 
654
        except KeyError:
 
655
            return
 
656
        try:
 
657
            children = os.listdir(self._tree.abspath(path))
 
658
        except OSError, e:
 
659
            if not (osutils._is_error_enotdir(e)
 
660
                    or e.errno in (errno.ENOENT, errno.ESRCH)):
 
661
                raise
 
662
            return
 
663
 
 
664
        for child in children:
 
665
            childpath = joinpath(path, child)
 
666
            if self._tree.is_control_filename(childpath):
 
667
                continue
 
668
            yield self.trans_id_tree_path(childpath)
 
669
 
535
670
    def has_named_child(self, by_parent, parent_id, name):
536
671
        try:
537
672
            children = by_parent[parent_id]
591
726
 
592
727
    def _improper_versioning(self):
593
728
        """Cannot version a file with no contents, or a bad type.
594
 
 
 
729
        
595
730
        However, existing entries with no contents are okay.
596
731
        """
597
732
        conflicts = []
607
742
 
608
743
    def _executability_conflicts(self):
609
744
        """Check for bad executability changes.
610
 
 
 
745
        
611
746
        Only versioned files may have their executability set, because
612
747
        1. only versioned entries can have executability under windows
613
748
        2. only files can be executable.  (The execute bit on a directory
712
847
            return True
713
848
        return False
714
849
 
 
850
    def _limbo_name(self, trans_id):
 
851
        """Generate the limbo name of a file"""
 
852
        limbo_name = self._limbo_files.get(trans_id)
 
853
        if limbo_name is not None:
 
854
            return limbo_name
 
855
        parent = self._new_parent.get(trans_id)
 
856
        # if the parent directory is already in limbo (e.g. when building a
 
857
        # tree), choose a limbo name inside the parent, to reduce further
 
858
        # renames.
 
859
        use_direct_path = False
 
860
        if self._new_contents.get(parent) == 'directory':
 
861
            filename = self._new_name.get(trans_id)
 
862
            if filename is not None:
 
863
                if parent not in self._limbo_children:
 
864
                    self._limbo_children[parent] = set()
 
865
                    self._limbo_children_names[parent] = {}
 
866
                    use_direct_path = True
 
867
                # the direct path can only be used if no other file has
 
868
                # already taken this pathname, i.e. if the name is unused, or
 
869
                # if it is already associated with this trans_id.
 
870
                elif self._case_sensitive_target:
 
871
                    if (self._limbo_children_names[parent].get(filename)
 
872
                        in (trans_id, None)):
 
873
                        use_direct_path = True
 
874
                else:
 
875
                    for l_filename, l_trans_id in\
 
876
                        self._limbo_children_names[parent].iteritems():
 
877
                        if l_trans_id == trans_id:
 
878
                            continue
 
879
                        if l_filename.lower() == filename.lower():
 
880
                            break
 
881
                    else:
 
882
                        use_direct_path = True
 
883
 
 
884
        if use_direct_path:
 
885
            limbo_name = pathjoin(self._limbo_files[parent], filename)
 
886
            self._limbo_children[parent].add(trans_id)
 
887
            self._limbo_children_names[parent][filename] = trans_id
 
888
        else:
 
889
            limbo_name = pathjoin(self._limbodir, trans_id)
 
890
            self._needs_rename.add(trans_id)
 
891
        self._limbo_files[trans_id] = limbo_name
 
892
        return limbo_name
 
893
 
715
894
    def _set_executability(self, path, trans_id):
716
895
        """Set the executability of versioned files """
717
896
        if supports_executable():
738
917
            self.version_file(file_id, trans_id)
739
918
        return trans_id
740
919
 
741
 
    def new_file(self, name, parent_id, contents, file_id=None,
 
920
    def new_file(self, name, parent_id, contents, file_id=None, 
742
921
                 executable=None):
743
922
        """Convenience method to create files.
744
 
 
 
923
        
745
924
        name is the name of the file to create.
746
925
        parent_id is the transaction id of the parent directory of the file.
747
926
        contents is an iterator of bytestrings, which will be used to produce
767
946
        """
768
947
        trans_id = self._new_entry(name, parent_id, file_id)
769
948
        self.create_directory(trans_id)
770
 
        return trans_id
 
949
        return trans_id 
771
950
 
772
951
    def new_symlink(self, name, parent_id, target, file_id=None):
773
952
        """Convenience method to create symbolic link.
774
 
 
 
953
        
775
954
        name is the name of the symlink to create.
776
955
        parent_id is the transaction id of the parent directory of the symlink.
777
956
        target is a bytestring of the target of the symlink.
816
995
        from_path = self._tree_id_paths.get(from_trans_id)
817
996
        if from_versioned:
818
997
            # get data from working tree if versioned
819
 
            from_entry = self._tree.iter_entries_by_dir([file_id]).next()[1]
 
998
            from_entry = self._tree.inventory[file_id]
820
999
            from_name = from_entry.name
821
1000
            from_parent = from_entry.parent_id
822
1001
        else:
923
1102
    def get_preview_tree(self):
924
1103
        """Return a tree representing the result of the transform.
925
1104
 
926
 
        The tree is a snapshot, and altering the TreeTransform will invalidate
927
 
        it.
 
1105
        This tree only supports the subset of Tree functionality required
 
1106
        by show_diff_trees.  It must only be compared to tt._tree.
928
1107
        """
929
1108
        return _PreviewTree(self)
930
1109
 
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
 
    def _text_parent(self, trans_id):
990
 
        file_id = self.tree_file_id(trans_id)
991
 
        try:
992
 
            if file_id is None or self._tree.kind(file_id) != 'file':
993
 
                return None
994
 
        except errors.NoSuchFile:
995
 
            return None
996
 
        return file_id
997
 
 
998
 
    def _get_parents_texts(self, trans_id):
999
 
        """Get texts for compression parents of this file."""
1000
 
        file_id = self._text_parent(trans_id)
1001
 
        if file_id is None:
1002
 
            return ()
1003
 
        return (self._tree.get_file_text(file_id),)
1004
 
 
1005
 
    def _get_parents_lines(self, trans_id):
1006
 
        """Get lines for compression parents of this file."""
1007
 
        file_id = self._text_parent(trans_id)
1008
 
        if file_id is None:
1009
 
            return ()
1010
 
        return (self._tree.get_file_lines(file_id),)
1011
 
 
1012
 
    def serialize(self, serializer):
1013
 
        """Serialize this TreeTransform.
1014
 
 
1015
 
        :param serializer: A Serialiser like pack.ContainerSerializer.
1016
 
        """
1017
 
        new_name = dict((k, v.encode('utf-8')) for k, v in
1018
 
                        self._new_name.items())
1019
 
        new_executability = dict((k, int(v)) for k, v in
1020
 
                                 self._new_executability.items())
1021
 
        tree_path_ids = dict((k.encode('utf-8'), v)
1022
 
                             for k, v in self._tree_path_ids.items())
1023
 
        attribs = {
1024
 
            '_id_number': self._id_number,
1025
 
            '_new_name': new_name,
1026
 
            '_new_parent': self._new_parent,
1027
 
            '_new_executability': new_executability,
1028
 
            '_new_id': self._new_id,
1029
 
            '_tree_path_ids': tree_path_ids,
1030
 
            '_removed_id': list(self._removed_id),
1031
 
            '_removed_contents': list(self._removed_contents),
1032
 
            '_non_present_ids': self._non_present_ids,
1033
 
            }
1034
 
        yield serializer.bytes_record(bencode.bencode(attribs),
1035
 
                                      (('attribs',),))
1036
 
        for trans_id, kind in self._new_contents.items():
1037
 
            if kind == 'file':
1038
 
                lines = osutils.chunks_to_lines(
1039
 
                    self._read_file_chunks(trans_id))
1040
 
                parents = self._get_parents_lines(trans_id)
1041
 
                mpdiff = multiparent.MultiParent.from_lines(lines, parents)
1042
 
                content = ''.join(mpdiff.to_patch())
1043
 
            if kind == 'directory':
1044
 
                content = ''
1045
 
            if kind == 'symlink':
1046
 
                content = self._read_symlink_target(trans_id)
1047
 
            yield serializer.bytes_record(content, ((trans_id, kind),))
1048
 
 
1049
 
    def deserialize(self, records):
1050
 
        """Deserialize a stored TreeTransform.
1051
 
 
1052
 
        :param records: An iterable of (names, content) tuples, as per
1053
 
            pack.ContainerPushParser.
1054
 
        """
1055
 
        names, content = records.next()
1056
 
        attribs = bencode.bdecode(content)
1057
 
        self._id_number = attribs['_id_number']
1058
 
        self._new_name = dict((k, v.decode('utf-8'))
1059
 
                            for k, v in attribs['_new_name'].items())
1060
 
        self._new_parent = attribs['_new_parent']
1061
 
        self._new_executability = dict((k, bool(v)) for k, v in
1062
 
            attribs['_new_executability'].items())
1063
 
        self._new_id = attribs['_new_id']
1064
 
        self._r_new_id = dict((v, k) for k, v in self._new_id.items())
1065
 
        self._tree_path_ids = {}
1066
 
        self._tree_id_paths = {}
1067
 
        for bytepath, trans_id in attribs['_tree_path_ids'].items():
1068
 
            path = bytepath.decode('utf-8')
1069
 
            self._tree_path_ids[path] = trans_id
1070
 
            self._tree_id_paths[trans_id] = path
1071
 
        self._removed_id = set(attribs['_removed_id'])
1072
 
        self._removed_contents = set(attribs['_removed_contents'])
1073
 
        self._non_present_ids = attribs['_non_present_ids']
1074
 
        for ((trans_id, kind),), content in records:
1075
 
            if kind == 'file':
1076
 
                mpdiff = multiparent.MultiParent.from_patch(content)
1077
 
                lines = mpdiff.to_lines(self._get_parents_texts(trans_id))
1078
 
                self.create_file(lines, trans_id)
1079
 
            if kind == 'directory':
1080
 
                self.create_directory(trans_id)
1081
 
            if kind == 'symlink':
1082
 
                self.create_symlink(content.decode('utf-8'), trans_id)
1083
 
 
1084
 
 
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):
 
1110
 
 
1111
class TreeTransform(TreeTransformBase):
1301
1112
    """Represent a tree transformation.
1302
1113
 
1303
1114
    This object is designed to support incremental generation of the transform,
1362
1173
    FileMover does not delete files until it is sure that a rollback will not
1363
1174
    happen.
1364
1175
    """
1365
 
    def __init__(self, tree, pb=None):
 
1176
    def __init__(self, tree, pb=DummyProgress()):
1366
1177
        """Note: a tree_write lock is taken on the tree.
1367
1178
 
1368
1179
        Use TreeTransform.finalize() to release the lock (can be omitted if
1389
1200
            tree.unlock()
1390
1201
            raise
1391
1202
 
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,
 
1203
        TreeTransformBase.__init__(self, tree, limbodir, pb,
1397
1204
                                   tree.case_sensitive)
1398
1205
        self._deletiondir = deletiondir
1399
1206
 
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
1207
    def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
1530
1208
        """Apply all changes to the inventory and filesystem.
1531
1209
 
1541
1219
        :param _mover: Supply an alternate FileMover, for testing
1542
1220
        """
1543
1221
        if not no_conflicts:
1544
 
            self._check_malformed()
 
1222
            conflicts = self.find_conflicts()
 
1223
            if len(conflicts) != 0:
 
1224
                raise MalformedTransform(conflicts=conflicts)
1545
1225
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1546
1226
        try:
1547
1227
            if precomputed_delta is None:
1644
1324
        """
1645
1325
        tree_paths = list(self._tree_path_ids.iteritems())
1646
1326
        tree_paths.sort(reverse=True)
 
1327
        kind_changes = set()
1647
1328
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1648
1329
        try:
1649
1330
            for num, data in enumerate(tree_paths):
1651
1332
                child_pb.update('removing file', num, len(tree_paths))
1652
1333
                full_path = self._tree.abspath(path)
1653
1334
                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):
 
1335
                    mover.pre_delete(full_path, os.path.join(self._deletiondir,
 
1336
                                     trans_id))
 
1337
                elif trans_id in self._new_name or trans_id in \
 
1338
                    self._new_parent:
1658
1339
                    try:
1659
1340
                        mover.rename(full_path, self._limbo_name(trans_id))
1660
1341
                    except OSError, e:
1664
1345
                        self.rename_count += 1
1665
1346
        finally:
1666
1347
            child_pb.finished()
 
1348
        return kind_changes
1667
1349
 
1668
1350
    def _apply_insertions(self, mover):
1669
1351
        """Perform tree operations that insert directory/inventory names.
1674
1356
 
1675
1357
        If inventory_delta is None, no inventory delta is calculated, and
1676
1358
        no list of modified paths is returned.
 
1359
 
 
1360
        kind_changes is a set of trans ids where the entry has changed
 
1361
        kind, and so an inventory delta entry should be created for them.
1677
1362
        """
1678
1363
        new_paths = self.new_paths(filesystem_only=True)
1679
1364
        modified_paths = []
1706
1391
        return modified_paths
1707
1392
 
1708
1393
 
1709
 
class TransformPreview(DiskTreeTransform):
 
1394
class TransformPreview(TreeTransformBase):
1710
1395
    """A TreeTransform for generating preview trees.
1711
1396
 
1712
1397
    Unlike TreeTransform, this version works when the input tree is a
1714
1399
    unversioned files in the input tree.
1715
1400
    """
1716
1401
 
1717
 
    def __init__(self, tree, pb=None, case_sensitive=True):
 
1402
    def __init__(self, tree, pb=DummyProgress(), case_sensitive=True):
1718
1403
        tree.lock_read()
1719
 
        limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
1720
 
        DiskTreeTransform.__init__(self, tree, limbodir, pb, case_sensitive)
 
1404
        limbodir = tempfile.mkdtemp(prefix='bzr-limbo-')
 
1405
        TreeTransformBase.__init__(self, tree, limbodir, pb, case_sensitive)
1721
1406
 
1722
1407
    def canonical_path(self, path):
1723
1408
        return path
1747
1432
        file_id = self.tree_file_id(parent_id)
1748
1433
        if file_id is None:
1749
1434
            return
1750
 
        entry = self._tree.iter_entries_by_dir([file_id]).next()[1]
1751
 
        children = getattr(entry, 'children', {})
 
1435
        children = getattr(self._tree.inventory[file_id], 'children', {})
1752
1436
        for child in children:
1753
1437
            childpath = joinpath(path, child)
1754
1438
            yield self.trans_id_tree_path(childpath)
1762
1446
        self._final_paths = FinalPaths(transform)
1763
1447
        self.__by_parent = None
1764
1448
        self._parent_ids = []
1765
 
        self._all_children_cache = {}
1766
 
        self._path2trans_id_cache = {}
1767
 
        self._final_name_cache = {}
1768
 
        self._iter_changes_cache = dict((c[0], c) for c in
1769
 
                                        self._transform.iter_changes())
 
1449
 
 
1450
    def _changes(self, file_id):
 
1451
        for changes in self._transform.iter_changes():
 
1452
            if changes[0] == file_id:
 
1453
                return changes
1770
1454
 
1771
1455
    def _content_change(self, file_id):
1772
1456
        """Return True if the content of this file changed"""
1773
 
        changes = self._iter_changes_cache.get(file_id)
 
1457
        changes = self._changes(file_id)
1774
1458
        # changes[2] is true if the file content changed.  See
1775
1459
        # InterTree.iter_changes.
1776
1460
        return (changes is not None and changes[2])
1810
1494
            self.__by_parent = self._transform.by_parent()
1811
1495
        return self.__by_parent
1812
1496
 
1813
 
    def _comparison_data(self, entry, path):
1814
 
        kind, size, executable, link_or_sha1 = self.path_content_summary(path)
1815
 
        if kind == 'missing':
1816
 
            kind = None
1817
 
            executable = False
1818
 
        else:
1819
 
            file_id = self._transform.final_file_id(self._path2trans_id(path))
1820
 
            executable = self.is_executable(file_id, path)
1821
 
        return kind, executable, None
1822
 
 
1823
 
    def is_locked(self):
1824
 
        return False
1825
 
 
1826
1497
    def lock_read(self):
1827
1498
        # Perhaps in theory, this should lock the TreeTransform?
1828
 
        return self
 
1499
        pass
1829
1500
 
1830
1501
    def unlock(self):
1831
1502
        pass
1848
1519
    def __iter__(self):
1849
1520
        return iter(self.all_file_ids())
1850
1521
 
1851
 
    def _has_id(self, file_id, fallback_check):
1852
 
        if file_id in self._transform._r_new_id:
1853
 
            return True
1854
 
        elif file_id in set([self._transform.tree_file_id(trans_id) for
1855
 
            trans_id in self._transform._removed_id]):
1856
 
            return False
1857
 
        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)
 
1522
    def paths2ids(self, specific_files, trees=None, require_versioned=False):
 
1523
        """See Tree.paths2ids"""
 
1524
        to_find = set(specific_files)
 
1525
        result = set()
 
1526
        for (file_id, paths, changed, versioned, parent, name, kind,
 
1527
             executable) in self._transform.iter_changes():
 
1528
            if paths[1] in to_find:
 
1529
                result.append(file_id)
 
1530
                to_find.remove(paths[1])
 
1531
        result.update(self._transform._tree.paths2ids(to_find,
 
1532
                      trees=[], require_versioned=require_versioned))
 
1533
        return result
1865
1534
 
1866
1535
    def _path2trans_id(self, path):
1867
 
        # We must not use None here, because that is a valid value to store.
1868
 
        trans_id = self._path2trans_id_cache.get(path, object)
1869
 
        if trans_id is not object:
1870
 
            return trans_id
1871
1536
        segments = splitpath(path)
1872
1537
        cur_parent = self._transform.root
1873
1538
        for cur_segment in segments:
1874
1539
            for child in self._all_children(cur_parent):
1875
 
                final_name = self._final_name_cache.get(child)
1876
 
                if final_name is None:
1877
 
                    final_name = self._transform.final_name(child)
1878
 
                    self._final_name_cache[child] = final_name
1879
 
                if final_name == cur_segment:
 
1540
                if self._transform.final_name(child) == cur_segment:
1880
1541
                    cur_parent = child
1881
1542
                    break
1882
1543
            else:
1883
 
                self._path2trans_id_cache[path] = None
1884
1544
                return None
1885
 
        self._path2trans_id_cache[path] = cur_parent
1886
1545
        return cur_parent
1887
1546
 
1888
1547
    def path2id(self, path):
1896
1555
            raise errors.NoSuchId(self, file_id)
1897
1556
 
1898
1557
    def _all_children(self, trans_id):
1899
 
        children = self._all_children_cache.get(trans_id)
1900
 
        if children is not None:
1901
 
            return children
1902
1558
        children = set(self._transform.iter_tree_children(trans_id))
1903
1559
        # children in the _new_parent set are provided by _by_parent.
1904
1560
        children.difference_update(self._transform._new_parent.keys())
1905
1561
        children.update(self._by_parent.get(trans_id, []))
1906
 
        self._all_children_cache[trans_id] = children
1907
1562
        return children
1908
1563
 
1909
 
    def iter_children(self, file_id):
1910
 
        trans_id = self._transform.trans_id_file_id(file_id)
1911
 
        for child_trans_id in self._all_children(trans_id):
1912
 
            yield self._transform.final_file_id(child_trans_id)
1913
 
 
1914
 
    def extras(self):
1915
 
        possible_extras = set(self._transform.trans_id_tree_path(p) for p
1916
 
                              in self._transform._tree.extras())
1917
 
        possible_extras.update(self._transform._new_contents)
1918
 
        possible_extras.update(self._transform._removed_id)
1919
 
        for trans_id in possible_extras:
1920
 
            if self._transform.final_file_id(trans_id) is None:
1921
 
                yield self._final_paths._determine_path(trans_id)
1922
 
 
1923
 
    def _make_inv_entries(self, ordered_entries, specific_file_ids=None,
1924
 
        yield_parents=False):
 
1564
    def _make_inv_entries(self, ordered_entries, specific_file_ids):
1925
1565
        for trans_id, parent_file_id in ordered_entries:
1926
1566
            file_id = self._transform.final_file_id(trans_id)
1927
1567
            if file_id is None:
1939
1579
                parent_file_id, file_id)
1940
1580
            yield new_entry, trans_id
1941
1581
 
1942
 
    def _list_files_by_dir(self):
 
1582
    def iter_entries_by_dir(self, specific_file_ids=None):
 
1583
        # This may not be a maximally efficient implementation, but it is
 
1584
        # reasonably straightforward.  An implementation that grafts the
 
1585
        # TreeTransform changes onto the tree's iter_entries_by_dir results
 
1586
        # might be more efficient, but requires tricky inferences about stack
 
1587
        # position.
1943
1588
        todo = [ROOT_PARENT]
1944
1589
        ordered_ids = []
1945
1590
        while len(todo) > 0:
1951
1596
            todo.extend(reversed(children))
1952
1597
            for trans_id in children:
1953
1598
                ordered_ids.append((trans_id, parent_file_id))
1954
 
        return ordered_ids
1955
 
 
1956
 
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
1957
 
        # This may not be a maximally efficient implementation, but it is
1958
 
        # reasonably straightforward.  An implementation that grafts the
1959
 
        # TreeTransform changes onto the tree's iter_entries_by_dir results
1960
 
        # might be more efficient, but requires tricky inferences about stack
1961
 
        # position.
1962
 
        ordered_ids = self._list_files_by_dir()
1963
1599
        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."""
1979
 
        # XXX This should behave like WorkingTree.list_files, but is really
1980
 
        # 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
 
1600
                                                      specific_file_ids):
 
1601
            yield unicode(self._final_paths.get_path(trans_id)), entry
2002
1602
 
2003
1603
    def kind(self, file_id):
2004
1604
        trans_id = self._transform.trans_id_file_id(file_id)
2014
1614
    def get_file_mtime(self, file_id, path=None):
2015
1615
        """See Tree.get_file_mtime"""
2016
1616
        if not self._content_change(file_id):
2017
 
            return self._transform._tree.get_file_mtime(file_id)
 
1617
            return self._transform._tree.get_file_mtime(file_id, path)
2018
1618
        return self._stat_limbo_file(file_id).st_mtime
2019
1619
 
2020
 
    def _file_size(self, entry, stat_value):
2021
 
        return self.get_file_size(entry.file_id)
2022
 
 
2023
1620
    def get_file_size(self, file_id):
2024
1621
        """See Tree.get_file_size"""
2025
1622
        if self.kind(file_id) == 'file':
2028
1625
            return None
2029
1626
 
2030
1627
    def get_file_sha1(self, file_id, path=None, stat_value=None):
2031
 
        trans_id = self._transform.trans_id_file_id(file_id)
2032
 
        kind = self._transform._new_contents.get(trans_id)
2033
 
        if kind is None:
2034
 
            return self._transform._tree.get_file_sha1(file_id)
2035
 
        if kind == 'file':
2036
 
            fileobj = self.get_file(file_id)
2037
 
            try:
2038
 
                return sha_file(fileobj)
2039
 
            finally:
2040
 
                fileobj.close()
 
1628
        return self._transform._tree.get_file_sha1(file_id)
2041
1629
 
2042
1630
    def is_executable(self, file_id, path=None):
2043
 
        if file_id is None:
2044
 
            return False
2045
1631
        trans_id = self._transform.trans_id_file_id(file_id)
2046
1632
        try:
2047
1633
            return self._transform._new_executability[trans_id]
2048
1634
        except KeyError:
2049
 
            try:
2050
 
                return self._transform._tree.is_executable(file_id, path)
2051
 
            except OSError, e:
2052
 
                if e.errno == errno.ENOENT:
2053
 
                    return False
2054
 
                raise
2055
 
            except errors.NoSuchId:
2056
 
                return False
 
1635
            return self._transform._tree.is_executable(file_id, path)
2057
1636
 
2058
1637
    def path_content_summary(self, path):
2059
1638
        trans_id = self._path2trans_id(path)
2074
1653
                statval = os.lstat(limbo_name)
2075
1654
                size = statval.st_size
2076
1655
                if not supports_executable():
2077
 
                    executable = False
 
1656
                    executable = None
2078
1657
                else:
2079
1658
                    executable = statval.st_mode & S_IEXEC
2080
1659
            else:
2081
1660
                size = None
2082
1661
                executable = None
2083
1662
            if kind == 'symlink':
2084
 
                link_or_sha1 = os.readlink(limbo_name).decode(osutils._fs_enc)
2085
 
        executable = tt._new_executability.get(trans_id, executable)
 
1663
                link_or_sha1 = os.readlink(limbo_name)
 
1664
        if supports_executable():
 
1665
            executable = tt._new_executability.get(trans_id, executable)
2086
1666
        return kind, size, executable, link_or_sha1
2087
1667
 
2088
1668
    def iter_changes(self, from_tree, include_unchanged=False,
2090
1670
                      require_versioned=True, want_unversioned=False):
2091
1671
        """See InterTree.iter_changes.
2092
1672
 
2093
 
        This has a fast path that is only used when the from_tree matches
2094
 
        the transform tree, and no fancy options are supplied.
 
1673
        This implementation does not support include_unchanged, specific_files,
 
1674
        or want_unversioned.  extra_trees, require_versioned, and pb are
 
1675
        ignored.
2095
1676
        """
2096
 
        if (from_tree is not self._transform._tree or include_unchanged or
2097
 
            specific_files or want_unversioned):
2098
 
            return tree.InterTree(from_tree, self).iter_changes(
2099
 
                include_unchanged=include_unchanged,
2100
 
                specific_files=specific_files,
2101
 
                pb=pb,
2102
 
                extra_trees=extra_trees,
2103
 
                require_versioned=require_versioned,
2104
 
                want_unversioned=want_unversioned)
 
1677
        if from_tree is not self._transform._tree:
 
1678
            raise ValueError('from_tree must be transform source tree.')
 
1679
        if include_unchanged:
 
1680
            raise ValueError('include_unchanged is not supported')
 
1681
        if specific_files is not None:
 
1682
            raise ValueError('specific_files is not supported')
2105
1683
        if want_unversioned:
2106
1684
            raise ValueError('want_unversioned is not supported')
2107
1685
        return self._transform.iter_changes()
2114
1692
        name = self._transform._limbo_name(trans_id)
2115
1693
        return open(name, 'rb')
2116
1694
 
2117
 
    def get_file_with_stat(self, file_id, path=None):
2118
 
        return self.get_file(file_id, path), None
 
1695
    def get_file_text(self, file_id):
 
1696
        text_file = self.get_file(file_id)
 
1697
        try:
 
1698
            return text_file.read()
 
1699
        finally:
 
1700
            text_file.close()
2119
1701
 
2120
1702
    def annotate_iter(self, file_id,
2121
1703
                      default_revision=_mod_revision.CURRENT_REVISION):
2122
 
        changes = self._iter_changes_cache.get(file_id)
 
1704
        changes = self._changes(file_id)
2123
1705
        if changes is None:
2124
1706
            get_old = True
2125
1707
        else:
2137
1719
            return old_annotation
2138
1720
        if not changed_content:
2139
1721
            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
1722
        return annotate.reannotate([old_annotation],
2148
1723
                                   self.get_file(file_id).readlines(),
2149
1724
                                   default_revision)
2154
1729
            return self._transform._tree.get_symlink_target(file_id)
2155
1730
        trans_id = self._transform.trans_id_file_id(file_id)
2156
1731
        name = self._transform._limbo_name(trans_id)
2157
 
        return osutils.readlink(name)
2158
 
 
2159
 
    def walkdirs(self, prefix=''):
2160
 
        pending = [self._transform.root]
2161
 
        while len(pending) > 0:
2162
 
            parent_id = pending.pop()
2163
 
            children = []
2164
 
            subdirs = []
2165
 
            prefix = prefix.rstrip('/')
2166
 
            parent_path = self._final_paths.get_path(parent_id)
2167
 
            parent_file_id = self._transform.final_file_id(parent_id)
2168
 
            for child_id in self._all_children(parent_id):
2169
 
                path_from_root = self._final_paths.get_path(child_id)
2170
 
                basename = self._transform.final_name(child_id)
2171
 
                file_id = self._transform.final_file_id(child_id)
2172
 
                try:
2173
 
                    kind = self._transform.final_kind(child_id)
2174
 
                    versioned_kind = kind
2175
 
                except NoSuchFile:
2176
 
                    kind = 'unknown'
2177
 
                    versioned_kind = self._transform._tree.stored_kind(file_id)
2178
 
                if versioned_kind == 'directory':
2179
 
                    subdirs.append(child_id)
2180
 
                children.append((path_from_root, basename, kind, None,
2181
 
                                 file_id, versioned_kind))
2182
 
            children.sort()
2183
 
            if parent_path.startswith(prefix):
2184
 
                yield (parent_path, parent_file_id), children
2185
 
            pending.extend(sorted(subdirs, key=self._final_paths.get_path,
2186
 
                                  reverse=True))
 
1732
        return os.readlink(name)
 
1733
 
 
1734
    def list_files(self, include_root=False):
 
1735
        return self._transform._tree.list_files(include_root)
 
1736
 
 
1737
    def walkdirs(self, prefix=""):
 
1738
        return self._transform._tree.walkdirs(prefix)
2187
1739
 
2188
1740
    def get_parent_ids(self):
2189
1741
        return self._parent_ids
2215
1767
        self.transform = transform
2216
1768
 
2217
1769
    def _determine_path(self, trans_id):
2218
 
        if (trans_id == self.transform.root or trans_id == ROOT_PARENT):
 
1770
        if trans_id == self.transform.root:
2219
1771
            return ""
2220
1772
        name = self.transform.final_name(trans_id)
2221
1773
        parent_id = self.transform.final_parent(trans_id)
2245
1797
def build_tree(tree, wt, accelerator_tree=None, hardlink=False,
2246
1798
               delta_from_tree=False):
2247
1799
    """Create working tree for a branch, using a TreeTransform.
2248
 
 
 
1800
    
2249
1801
    This function should be used on empty trees, having a tree root at most.
2250
1802
    (see merge and revert functionality for working with existing trees)
2251
1803
 
2252
1804
    Existing files are handled like so:
2253
 
 
 
1805
    
2254
1806
    - Existing bzrdirs take precedence over creating new items.  They are
2255
1807
      created as '%s.diverted' % name.
2256
1808
    - Otherwise, if the content on disk matches the content we are building,
2358
1910
                    executable = tree.is_executable(file_id, tree_path)
2359
1911
                    if executable:
2360
1912
                        tt.set_executability(executable, trans_id)
2361
 
                    trans_data = (trans_id, tree_path)
2362
 
                    deferred_contents.append((file_id, trans_data))
 
1913
                    deferred_contents.append((file_id, trans_id))
2363
1914
                else:
2364
1915
                    file_trans_id[file_id] = new_by_entry(tt, entry, parent_id,
2365
1916
                                                          tree)
2396
1947
def _create_files(tt, tree, desired_files, pb, offset, accelerator_tree,
2397
1948
                  hardlink):
2398
1949
    total = len(desired_files) + offset
2399
 
    wt = tt._tree
2400
1950
    if accelerator_tree is None:
2401
1951
        new_desired_files = desired_files
2402
1952
    else:
2403
1953
        iter = accelerator_tree.iter_changes(tree, include_unchanged=True)
2404
 
        unchanged = [(f, p[1]) for (f, p, c, v, d, n, k, e)
2405
 
                     in iter if not (c or e[0] != e[1])]
2406
 
        if accelerator_tree.supports_content_filtering():
2407
 
            unchanged = [(f, p) for (f, p) in unchanged
2408
 
                         if not accelerator_tree.iter_search_rules([p]).next()]
2409
 
        unchanged = dict(unchanged)
 
1954
        unchanged = dict((f, p[1]) for (f, p, c, v, d, n, k, e)
 
1955
                         in iter if not (c or e[0] != e[1]))
2410
1956
        new_desired_files = []
2411
1957
        count = 0
2412
 
        for file_id, (trans_id, tree_path) in desired_files:
 
1958
        for file_id, trans_id in desired_files:
2413
1959
            accelerator_path = unchanged.get(file_id)
2414
1960
            if accelerator_path is None:
2415
 
                new_desired_files.append((file_id, (trans_id, tree_path)))
 
1961
                new_desired_files.append((file_id, trans_id))
2416
1962
                continue
2417
1963
            pb.update('Adding file contents', count + offset, total)
2418
1964
            if hardlink:
2420
1966
                                   trans_id)
2421
1967
            else:
2422
1968
                contents = accelerator_tree.get_file(file_id, accelerator_path)
2423
 
                if wt.supports_content_filtering():
2424
 
                    filters = wt._content_filter_stack(tree_path)
2425
 
                    contents = filtered_output_bytes(contents, filters,
2426
 
                        ContentFilterContext(tree_path, tree))
2427
1969
                try:
2428
1970
                    tt.create_file(contents, trans_id)
2429
1971
                finally:
2430
 
                    try:
2431
 
                        contents.close()
2432
 
                    except AttributeError:
2433
 
                        # after filtering, contents may no longer be file-like
2434
 
                        pass
 
1972
                    contents.close()
2435
1973
            count += 1
2436
1974
        offset += count
2437
 
    for count, ((trans_id, tree_path), contents) in enumerate(
2438
 
            tree.iter_files_bytes(new_desired_files)):
2439
 
        if wt.supports_content_filtering():
2440
 
            filters = wt._content_filter_stack(tree_path)
2441
 
            contents = filtered_output_bytes(contents, filters,
2442
 
                ContentFilterContext(tree_path, tree))
 
1975
    for count, (trans_id, contents) in enumerate(tree.iter_files_bytes(
 
1976
                                                 new_desired_files)):
2443
1977
        tt.create_file(contents, trans_id)
2444
1978
        pb.update('Adding file contents', count + offset, total)
2445
1979
 
2505
2039
    if kind == 'file':
2506
2040
        contents = tree.get_file(entry.file_id).readlines()
2507
2041
        executable = tree.is_executable(entry.file_id)
2508
 
        return tt.new_file(name, parent_id, contents, entry.file_id,
 
2042
        return tt.new_file(name, parent_id, contents, entry.file_id, 
2509
2043
                           executable)
2510
2044
    elif kind in ('directory', 'tree-reference'):
2511
2045
        trans_id = tt.new_directory(name, parent_id, entry.file_id)
2512
2046
        if kind == 'tree-reference':
2513
2047
            tt.set_tree_reference(entry.reference_revision, trans_id)
2514
 
        return trans_id
 
2048
        return trans_id 
2515
2049
    elif kind == 'symlink':
2516
2050
        target = tree.get_symlink_target(entry.file_id)
2517
2051
        return tt.new_symlink(name, parent_id, target, entry.file_id)
2519
2053
        raise errors.BadFileKindError(name, kind)
2520
2054
 
2521
2055
 
2522
 
@deprecated_function(deprecated_in((1, 9, 0)))
2523
2056
def create_by_entry(tt, entry, tree, trans_id, lines=None, mode_id=None):
2524
 
    """Create new file contents according to an inventory entry.
2525
 
 
2526
 
    DEPRECATED.  Use create_from_tree instead.
2527
 
    """
 
2057
    """Create new file contents according to an inventory entry."""
2528
2058
    if entry.kind == "file":
2529
2059
        if lines is None:
2530
2060
            lines = tree.get_file(entry.file_id).readlines()
2535
2065
        tt.create_directory(trans_id)
2536
2066
 
2537
2067
 
2538
 
def create_from_tree(tt, trans_id, tree, file_id, bytes=None,
2539
 
    filter_tree_path=None):
2540
 
    """Create new file contents according to tree contents.
2541
 
    
2542
 
    :param filter_tree_path: the tree path to use to lookup
2543
 
      content filters to apply to the bytes output in the working tree.
2544
 
      This only applies if the working tree supports content filtering.
2545
 
    """
2546
 
    kind = tree.kind(file_id)
2547
 
    if kind == 'directory':
2548
 
        tt.create_directory(trans_id)
2549
 
    elif kind == "file":
2550
 
        if bytes is None:
2551
 
            tree_file = tree.get_file(file_id)
2552
 
            try:
2553
 
                bytes = tree_file.readlines()
2554
 
            finally:
2555
 
                tree_file.close()
2556
 
        wt = tt._tree
2557
 
        if wt.supports_content_filtering() and filter_tree_path is not None:
2558
 
            filters = wt._content_filter_stack(filter_tree_path)
2559
 
            bytes = filtered_output_bytes(bytes, filters,
2560
 
                ContentFilterContext(filter_tree_path, tree))
2561
 
        tt.create_file(bytes, trans_id)
2562
 
    elif kind == "symlink":
2563
 
        tt.create_symlink(tree.get_symlink_target(file_id), trans_id)
2564
 
    else:
2565
 
        raise AssertionError('Unknown kind %r' % kind)
2566
 
 
2567
 
 
2568
2068
def create_entry_executability(tt, entry, trans_id):
2569
2069
    """Set the executability of a trans_id according to an inventory entry"""
2570
2070
    if entry.kind == "file":
2607
2107
        if entry.kind != working_kind:
2608
2108
            contents_mod, meta_mod = True, False
2609
2109
        else:
2610
 
            cur_entry._read_tree_state(working_tree.id2path(file_id),
 
2110
            cur_entry._read_tree_state(working_tree.id2path(file_id), 
2611
2111
                                       working_tree)
2612
2112
            contents_mod, meta_mod = entry.detect_changes(cur_entry)
2613
2113
            cur_entry._forget_tree_state()
2615
2115
 
2616
2116
 
2617
2117
def revert(working_tree, target_tree, filenames, backups=False,
2618
 
           pb=None, change_reporter=None):
 
2118
           pb=DummyProgress(), change_reporter=None):
2619
2119
    """Revert a working tree's contents to those of a target tree."""
2620
2120
    target_tree.lock_read()
2621
 
    pb = ui.ui_factory.nested_progress_bar()
2622
2121
    tt = TreeTransform(working_tree, pb)
2623
2122
    try:
2624
2123
        pp = ProgressPhase("Revert phase", 3, pb)
2625
 
        conflicts, merge_modified = _prepare_revert_transform(
2626
 
            working_tree, target_tree, tt, filenames, backups, pp)
 
2124
        pp.next_phase()
 
2125
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
2126
        try:
 
2127
            merge_modified = _alter_files(working_tree, target_tree, tt,
 
2128
                                          child_pb, filenames, backups)
 
2129
        finally:
 
2130
            child_pb.finished()
 
2131
        pp.next_phase()
 
2132
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
2133
        try:
 
2134
            raw_conflicts = resolve_conflicts(tt, child_pb,
 
2135
                lambda t, c: conflict_pass(t, c, target_tree))
 
2136
        finally:
 
2137
            child_pb.finished()
 
2138
        conflicts = cook_conflicts(raw_conflicts, tt)
2627
2139
        if change_reporter:
2628
2140
            change_reporter = delta._ChangeReporter(
2629
2141
                unversioned_filter=working_tree.is_ignored)
2640
2152
    return conflicts
2641
2153
 
2642
2154
 
2643
 
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
2644
 
                              backups, pp, basis_tree=None,
2645
 
                              merge_modified=None):
2646
 
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2647
 
    try:
2648
 
        if merge_modified is None:
2649
 
            merge_modified = working_tree.merge_modified()
2650
 
        merge_modified = _alter_files(working_tree, target_tree, tt,
2651
 
                                      child_pb, filenames, backups,
2652
 
                                      merge_modified, basis_tree)
2653
 
    finally:
2654
 
        child_pb.finished()
2655
 
    child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2656
 
    try:
2657
 
        raw_conflicts = resolve_conflicts(tt, child_pb,
2658
 
            lambda t, c: conflict_pass(t, c, target_tree))
2659
 
    finally:
2660
 
        child_pb.finished()
2661
 
    conflicts = cook_conflicts(raw_conflicts, tt)
2662
 
    return conflicts, merge_modified
2663
 
 
2664
 
 
2665
2155
def _alter_files(working_tree, target_tree, tt, pb, specific_files,
2666
 
                 backups, merge_modified, basis_tree=None):
2667
 
    if basis_tree is not None:
2668
 
        basis_tree.lock_read()
 
2156
                 backups):
 
2157
    merge_modified = working_tree.merge_modified()
2669
2158
    change_list = target_tree.iter_changes(working_tree,
2670
2159
        specific_files=specific_files, pb=pb)
2671
 
    if target_tree.get_root_id() is None:
 
2160
    if target_tree.inventory.root is None:
2672
2161
        skip_root = True
2673
2162
    else:
2674
2163
        skip_root = False
 
2164
    basis_tree = None
2675
2165
    try:
2676
2166
        deferred_files = []
2677
2167
        for id_num, (file_id, path, changed_content, versioned, parent, name,
2713
2203
                        # contents
2714
2204
                        mode_id = trans_id
2715
2205
                        trans_id = new_trans_id
2716
 
                if kind[1] in ('directory', 'tree-reference'):
 
2206
                if kind[1] == 'directory':
2717
2207
                    tt.create_directory(trans_id)
2718
 
                    if kind[1] == 'tree-reference':
2719
 
                        revision = target_tree.get_reference_revision(file_id,
2720
 
                                                                      path[1])
2721
 
                        tt.set_tree_reference(revision, trans_id)
2722
2208
                elif kind[1] == 'symlink':
2723
2209
                    tt.create_symlink(target_tree.get_symlink_target(file_id),
2724
2210
                                      trans_id)
2744
2230
                tt.version_file(file_id, trans_id)
2745
2231
            if versioned == (True, False):
2746
2232
                tt.unversion_file(trans_id)
2747
 
            if (name[1] is not None and
 
2233
            if (name[1] is not None and 
2748
2234
                (name[0] != name[1] or parent[0] != parent[1])):
2749
 
                if name[1] == '' and parent[1] is None:
2750
 
                    parent_trans = ROOT_PARENT
2751
 
                else:
2752
 
                    parent_trans = tt.trans_id_file_id(parent[1])
2753
 
                if parent[0] is None and versioned[0]:
2754
 
                    tt.adjust_root_path(name[1], parent_trans)
2755
 
                else:
2756
 
                    tt.adjust_path(name[1], parent_trans, trans_id)
 
2235
                tt.adjust_path(
 
2236
                    name[1], tt.trans_id_file_id(parent[1]), trans_id)
2757
2237
            if executable[0] != executable[1] and kind[1] == "file":
2758
2238
                tt.set_executability(executable[1], trans_id)
2759
 
        if working_tree.supports_content_filtering():
2760
 
            for index, ((trans_id, mode_id), bytes) in enumerate(
2761
 
                target_tree.iter_files_bytes(deferred_files)):
2762
 
                file_id = deferred_files[index][0]
2763
 
                # We're reverting a tree to the target tree so using the
2764
 
                # target tree to find the file path seems the best choice
2765
 
                # here IMO - Ian C 27/Oct/2009
2766
 
                filter_tree_path = target_tree.id2path(file_id)
2767
 
                filters = working_tree._content_filter_stack(filter_tree_path)
2768
 
                bytes = filtered_output_bytes(bytes, filters,
2769
 
                    ContentFilterContext(filter_tree_path, working_tree))
2770
 
                tt.create_file(bytes, trans_id, mode_id)
2771
 
        else:
2772
 
            for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
2773
 
                deferred_files):
2774
 
                tt.create_file(bytes, trans_id, mode_id)
2775
 
        tt.fixup_new_roots()
 
2239
        for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
 
2240
            deferred_files):
 
2241
            tt.create_file(bytes, trans_id, mode_id)
2776
2242
    finally:
2777
2243
        if basis_tree is not None:
2778
2244
            basis_tree.unlock()
2779
2245
    return merge_modified
2780
2246
 
2781
2247
 
2782
 
def resolve_conflicts(tt, pb=None, pass_func=None):
 
2248
def resolve_conflicts(tt, pb=DummyProgress(), pass_func=None):
2783
2249
    """Make many conflict-resolution attempts, but die if they fail"""
2784
2250
    if pass_func is None:
2785
2251
        pass_func = conflict_pass
2786
2252
    new_conflicts = set()
2787
 
    pb = ui.ui_factory.nested_progress_bar()
2788
2253
    try:
2789
2254
        for n in range(10):
2790
2255
            pb.update('Resolution pass', n+1, 10)
2794
2259
            new_conflicts.update(pass_func(tt, conflicts))
2795
2260
        raise MalformedTransform(conflicts=conflicts)
2796
2261
    finally:
2797
 
        pb.finished()
 
2262
        pb.clear()
2798
2263
 
2799
2264
 
2800
2265
def conflict_pass(tt, conflicts, path_tree=None):
2819
2284
                existing_file, new_file = conflict[1], conflict[2]
2820
2285
            new_name = tt.final_name(existing_file)+'.moved'
2821
2286
            tt.adjust_path(new_name, final_parent, existing_file)
2822
 
            new_conflicts.add((c_type, 'Moved existing file to',
 
2287
            new_conflicts.add((c_type, 'Moved existing file to', 
2823
2288
                               existing_file, new_file))
2824
2289
        elif c_type == 'parent loop':
2825
2290
            # break the loop by undoing one of the ops that caused the loop
2829
2294
            new_conflicts.add((c_type, 'Cancelled move', cur,
2830
2295
                               tt.final_parent(cur),))
2831
2296
            tt.adjust_path(tt.final_name(cur), tt.get_tree_parent(cur), cur)
2832
 
 
 
2297
            
2833
2298
        elif c_type == 'missing parent':
2834
2299
            trans_id = conflict[1]
2835
2300
            try:
2836
2301
                tt.cancel_deletion(trans_id)
2837
 
                new_conflicts.add(('deleting parent', 'Not deleting',
 
2302
                new_conflicts.add(('deleting parent', 'Not deleting', 
2838
2303
                                   trans_id))
2839
2304
            except KeyError:
2840
2305
                create = True
2849
2314
                        # special-case the other tree root (move its
2850
2315
                        # children to current root)
2851
2316
                        if entry.parent_id is None:
2852
 
                            create = False
 
2317
                            create=False
2853
2318
                            moved = _reparent_transform_children(
2854
2319
                                tt, trans_id, tt.root)
2855
2320
                            for child in moved:
2882
2347
            if parent_file_id is not None:
2883
2348
                tt.unversion_file(parent_id)
2884
2349
            new_conflicts.add((c_type, 'Created directory', new_parent_id))
2885
 
        elif c_type == 'versioning no contents':
2886
 
            tt.cancel_versioning(conflict[1])
2887
2350
    return new_conflicts
2888
2351
 
2889
2352
 
2905
2368
        if len(conflict) == 3:
2906
2369
            yield Conflict.factory(c_type, action=action, path=modified_path,
2907
2370
                                     file_id=modified_id)
2908
 
 
 
2371
             
2909
2372
        else:
2910
2373
            conflicting_path = fp.get_path(conflict[3])
2911
2374
            conflicting_id = tt.final_file_id(conflict[3])
2912
2375
            yield Conflict.factory(c_type, action=action, path=modified_path,
2913
 
                                   file_id=modified_id,
 
2376
                                   file_id=modified_id, 
2914
2377
                                   conflict_path=conflicting_path,
2915
2378
                                   conflict_file_id=conflicting_id)
2916
2379
 
2923
2386
        self.pending_deletions = []
2924
2387
 
2925
2388
    def rename(self, from_, to):
2926
 
        """Rename a file from one path to another."""
 
2389
        """Rename a file from one path to another.  Functions like os.rename"""
2927
2390
        try:
2928
 
            osutils.rename(from_, to)
 
2391
            os.rename(from_, to)
2929
2392
        except OSError, e:
2930
2393
            if e.errno in (errno.EEXIST, errno.ENOTEMPTY):
2931
2394
                raise errors.FileExists(to, str(e))
2945
2408
    def rollback(self):
2946
2409
        """Reverse all renames that have been performed"""
2947
2410
        for from_, to in reversed(self.past_renames):
2948
 
            osutils.rename(to, from_)
 
2411
            os.rename(to, from_)
2949
2412
        # after rollback, don't reuse _FileMover
2950
2413
        past_renames = None
2951
2414
        pending_deletions = None