~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transform.py

  • Committer: Robert Collins
  • Date: 2007-10-23 22:14:32 UTC
  • mto: (2592.6.3 repository)
  • mto: This revision was merged to the branch mainline in revision 2967.
  • Revision ID: robertc@robertcollins.net-20071023221432-j8zndh1oiegql3cu
* Commit updates the state of the working tree via a delta rather than
  supplying entirely new basis trees. For commit of a single specified file
  this reduces the wall clock time for commit by roughly a 30%.
  (Robert Collins, Martin Pool)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006, 2007 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
 
from stat import S_ISREG, S_IEXEC
20
 
import time
 
19
from stat import S_ISREG
21
20
 
22
 
from bzrlib import (
23
 
    errors,
24
 
    lazy_import,
25
 
    registry,
26
 
    trace,
27
 
    tree,
28
 
    )
29
 
lazy_import.lazy_import(globals(), """
30
 
from bzrlib import (
31
 
    annotate,
32
 
    bencode,
 
21
from bzrlib.lazy_import import lazy_import
 
22
lazy_import(globals(), """
 
23
from bzrlib import (
33
24
    bzrdir,
34
 
    commit,
35
25
    delta,
36
26
    errors,
37
 
    inventory,
38
 
    multiparent,
39
 
    osutils,
40
 
    revision as _mod_revision,
41
 
    ui,
42
 
    urlutils,
 
27
    inventory
43
28
    )
44
29
""")
45
30
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
46
 
                           ReusingTransform, CantMoveRoot,
47
 
                           ExistingLimbo, ImmortalLimbo, NoFinalPath,
48
 
                           UnableCreateSymlink)
49
 
from bzrlib.filters import filtered_output_bytes, ContentFilterContext
50
 
from bzrlib.osutils import (
51
 
    delete_any,
52
 
    file_kind,
53
 
    has_symlinks,
54
 
    pathjoin,
55
 
    sha_file,
56
 
    splitpath,
57
 
    supports_executable,
58
 
    )
59
 
from bzrlib.progress import ProgressPhase
 
31
                           ReusingTransform, NotVersionedError, CantMoveRoot,
 
32
                           ExistingLimbo, ImmortalLimbo, NoFinalPath)
 
33
from bzrlib.inventory import InventoryEntry
 
34
from bzrlib.osutils import (file_kind, supports_executable, pathjoin, lexists,
 
35
                            delete_any)
 
36
from bzrlib.progress import DummyProgress, ProgressPhase
60
37
from bzrlib.symbol_versioning import (
61
 
    deprecated_function,
62
 
    deprecated_in,
63
 
    deprecated_method,
64
 
    )
 
38
        deprecated_function,
 
39
        zero_fifteen,
 
40
        zero_ninety,
 
41
        )
 
42
from bzrlib.trace import mutter, warning
 
43
from bzrlib import tree
 
44
import bzrlib.ui
 
45
import bzrlib.urlutils as urlutils
65
46
 
66
47
 
67
48
ROOT_PARENT = "root-parent"
68
49
 
 
50
 
69
51
def unique_add(map, key, value):
70
52
    if key in map:
71
53
        raise DuplicateKey(key=key)
72
54
    map[key] = value
73
55
 
74
56
 
75
 
 
76
57
class _TransformResults(object):
77
58
    def __init__(self, modified_paths, rename_count):
78
59
        object.__init__(self)
80
61
        self.rename_count = rename_count
81
62
 
82
63
 
83
 
class TreeTransformBase(object):
84
 
    """The base class for TreeTransform and its kin."""
85
 
 
86
 
    def __init__(self, tree, pb=None,
87
 
                 case_sensitive=True):
88
 
        """Constructor.
89
 
 
90
 
        :param tree: The tree that will be transformed, but not necessarily
91
 
            the output tree.
92
 
        :param pb: ignored
93
 
        :param case_sensitive: If True, the target of the transform is
94
 
            case sensitive, not just case preserving.
 
64
class TreeTransform(object):
 
65
    """Represent a tree transformation.
 
66
    
 
67
    This object is designed to support incremental generation of the transform,
 
68
    in any order.
 
69
 
 
70
    However, it gives optimum performance when parent directories are created
 
71
    before their contents.  The transform is then able to put child files
 
72
    directly in their parent directory, avoiding later renames.
 
73
    
 
74
    It is easy to produce malformed transforms, but they are generally
 
75
    harmless.  Attempting to apply a malformed transform will cause an
 
76
    exception to be raised before any modifications are made to the tree.  
 
77
 
 
78
    Many kinds of malformed transforms can be corrected with the 
 
79
    resolve_conflicts function.  The remaining ones indicate programming error,
 
80
    such as trying to create a file with no path.
 
81
 
 
82
    Two sets of file creation methods are supplied.  Convenience methods are:
 
83
     * new_file
 
84
     * new_directory
 
85
     * new_symlink
 
86
 
 
87
    These are composed of the low-level methods:
 
88
     * create_path
 
89
     * create_file or create_directory or create_symlink
 
90
     * version_file
 
91
     * set_executability
 
92
    """
 
93
    def __init__(self, tree, pb=DummyProgress()):
 
94
        """Note: a tree_write lock is taken on the tree.
 
95
        
 
96
        Use TreeTransform.finalize() to release the lock (can be omitted if
 
97
        TreeTransform.apply() called).
95
98
        """
96
99
        object.__init__(self)
97
100
        self._tree = tree
 
101
        self._tree.lock_tree_write()
 
102
        try:
 
103
            control_files = self._tree._control_files
 
104
            self._limbodir = urlutils.local_path_from_url(
 
105
                control_files.controlfilename('limbo'))
 
106
            try:
 
107
                os.mkdir(self._limbodir)
 
108
            except OSError, e:
 
109
                if e.errno == errno.EEXIST:
 
110
                    raise ExistingLimbo(self._limbodir)
 
111
            self._deletiondir = urlutils.local_path_from_url(
 
112
                control_files.controlfilename('pending-deletion'))
 
113
            try:
 
114
                os.mkdir(self._deletiondir)
 
115
            except OSError, e:
 
116
                if e.errno == errno.EEXIST:
 
117
                    raise errors.ExistingPendingDeletion(self._deletiondir)
 
118
 
 
119
        except: 
 
120
            self._tree.unlock()
 
121
            raise
 
122
 
98
123
        self._id_number = 0
99
 
        # mapping of trans_id -> new basename
100
124
        self._new_name = {}
101
 
        # mapping of trans_id -> new parent trans_id
102
125
        self._new_parent = {}
103
 
        # mapping of trans_id with new contents -> new file_kind
104
126
        self._new_contents = {}
105
 
        # mapping of trans_id => (sha1 of content, stat_value)
106
 
        self._observed_sha1s = {}
107
 
        # Set of trans_ids whose contents will be removed
 
127
        # A mapping of transform ids to their limbo filename
 
128
        self._limbo_files = {}
 
129
        # A mapping of transform ids to a set of the transform ids of children
 
130
        # that their limbo directory has
 
131
        self._limbo_children = {}
 
132
        # Map transform ids to maps of child filename to child transform id
 
133
        self._limbo_children_names = {}
 
134
        # List of transform ids that need to be renamed from limbo into place
 
135
        self._needs_rename = set()
108
136
        self._removed_contents = set()
109
 
        # Mapping of trans_id -> new execute-bit value
110
137
        self._new_executability = {}
111
 
        # Mapping of trans_id -> new tree-reference value
112
138
        self._new_reference_revision = {}
113
 
        # Mapping of trans_id -> new file_id
114
139
        self._new_id = {}
115
 
        # Mapping of old file-id -> trans_id
116
140
        self._non_present_ids = {}
117
 
        # Mapping of new file_id -> trans_id
118
141
        self._r_new_id = {}
119
 
        # Set of trans_ids that will be removed
120
142
        self._removed_id = set()
121
 
        # Mapping of path in old tree -> trans_id
122
143
        self._tree_path_ids = {}
123
 
        # Mapping trans_id -> path in old tree
124
144
        self._tree_id_paths = {}
125
 
        # The trans_id that will be used as the tree root
126
 
        root_id = tree.get_root_id()
127
 
        if root_id is not None:
128
 
            self._new_root = self.trans_id_tree_file_id(root_id)
129
 
        else:
130
 
            self._new_root = None
131
 
        # Indicator of whether the transform has been applied
132
 
        self._done = False
133
 
        # A progress bar
 
145
        # Cache of realpath results, to speed up canonical_path
 
146
        self._realpaths = {}
 
147
        # Cache of relpath results, to speed up canonical_path
 
148
        self._relpaths = {}
 
149
        self._new_root = self.trans_id_tree_file_id(tree.get_root_id())
 
150
        self.__done = False
134
151
        self._pb = pb
135
 
        # Whether the target is case sensitive
136
 
        self._case_sensitive_target = case_sensitive
137
 
        # A counter of how many files have been renamed
138
152
        self.rename_count = 0
139
153
 
140
 
    def finalize(self):
141
 
        """Release the working tree lock, if held.
142
 
 
143
 
        This is required if apply has not been invoked, but can be invoked
144
 
        even after apply.
145
 
        """
146
 
        if self._tree is None:
147
 
            return
148
 
        self._tree.unlock()
149
 
        self._tree = None
150
 
 
151
154
    def __get_root(self):
152
155
        return self._new_root
153
156
 
154
157
    root = property(__get_root)
155
158
 
 
159
    def finalize(self):
 
160
        """Release the working tree lock, if held, clean up limbo dir.
 
161
 
 
162
        This is required if apply has not been invoked, but can be invoked
 
163
        even after apply.
 
164
        """
 
165
        if self._tree is None:
 
166
            return
 
167
        try:
 
168
            entries = [(self._limbo_name(t), t, k) for t, k in
 
169
                       self._new_contents.iteritems()]
 
170
            entries.sort(reverse=True)
 
171
            for path, trans_id, kind in entries:
 
172
                if kind == "directory":
 
173
                    os.rmdir(path)
 
174
                else:
 
175
                    os.unlink(path)
 
176
            try:
 
177
                os.rmdir(self._limbodir)
 
178
            except OSError:
 
179
                # We don't especially care *why* the dir is immortal.
 
180
                raise ImmortalLimbo(self._limbodir)
 
181
            try:
 
182
                os.rmdir(self._deletiondir)
 
183
            except OSError:
 
184
                raise errors.ImmortalPendingDeletion(self._deletiondir)
 
185
        finally:
 
186
            self._tree.unlock()
 
187
            self._tree = None
 
188
 
156
189
    def _assign_id(self):
157
190
        """Produce a new tranform id"""
158
191
        new_id = "new-%s" % self._id_number
168
201
 
169
202
    def adjust_path(self, name, parent, trans_id):
170
203
        """Change the path that is assigned to a transaction id."""
171
 
        if parent is None:
172
 
            raise ValueError("Parent trans-id may not be None")
173
204
        if trans_id == self._new_root:
174
205
            raise CantMoveRoot
 
206
        previous_parent = self._new_parent.get(trans_id)
 
207
        previous_name = self._new_name.get(trans_id)
175
208
        self._new_name[trans_id] = name
176
209
        self._new_parent[trans_id] = parent
 
210
        if (trans_id in self._limbo_files and
 
211
            trans_id not in self._needs_rename):
 
212
            self._rename_in_limbo([trans_id])
 
213
            self._limbo_children[previous_parent].remove(trans_id)
 
214
            del self._limbo_children_names[previous_parent][previous_name]
 
215
 
 
216
    def _rename_in_limbo(self, trans_ids):
 
217
        """Fix limbo names so that the right final path is produced.
 
218
 
 
219
        This means we outsmarted ourselves-- we tried to avoid renaming
 
220
        these files later by creating them with their final names in their
 
221
        final parents.  But now the previous name or parent is no longer
 
222
        suitable, so we have to rename them.
 
223
 
 
224
        Even for trans_ids that have no new contents, we must remove their
 
225
        entries from _limbo_files, because they are now stale.
 
226
        """
 
227
        for trans_id in trans_ids:
 
228
            old_path = self._limbo_files.pop(trans_id)
 
229
            if trans_id not in self._new_contents:
 
230
                continue
 
231
            new_path = self._limbo_name(trans_id)
 
232
            os.rename(old_path, new_path)
177
233
 
178
234
    def adjust_root_path(self, name, parent):
179
235
        """Emulate moving the root by moving all children, instead.
180
 
 
 
236
        
181
237
        We do this by undoing the association of root's transaction id with the
182
238
        current tree.  This allows us to create a new directory with that
183
 
        transaction id.  We unversion the root directory and version the
 
239
        transaction id.  We unversion the root directory and version the 
184
240
        physically new directory, and hope someone versions the tree root
185
241
        later.
186
242
        """
189
245
        # force moving all children of root
190
246
        for child_id in self.iter_tree_children(old_root):
191
247
            if child_id != parent:
192
 
                self.adjust_path(self.final_name(child_id),
 
248
                self.adjust_path(self.final_name(child_id), 
193
249
                                 self.final_parent(child_id), child_id)
194
250
            file_id = self.final_file_id(child_id)
195
251
            if file_id is not None:
196
252
                self.unversion_file(child_id)
197
253
            self.version_file(file_id, child_id)
198
 
 
 
254
        
199
255
        # the physical root needs a new transaction id
200
256
        self._tree_path_ids.pop("")
201
257
        self._tree_id_paths.pop(old_root)
207
263
        self.version_file(old_root_file_id, old_root)
208
264
        self.unversion_file(self._new_root)
209
265
 
210
 
    def fixup_new_roots(self):
211
 
        """Reinterpret requests to change the root directory
212
 
 
213
 
        Instead of creating a root directory, or moving an existing directory,
214
 
        all the attributes and children of the new root are applied to the
215
 
        existing root directory.
216
 
 
217
 
        This means that the old root trans-id becomes obsolete, so it is
218
 
        recommended only to invoke this after the root trans-id has become
219
 
        irrelevant.
220
 
        """
221
 
        new_roots = [k for k, v in self._new_parent.iteritems() if v is
222
 
                     ROOT_PARENT]
223
 
        if len(new_roots) < 1:
224
 
            return
225
 
        if len(new_roots) != 1:
226
 
            raise ValueError('A tree cannot have two roots!')
227
 
        if self._new_root is None:
228
 
            self._new_root = new_roots[0]
229
 
            return
230
 
        old_new_root = new_roots[0]
231
 
        # TODO: What to do if a old_new_root is present, but self._new_root is
232
 
        #       not listed as being removed? This code explicitly unversions
233
 
        #       the old root and versions it with the new file_id. Though that
234
 
        #       seems like an incomplete delta
235
 
 
236
 
        # unversion the new root's directory.
237
 
        file_id = self.final_file_id(old_new_root)
238
 
        if old_new_root in self._new_id:
239
 
            self.cancel_versioning(old_new_root)
240
 
        else:
241
 
            self.unversion_file(old_new_root)
242
 
        # if, at this stage, root still has an old file_id, zap it so we can
243
 
        # stick a new one in.
244
 
        if (self.tree_file_id(self._new_root) is not None and
245
 
            self._new_root not in self._removed_id):
246
 
            self.unversion_file(self._new_root)
247
 
        self.version_file(file_id, self._new_root)
248
 
 
249
 
        # Now move children of new root into old root directory.
250
 
        # Ensure all children are registered with the transaction, but don't
251
 
        # use directly-- some tree children have new parents
252
 
        list(self.iter_tree_children(old_new_root))
253
 
        # Move all children of new root into old root directory.
254
 
        for child in self.by_parent().get(old_new_root, []):
255
 
            self.adjust_path(self.final_name(child), self._new_root, child)
256
 
 
257
 
        # Ensure old_new_root has no directory.
258
 
        if old_new_root in self._new_contents:
259
 
            self.cancel_creation(old_new_root)
260
 
        else:
261
 
            self.delete_contents(old_new_root)
262
 
 
263
 
        # prevent deletion of root directory.
264
 
        if self._new_root in self._removed_contents:
265
 
            self.cancel_deletion(self._new_root)
266
 
 
267
 
        # destroy path info for old_new_root.
268
 
        del self._new_parent[old_new_root]
269
 
        del self._new_name[old_new_root]
270
 
 
271
266
    def trans_id_tree_file_id(self, inventory_id):
272
267
        """Determine the transaction id of a working tree file.
273
 
 
 
268
        
274
269
        This reflects only files that already exist, not ones that will be
275
270
        added by transactions.
276
271
        """
277
 
        if inventory_id is None:
278
 
            raise ValueError('None is not a valid file id')
279
 
        path = self._tree.id2path(inventory_id)
 
272
        path = self._tree.inventory.id2path(inventory_id)
280
273
        return self.trans_id_tree_path(path)
281
274
 
282
275
    def trans_id_file_id(self, file_id):
285
278
        a transaction has been unversioned, it is deliberately still returned.
286
279
        (this will likely lead to an unversioned parent conflict.)
287
280
        """
288
 
        if file_id is None:
289
 
            raise ValueError('None is not a valid file id')
290
281
        if file_id in self._r_new_id and self._r_new_id[file_id] is not None:
291
282
            return self._r_new_id[file_id]
292
 
        else:
293
 
            try:
294
 
                self._tree.iter_entries_by_dir([file_id]).next()
295
 
            except StopIteration:
296
 
                if file_id in self._non_present_ids:
297
 
                    return self._non_present_ids[file_id]
298
 
                else:
299
 
                    trans_id = self._assign_id()
300
 
                    self._non_present_ids[file_id] = trans_id
301
 
                    return trans_id
302
 
            else:
303
 
                return self.trans_id_tree_file_id(file_id)
 
283
        elif file_id in self._tree.inventory:
 
284
            return self.trans_id_tree_file_id(file_id)
 
285
        elif file_id in self._non_present_ids:
 
286
            return self._non_present_ids[file_id]
 
287
        else:
 
288
            trans_id = self._assign_id()
 
289
            self._non_present_ids[file_id] = trans_id
 
290
            return trans_id
 
291
 
 
292
    def canonical_path(self, path):
 
293
        """Get the canonical tree-relative path"""
 
294
        # don't follow final symlinks
 
295
        abs = self._tree.abspath(path)
 
296
        if abs in self._relpaths:
 
297
            return self._relpaths[abs]
 
298
        dirname, basename = os.path.split(abs)
 
299
        if dirname not in self._realpaths:
 
300
            self._realpaths[dirname] = os.path.realpath(dirname)
 
301
        dirname = self._realpaths[dirname]
 
302
        abs = pathjoin(dirname, basename)
 
303
        if dirname in self._relpaths:
 
304
            relpath = pathjoin(self._relpaths[dirname], basename)
 
305
            relpath = relpath.rstrip('/\\')
 
306
        else:
 
307
            relpath = self._tree.relpath(abs)
 
308
        self._relpaths[abs] = relpath
 
309
        return relpath
304
310
 
305
311
    def trans_id_tree_path(self, path):
306
312
        """Determine (and maybe set) the transaction ID for a tree path."""
317
323
            return ROOT_PARENT
318
324
        return self.trans_id_tree_path(os.path.dirname(path))
319
325
 
 
326
    def create_file(self, contents, trans_id, mode_id=None):
 
327
        """Schedule creation of a new file.
 
328
 
 
329
        See also new_file.
 
330
        
 
331
        Contents is an iterator of strings, all of which will be written
 
332
        to the target destination.
 
333
 
 
334
        New file takes the permissions of any existing file with that id,
 
335
        unless mode_id is specified.
 
336
        """
 
337
        name = self._limbo_name(trans_id)
 
338
        f = open(name, 'wb')
 
339
        try:
 
340
            try:
 
341
                unique_add(self._new_contents, trans_id, 'file')
 
342
            except:
 
343
                # Clean up the file, it never got registered so
 
344
                # TreeTransform.finalize() won't clean it up.
 
345
                f.close()
 
346
                os.unlink(name)
 
347
                raise
 
348
 
 
349
            f.writelines(contents)
 
350
        finally:
 
351
            f.close()
 
352
        self._set_mode(trans_id, mode_id, S_ISREG)
 
353
 
 
354
    def _set_mode(self, trans_id, mode_id, typefunc):
 
355
        """Set the mode of new file contents.
 
356
        The mode_id is the existing file to get the mode from (often the same
 
357
        as trans_id).  The operation is only performed if there's a mode match
 
358
        according to typefunc.
 
359
        """
 
360
        if mode_id is None:
 
361
            mode_id = trans_id
 
362
        try:
 
363
            old_path = self._tree_id_paths[mode_id]
 
364
        except KeyError:
 
365
            return
 
366
        try:
 
367
            mode = os.stat(self._tree.abspath(old_path)).st_mode
 
368
        except OSError, e:
 
369
            if e.errno == errno.ENOENT:
 
370
                return
 
371
            else:
 
372
                raise
 
373
        if typefunc(mode):
 
374
            os.chmod(self._limbo_name(trans_id), mode)
 
375
 
 
376
    def create_directory(self, trans_id):
 
377
        """Schedule creation of a new directory.
 
378
        
 
379
        See also new_directory.
 
380
        """
 
381
        os.mkdir(self._limbo_name(trans_id))
 
382
        unique_add(self._new_contents, trans_id, 'directory')
 
383
 
 
384
    def create_symlink(self, target, trans_id):
 
385
        """Schedule creation of a new symbolic link.
 
386
 
 
387
        target is a bytestring.
 
388
        See also new_symlink.
 
389
        """
 
390
        os.symlink(target, self._limbo_name(trans_id))
 
391
        unique_add(self._new_contents, trans_id, 'symlink')
 
392
 
 
393
    def cancel_creation(self, trans_id):
 
394
        """Cancel the creation of new file contents."""
 
395
        del self._new_contents[trans_id]
 
396
        children = self._limbo_children.get(trans_id)
 
397
        # if this is a limbo directory with children, move them before removing
 
398
        # the directory
 
399
        if children is not None:
 
400
            self._rename_in_limbo(children)
 
401
            del self._limbo_children[trans_id]
 
402
            del self._limbo_children_names[trans_id]
 
403
        delete_any(self._limbo_name(trans_id))
 
404
 
320
405
    def delete_contents(self, trans_id):
321
406
        """Schedule the contents of a path entry for deletion"""
322
 
        kind = self.tree_kind(trans_id)
323
 
        if kind is not None:
324
 
            self._removed_contents.add(trans_id)
 
407
        self.tree_kind(trans_id)
 
408
        self._removed_contents.add(trans_id)
325
409
 
326
410
    def cancel_deletion(self, trans_id):
327
411
        """Cancel a scheduled deletion"""
351
435
 
352
436
    def version_file(self, file_id, trans_id):
353
437
        """Schedule a file to become versioned."""
354
 
        if file_id is None:
355
 
            raise ValueError()
 
438
        assert file_id is not None
356
439
        unique_add(self._new_id, trans_id, file_id)
357
440
        unique_add(self._r_new_id, file_id, trans_id)
358
441
 
362
445
        del self._new_id[trans_id]
363
446
        del self._r_new_id[file_id]
364
447
 
365
 
    def new_paths(self, filesystem_only=False):
366
 
        """Determine the paths of all new and changed files.
367
 
 
368
 
        :param filesystem_only: if True, only calculate values for files
369
 
            that require renames or execute bit changes.
 
448
    def new_paths(self):
 
449
        """Determine the paths of all new and changed files"""
 
450
        new_ids = set()
 
451
        fp = FinalPaths(self)
 
452
        for id_set in (self._new_name, self._new_parent, self._new_contents,
 
453
                       self._new_id, self._new_executability):
 
454
            new_ids.update(id_set)
 
455
        new_paths = [(fp.get_path(t), t) for t in new_ids]
 
456
        new_paths.sort()
 
457
        return new_paths
 
458
 
 
459
    def tree_kind(self, trans_id):
 
460
        """Determine the file kind in the working tree.
 
461
 
 
462
        Raises NoSuchFile if the file does not exist
370
463
        """
371
 
        new_ids = set()
372
 
        if filesystem_only:
373
 
            stale_ids = self._needs_rename.difference(self._new_name)
374
 
            stale_ids.difference_update(self._new_parent)
375
 
            stale_ids.difference_update(self._new_contents)
376
 
            stale_ids.difference_update(self._new_id)
377
 
            needs_rename = self._needs_rename.difference(stale_ids)
378
 
            id_sets = (needs_rename, self._new_executability)
379
 
        else:
380
 
            id_sets = (self._new_name, self._new_parent, self._new_contents,
381
 
                       self._new_id, self._new_executability)
382
 
        for id_set in id_sets:
383
 
            new_ids.update(id_set)
384
 
        return sorted(FinalPaths(self).get_paths(new_ids))
385
 
 
386
 
    def _inventory_altered(self):
387
 
        """Get the trans_ids and paths of files needing new inv entries."""
388
 
        new_ids = set()
389
 
        for id_set in [self._new_name, self._new_parent, self._new_id,
390
 
                       self._new_executability]:
391
 
            new_ids.update(id_set)
392
 
        changed_kind = set(self._removed_contents)
393
 
        changed_kind.intersection_update(self._new_contents)
394
 
        changed_kind.difference_update(new_ids)
395
 
        changed_kind = (t for t in changed_kind
396
 
                        if self.tree_kind(t) != self.final_kind(t))
397
 
        new_ids.update(changed_kind)
398
 
        return sorted(FinalPaths(self).get_paths(new_ids))
 
464
        path = self._tree_id_paths.get(trans_id)
 
465
        if path is None:
 
466
            raise NoSuchFile(None)
 
467
        try:
 
468
            return file_kind(self._tree.abspath(path))
 
469
        except OSError, e:
 
470
            if e.errno != errno.ENOENT:
 
471
                raise
 
472
            else:
 
473
                raise NoSuchFile(path)
399
474
 
400
475
    def final_kind(self, trans_id):
401
476
        """Determine the final file kind, after any changes applied.
402
 
 
403
 
        :return: None if the file does not exist/has no contents.  (It is
404
 
            conceivable that a path would be created without the corresponding
405
 
            contents insertion command)
 
477
        
 
478
        Raises NoSuchFile if the file does not exist/has no contents.
 
479
        (It is conceivable that a path would be created without the
 
480
        corresponding contents insertion command)
406
481
        """
407
482
        if trans_id in self._new_contents:
408
483
            return self._new_contents[trans_id]
409
484
        elif trans_id in self._removed_contents:
410
 
            return None
 
485
            raise NoSuchFile(None)
411
486
        else:
412
487
            return self.tree_kind(trans_id)
413
488
 
420
495
            return None
421
496
        # the file is old; the old id is still valid
422
497
        if self._new_root == trans_id:
423
 
            return self._tree.get_root_id()
424
 
        return self._tree.path2id(path)
 
498
            return self._tree.inventory.root.file_id
 
499
        return self._tree.inventory.path2id(path)
425
500
 
426
501
    def final_file_id(self, trans_id):
427
502
        """Determine the file id after any changes are applied, or None.
428
 
 
 
503
        
429
504
        None indicates that the file will not be versioned after changes are
430
505
        applied.
431
506
        """
432
507
        try:
 
508
            # there is a new id for this file
 
509
            assert self._new_id[trans_id] is not None
433
510
            return self._new_id[trans_id]
434
511
        except KeyError:
435
512
            if trans_id in self._removed_id:
470
547
 
471
548
    def by_parent(self):
472
549
        """Return a map of parent: children for known parents.
473
 
 
 
550
        
474
551
        Only new paths and parents of tree files with assigned ids are used.
475
552
        """
476
553
        by_parent = {}
477
554
        items = list(self._new_parent.iteritems())
478
 
        items.extend((t, self.final_parent(t)) for t in
 
555
        items.extend((t, self.final_parent(t)) for t in 
479
556
                      self._tree_id_paths.keys())
480
557
        for trans_id, parent_id in items:
481
558
            if parent_id not in by_parent:
492
569
 
493
570
    def find_conflicts(self):
494
571
        """Find any violations of inventory or filesystem invariants"""
495
 
        if self._done is True:
 
572
        if self.__done is True:
496
573
            raise ReusingTransform()
497
574
        conflicts = []
498
575
        # ensure all children of all existent parents are known
509
586
        conflicts.extend(self._overwrite_conflicts())
510
587
        return conflicts
511
588
 
512
 
    def _check_malformed(self):
513
 
        conflicts = self.find_conflicts()
514
 
        if len(conflicts) != 0:
515
 
            raise MalformedTransform(conflicts=conflicts)
516
 
 
517
589
    def _add_tree_children(self):
518
590
        """Add all the children of all active parents to the known paths.
519
591
 
521
593
        removed.  This is a necessary first step in detecting conflicts.
522
594
        """
523
595
        parents = self.by_parent().keys()
524
 
        parents.extend([t for t in self._removed_contents if
 
596
        parents.extend([t for t in self._removed_contents if 
525
597
                        self.tree_kind(t) == 'directory'])
526
598
        for trans_id in self._removed_id:
527
599
            file_id = self.tree_file_id(trans_id)
528
 
            if file_id is not None:
529
 
                # XXX: This seems like something that should go via a different
530
 
                #      indirection.
531
 
                if self._tree.inventory[file_id].kind == 'directory':
532
 
                    parents.append(trans_id)
533
 
            elif self.tree_kind(trans_id) == 'directory':
 
600
            if self._tree.inventory[file_id].kind == 'directory':
534
601
                parents.append(trans_id)
535
602
 
536
603
        for parent_id in parents:
537
604
            # ensure that all children are registered with the transaction
538
605
            list(self.iter_tree_children(parent_id))
539
606
 
540
 
    @deprecated_method(deprecated_in((2, 3, 0)))
 
607
    def iter_tree_children(self, parent_id):
 
608
        """Iterate through the entry's tree children, if any"""
 
609
        try:
 
610
            path = self._tree_id_paths[parent_id]
 
611
        except KeyError:
 
612
            return
 
613
        try:
 
614
            children = os.listdir(self._tree.abspath(path))
 
615
        except OSError, e:
 
616
            if e.errno != errno.ENOENT and e.errno != errno.ESRCH:
 
617
                raise
 
618
            return
 
619
            
 
620
        for child in children:
 
621
            childpath = joinpath(path, child)
 
622
            if self._tree.is_control_filename(childpath):
 
623
                continue
 
624
            yield self.trans_id_tree_path(childpath)
 
625
 
541
626
    def has_named_child(self, by_parent, parent_id, name):
542
 
        return self._has_named_child(
543
 
            name, parent_id, known_children=by_parent.get(parent_id, []))
544
 
 
545
 
    def _has_named_child(self, name, parent_id, known_children):
546
 
        """Does a parent already have a name child.
547
 
 
548
 
        :param name: The searched for name.
549
 
 
550
 
        :param parent_id: The parent for which the check is made.
551
 
 
552
 
        :param known_children: The already known children. This should have
553
 
            been recently obtained from `self.by_parent.get(parent_id)`
554
 
            (or will be if None is passed).
555
 
        """
556
 
        if known_children is None:
557
 
            known_children = self.by_parent().get(parent_id, [])
558
 
        for child in known_children:
 
627
        try:
 
628
            children = by_parent[parent_id]
 
629
        except KeyError:
 
630
            children = []
 
631
        for child in children:
559
632
            if self.final_name(child) == name:
560
633
                return True
561
 
        parent_path = self._tree_id_paths.get(parent_id, None)
562
 
        if parent_path is None:
563
 
            # No parent... no children
 
634
        try:
 
635
            path = self._tree_id_paths[parent_id]
 
636
        except KeyError:
564
637
            return False
565
 
        child_path = joinpath(parent_path, name)
566
 
        child_id = self._tree_path_ids.get(child_path, None)
 
638
        childpath = joinpath(path, name)
 
639
        child_id = self._tree_path_ids.get(childpath)
567
640
        if child_id is None:
568
 
            # Not known by the tree transform yet, check the filesystem
569
 
            return osutils.lexists(self._tree.abspath(child_path))
 
641
            return lexists(self._tree.abspath(childpath))
570
642
        else:
571
 
            raise AssertionError('child_id is missing: %s, %s, %s'
572
 
                                 % (name, parent_id, child_id))
573
 
 
574
 
    def _available_backup_name(self, name, target_id):
575
 
        """Find an available backup name.
576
 
 
577
 
        :param name: The basename of the file.
578
 
 
579
 
        :param target_id: The directory trans_id where the backup should 
580
 
            be placed.
581
 
        """
582
 
        known_children = self.by_parent().get(target_id, [])
583
 
        return osutils.available_backup_name(
584
 
            name,
585
 
            lambda base: self._has_named_child(
586
 
                base, target_id, known_children))
 
643
            if self.final_parent(child_id) != parent_id:
 
644
                return False
 
645
            if child_id in self._removed_contents:
 
646
                # XXX What about dangling file-ids?
 
647
                return False
 
648
            else:
 
649
                return True
587
650
 
588
651
    def _parent_loops(self):
589
652
        """No entry should be its own ancestor"""
619
682
 
620
683
    def _improper_versioning(self):
621
684
        """Cannot version a file with no contents, or a bad type.
622
 
 
 
685
        
623
686
        However, existing entries with no contents are okay.
624
687
        """
625
688
        conflicts = []
626
689
        for trans_id in self._new_id.iterkeys():
627
 
            kind = self.final_kind(trans_id)
628
 
            if kind is None:
 
690
            try:
 
691
                kind = self.final_kind(trans_id)
 
692
            except NoSuchFile:
629
693
                conflicts.append(('versioning no contents', trans_id))
630
694
                continue
631
 
            if not inventory.InventoryEntry.versionable_kind(kind):
 
695
            if not InventoryEntry.versionable_kind(kind):
632
696
                conflicts.append(('versioning bad kind', trans_id, kind))
633
697
        return conflicts
634
698
 
635
699
    def _executability_conflicts(self):
636
700
        """Check for bad executability changes.
637
 
 
 
701
        
638
702
        Only versioned files may have their executability set, because
639
703
        1. only versioned entries can have executability under windows
640
704
        2. only files can be executable.  (The execute bit on a directory
645
709
            if self.final_file_id(trans_id) is None:
646
710
                conflicts.append(('unversioned executability', trans_id))
647
711
            else:
648
 
                if self.final_kind(trans_id) != "file":
 
712
                try:
 
713
                    non_file = self.final_kind(trans_id) != "file"
 
714
                except NoSuchFile:
 
715
                    non_file = True
 
716
                if non_file is True:
649
717
                    conflicts.append(('non-file executability', trans_id))
650
718
        return conflicts
651
719
 
653
721
        """Check for overwrites (not permitted on Win32)"""
654
722
        conflicts = []
655
723
        for trans_id in self._new_contents:
656
 
            if self.tree_kind(trans_id) is None:
 
724
            try:
 
725
                self.tree_kind(trans_id)
 
726
            except NoSuchFile:
657
727
                continue
658
728
            if trans_id not in self._removed_contents:
659
729
                conflicts.append(('overwrite', trans_id,
666
736
        if (self._new_name, self._new_parent) == ({}, {}):
667
737
            return conflicts
668
738
        for children in by_parent.itervalues():
669
 
            name_ids = []
670
 
            for child_tid in children:
671
 
                name = self.final_name(child_tid)
672
 
                if name is not None:
673
 
                    # Keep children only if they still exist in the end
674
 
                    if not self._case_sensitive_target:
675
 
                        name = name.lower()
676
 
                    name_ids.append((name, child_tid))
 
739
            name_ids = [(self.final_name(t), t) for t in children]
677
740
            name_ids.sort()
678
741
            last_name = None
679
742
            last_trans_id = None
680
743
            for name, trans_id in name_ids:
681
 
                kind = self.final_kind(trans_id)
 
744
                try:
 
745
                    kind = self.final_kind(trans_id)
 
746
                except NoSuchFile:
 
747
                    kind = None
682
748
                file_id = self.final_file_id(trans_id)
683
749
                if kind is None and file_id is None:
684
750
                    continue
694
760
        conflicts = []
695
761
        removed_tree_ids = set((self.tree_file_id(trans_id) for trans_id in
696
762
                                self._removed_id))
697
 
        all_ids = self._tree.all_file_ids()
698
 
        active_tree_ids = all_ids.difference(removed_tree_ids)
 
763
        active_tree_ids = set((f for f in self._tree.inventory if
 
764
                               f not in removed_tree_ids))
699
765
        for trans_id, file_id in self._new_id.iteritems():
700
766
            if file_id in active_tree_ids:
701
767
                old_trans_id = self.trans_id_tree_file_id(file_id)
703
769
        return conflicts
704
770
 
705
771
    def _parent_type_conflicts(self, by_parent):
706
 
        """Children must have a directory parent"""
 
772
        """parents must have directory 'contents'."""
707
773
        conflicts = []
708
774
        for parent_id, children in by_parent.iteritems():
709
775
            if parent_id is ROOT_PARENT:
710
776
                continue
711
 
            no_children = True
712
 
            for child_id in children:
713
 
                if self.final_kind(child_id) is not None:
714
 
                    no_children = False
715
 
                    break
716
 
            if no_children:
 
777
            if not self._any_contents(children):
717
778
                continue
718
 
            # There is at least a child, so we need an existing directory to
719
 
            # contain it.
720
 
            kind = self.final_kind(parent_id)
 
779
            for child in children:
 
780
                try:
 
781
                    self.final_kind(child)
 
782
                except NoSuchFile:
 
783
                    continue
 
784
            try:
 
785
                kind = self.final_kind(parent_id)
 
786
            except NoSuchFile:
 
787
                kind = None
721
788
            if kind is None:
722
 
                # The directory will be deleted
723
789
                conflicts.append(('missing parent', parent_id))
724
790
            elif kind != "directory":
725
 
                # Meh, we need a *directory* to put something in it
726
791
                conflicts.append(('non-directory parent', parent_id))
727
792
        return conflicts
728
793
 
729
 
    def _set_executability(self, path, trans_id):
 
794
    def _any_contents(self, trans_ids):
 
795
        """Return true if any of the trans_ids, will have contents."""
 
796
        for trans_id in trans_ids:
 
797
            try:
 
798
                kind = self.final_kind(trans_id)
 
799
            except NoSuchFile:
 
800
                continue
 
801
            return True
 
802
        return False
 
803
            
 
804
    def apply(self, no_conflicts=False, _mover=None):
 
805
        """Apply all changes to the inventory and filesystem.
 
806
        
 
807
        If filesystem or inventory conflicts are present, MalformedTransform
 
808
        will be thrown.
 
809
 
 
810
        If apply succeeds, finalize is not necessary.
 
811
 
 
812
        :param no_conflicts: if True, the caller guarantees there are no
 
813
            conflicts, so no check is made.
 
814
        :param _mover: Supply an alternate FileMover, for testing
 
815
        """
 
816
        if not no_conflicts:
 
817
            conflicts = self.find_conflicts()
 
818
            if len(conflicts) != 0:
 
819
                raise MalformedTransform(conflicts=conflicts)
 
820
        inv = self._tree.inventory
 
821
        inventory_delta = []
 
822
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
823
        try:
 
824
            if _mover is None:
 
825
                mover = _FileMover()
 
826
            else:
 
827
                mover = _mover
 
828
            try:
 
829
                child_pb.update('Apply phase', 0, 2)
 
830
                self._apply_removals(inv, inventory_delta, mover)
 
831
                child_pb.update('Apply phase', 1, 2)
 
832
                modified_paths = self._apply_insertions(inv, inventory_delta,
 
833
                                                        mover)
 
834
            except:
 
835
                mover.rollback()
 
836
                raise
 
837
            else:
 
838
                mover.apply_deletions()
 
839
        finally:
 
840
            child_pb.finished()
 
841
        self._tree.apply_inventory_delta(inventory_delta)
 
842
        self.__done = True
 
843
        self.finalize()
 
844
        return _TransformResults(modified_paths, self.rename_count)
 
845
 
 
846
    def _limbo_name(self, trans_id):
 
847
        """Generate the limbo name of a file"""
 
848
        limbo_name = self._limbo_files.get(trans_id)
 
849
        if limbo_name is not None:
 
850
            return limbo_name
 
851
        parent = self._new_parent.get(trans_id)
 
852
        # if the parent directory is already in limbo (e.g. when building a
 
853
        # tree), choose a limbo name inside the parent, to reduce further
 
854
        # renames.
 
855
        use_direct_path = False
 
856
        if self._new_contents.get(parent) == 'directory':
 
857
            filename = self._new_name.get(trans_id)
 
858
            if filename is not None:
 
859
                if parent not in self._limbo_children:
 
860
                    self._limbo_children[parent] = set()
 
861
                    self._limbo_children_names[parent] = {}
 
862
                    use_direct_path = True
 
863
                # the direct path can only be used if no other file has
 
864
                # already taken this pathname, i.e. if the name is unused, or
 
865
                # if it is already associated with this trans_id.
 
866
                elif (self._limbo_children_names[parent].get(filename)
 
867
                      in (trans_id, None)):
 
868
                    use_direct_path = True
 
869
        if use_direct_path:
 
870
            limbo_name = pathjoin(self._limbo_files[parent], filename)
 
871
            self._limbo_children[parent].add(trans_id)
 
872
            self._limbo_children_names[parent][filename] = trans_id
 
873
        else:
 
874
            limbo_name = pathjoin(self._limbodir, trans_id)
 
875
            self._needs_rename.add(trans_id)
 
876
        self._limbo_files[trans_id] = limbo_name
 
877
        return limbo_name
 
878
 
 
879
    def _apply_removals(self, inv, inventory_delta, mover):
 
880
        """Perform tree operations that remove directory/inventory names.
 
881
        
 
882
        That is, delete files that are to be deleted, and put any files that
 
883
        need renaming into limbo.  This must be done in strict child-to-parent
 
884
        order.
 
885
        """
 
886
        tree_paths = list(self._tree_path_ids.iteritems())
 
887
        tree_paths.sort(reverse=True)
 
888
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
889
        try:
 
890
            for num, data in enumerate(tree_paths):
 
891
                path, trans_id = data
 
892
                child_pb.update('removing file', num, len(tree_paths))
 
893
                full_path = self._tree.abspath(path)
 
894
                if trans_id in self._removed_contents:
 
895
                    mover.pre_delete(full_path, os.path.join(self._deletiondir,
 
896
                                     trans_id))
 
897
                elif trans_id in self._new_name or trans_id in \
 
898
                    self._new_parent:
 
899
                    try:
 
900
                        mover.rename(full_path, self._limbo_name(trans_id))
 
901
                    except OSError, e:
 
902
                        if e.errno != errno.ENOENT:
 
903
                            raise
 
904
                    else:
 
905
                        self.rename_count += 1
 
906
                if trans_id in self._removed_id:
 
907
                    if trans_id == self._new_root:
 
908
                        file_id = self._tree.inventory.root.file_id
 
909
                    else:
 
910
                        file_id = self.tree_file_id(trans_id)
 
911
                    assert file_id is not None
 
912
                    inventory_delta.append((path, None, file_id, None))
 
913
        finally:
 
914
            child_pb.finished()
 
915
 
 
916
    def _apply_insertions(self, inv, inventory_delta, mover):
 
917
        """Perform tree operations that insert directory/inventory names.
 
918
        
 
919
        That is, create any files that need to be created, and restore from
 
920
        limbo any files that needed renaming.  This must be done in strict
 
921
        parent-to-child order.
 
922
        """
 
923
        new_paths = self.new_paths()
 
924
        modified_paths = []
 
925
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
926
        try:
 
927
            for num, (path, trans_id) in enumerate(new_paths):
 
928
                new_entry = None
 
929
                child_pb.update('adding file', num, len(new_paths))
 
930
                try:
 
931
                    kind = self._new_contents[trans_id]
 
932
                except KeyError:
 
933
                    kind = contents = None
 
934
                if trans_id in self._new_contents or \
 
935
                    self.path_changed(trans_id):
 
936
                    full_path = self._tree.abspath(path)
 
937
                    if trans_id in self._needs_rename:
 
938
                        try:
 
939
                            mover.rename(self._limbo_name(trans_id), full_path)
 
940
                        except OSError, e:
 
941
                            # We may be renaming a dangling inventory id
 
942
                            if e.errno != errno.ENOENT:
 
943
                                raise
 
944
                        else:
 
945
                            self.rename_count += 1
 
946
                    if trans_id in self._new_contents:
 
947
                        modified_paths.append(full_path)
 
948
                        del self._new_contents[trans_id]
 
949
 
 
950
                if trans_id in self._new_id:
 
951
                    if kind is None:
 
952
                        kind = file_kind(self._tree.abspath(path))
 
953
                    if trans_id in self._new_reference_revision:
 
954
                        new_entry = inventory.TreeReference(
 
955
                            self._new_id[trans_id],
 
956
                            self._new_name[trans_id], 
 
957
                            self.final_file_id(self._new_parent[trans_id]),
 
958
                            None, self._new_reference_revision[trans_id])
 
959
                    else:
 
960
                        new_entry = inventory.make_entry(kind,
 
961
                            self.final_name(trans_id),
 
962
                            self.final_file_id(self.final_parent(trans_id)),
 
963
                            self._new_id[trans_id])
 
964
                else:
 
965
                    if trans_id in self._new_name or trans_id in\
 
966
                        self._new_parent or\
 
967
                        trans_id in self._new_executability:
 
968
                        file_id = self.final_file_id(trans_id)
 
969
                        if file_id is not None:
 
970
                            entry = inv[file_id]
 
971
                            new_entry = entry.copy()
 
972
 
 
973
                    if trans_id in self._new_name or trans_id in\
 
974
                        self._new_parent:
 
975
                            if new_entry is not None:
 
976
                                new_entry.name = self.final_name(trans_id)
 
977
                                parent = self.final_parent(trans_id)
 
978
                                parent_id = self.final_file_id(parent)
 
979
                                new_entry.parent_id = parent_id
 
980
 
 
981
                if trans_id in self._new_executability:
 
982
                    self._set_executability(path, new_entry, trans_id)
 
983
                if new_entry is not None:
 
984
                    if new_entry.file_id in inv:
 
985
                        old_path = inv.id2path(new_entry.file_id)
 
986
                    else:
 
987
                        old_path = None
 
988
                    inventory_delta.append((old_path, path,
 
989
                                            new_entry.file_id,
 
990
                                            new_entry))
 
991
        finally:
 
992
            child_pb.finished()
 
993
        return modified_paths
 
994
 
 
995
    def _set_executability(self, path, entry, trans_id):
730
996
        """Set the executability of versioned files """
 
997
        new_executability = self._new_executability[trans_id]
 
998
        entry.executable = new_executability
731
999
        if supports_executable():
732
 
            new_executability = self._new_executability[trans_id]
733
1000
            abspath = self._tree.abspath(path)
734
1001
            current_mode = os.stat(abspath).st_mode
735
1002
            if new_executability:
752
1019
            self.version_file(file_id, trans_id)
753
1020
        return trans_id
754
1021
 
755
 
    def new_file(self, name, parent_id, contents, file_id=None,
756
 
                 executable=None, sha1=None):
 
1022
    def new_file(self, name, parent_id, contents, file_id=None, 
 
1023
                 executable=None):
757
1024
        """Convenience method to create files.
758
 
 
 
1025
        
759
1026
        name is the name of the file to create.
760
1027
        parent_id is the transaction id of the parent directory of the file.
761
1028
        contents is an iterator of bytestrings, which will be used to produce
766
1033
        trans_id = self._new_entry(name, parent_id, file_id)
767
1034
        # TODO: rather than scheduling a set_executable call,
768
1035
        # have create_file create the file with the right mode.
769
 
        self.create_file(contents, trans_id, sha1=sha1)
 
1036
        self.create_file(contents, trans_id)
770
1037
        if executable is not None:
771
1038
            self.set_executability(executable, trans_id)
772
1039
        return trans_id
781
1048
        """
782
1049
        trans_id = self._new_entry(name, parent_id, file_id)
783
1050
        self.create_directory(trans_id)
784
 
        return trans_id
 
1051
        return trans_id 
785
1052
 
786
1053
    def new_symlink(self, name, parent_id, target, file_id=None):
787
1054
        """Convenience method to create symbolic link.
788
 
 
 
1055
        
789
1056
        name is the name of the symlink to create.
790
1057
        parent_id is the transaction id of the parent directory of the symlink.
791
1058
        target is a bytestring of the target of the symlink.
795
1062
        self.create_symlink(target, trans_id)
796
1063
        return trans_id
797
1064
 
798
 
    def new_orphan(self, trans_id, parent_id):
799
 
        """Schedule an item to be orphaned.
800
 
 
801
 
        When a directory is about to be removed, its children, if they are not
802
 
        versioned are moved out of the way: they don't have a parent anymore.
803
 
 
804
 
        :param trans_id: The trans_id of the existing item.
805
 
        :param parent_id: The parent trans_id of the item.
806
 
        """
807
 
        raise NotImplementedError(self.new_orphan)
808
 
 
809
 
    def _get_potential_orphans(self, dir_id):
810
 
        """Find the potential orphans in a directory.
811
 
 
812
 
        A directory can't be safely deleted if there are versioned files in it.
813
 
        If all the contained files are unversioned then they can be orphaned.
814
 
 
815
 
        The 'None' return value means that the directory contains at least one
816
 
        versioned file and should not be deleted.
817
 
 
818
 
        :param dir_id: The directory trans id.
819
 
 
820
 
        :return: A list of the orphan trans ids or None if at least one
821
 
             versioned file is present.
822
 
        """
823
 
        orphans = []
824
 
        # Find the potential orphans, stop if one item should be kept
825
 
        for child_tid in self.by_parent()[dir_id]:
826
 
            if child_tid in self._removed_contents:
827
 
                # The child is removed as part of the transform. Since it was
828
 
                # versioned before, it's not an orphan
829
 
                continue
830
 
            elif self.final_file_id(child_tid) is None:
831
 
                # The child is not versioned
832
 
                orphans.append(child_tid)
833
 
            else:
834
 
                # We have a versioned file here, searching for orphans is
835
 
                # meaningless.
836
 
                orphans = None
837
 
                break
838
 
        return orphans
839
 
 
840
1065
    def _affected_ids(self):
841
1066
        """Return the set of transform ids affected by the transform"""
842
1067
        trans_ids = set(self._removed_id)
872
1097
        from_path = self._tree_id_paths.get(from_trans_id)
873
1098
        if from_versioned:
874
1099
            # get data from working tree if versioned
875
 
            from_entry = self._tree.iter_entries_by_dir([file_id]).next()[1]
 
1100
            from_entry = self._tree.inventory[file_id]
876
1101
            from_name = from_entry.name
877
1102
            from_parent = from_entry.parent_id
878
1103
        else:
901
1126
        Return a (name, parent, kind, executable) tuple
902
1127
        """
903
1128
        to_name = self.final_name(to_trans_id)
904
 
        to_kind = self.final_kind(to_trans_id)
 
1129
        try:
 
1130
            to_kind = self.final_kind(to_trans_id)
 
1131
        except NoSuchFile:
 
1132
            to_kind = None
905
1133
        to_parent = self.final_file_id(self.final_parent(to_trans_id))
906
1134
        if to_trans_id in self._new_executability:
907
1135
            to_executable = self._new_executability[to_trans_id]
911
1139
            to_executable = False
912
1140
        return to_name, to_parent, to_kind, to_executable
913
1141
 
914
 
    def iter_changes(self):
915
 
        """Produce output in the same format as Tree.iter_changes.
 
1142
    def _iter_changes(self):
 
1143
        """Produce output in the same format as Tree._iter_changes.
916
1144
 
917
1145
        Will produce nonsensical results if invoked while inventory/filesystem
918
1146
        conflicts (as reported by TreeTransform.find_conflicts()) are present.
973
1201
                   (from_executable, to_executable)))
974
1202
        return iter(sorted(results, key=lambda x:x[1]))
975
1203
 
976
 
    def get_preview_tree(self):
977
 
        """Return a tree representing the result of the transform.
978
 
 
979
 
        The tree is a snapshot, and altering the TreeTransform will invalidate
980
 
        it.
981
 
        """
982
 
        return _PreviewTree(self)
983
 
 
984
 
    def commit(self, branch, message, merge_parents=None, strict=False,
985
 
               timestamp=None, timezone=None, committer=None, authors=None,
986
 
               revprops=None, revision_id=None):
987
 
        """Commit the result of this TreeTransform to a branch.
988
 
 
989
 
        :param branch: The branch to commit to.
990
 
        :param message: The message to attach to the commit.
991
 
        :param merge_parents: Additional parent revision-ids specified by
992
 
            pending merges.
993
 
        :param strict: If True, abort the commit if there are unversioned
994
 
            files.
995
 
        :param timestamp: if not None, seconds-since-epoch for the time and
996
 
            date.  (May be a float.)
997
 
        :param timezone: Optional timezone for timestamp, as an offset in
998
 
            seconds.
999
 
        :param committer: Optional committer in email-id format.
1000
 
            (e.g. "J Random Hacker <jrandom@example.com>")
1001
 
        :param authors: Optional list of authors in email-id format.
1002
 
        :param revprops: Optional dictionary of revision properties.
1003
 
        :param revision_id: Optional revision id.  (Specifying a revision-id
1004
 
            may reduce performance for some non-native formats.)
1005
 
        :return: The revision_id of the revision committed.
1006
 
        """
1007
 
        self._check_malformed()
1008
 
        if strict:
1009
 
            unversioned = set(self._new_contents).difference(set(self._new_id))
1010
 
            for trans_id in unversioned:
1011
 
                if self.final_file_id(trans_id) is None:
1012
 
                    raise errors.StrictCommitFailed()
1013
 
 
1014
 
        revno, last_rev_id = branch.last_revision_info()
1015
 
        if last_rev_id == _mod_revision.NULL_REVISION:
1016
 
            if merge_parents is not None:
1017
 
                raise ValueError('Cannot supply merge parents for first'
1018
 
                                 ' commit.')
1019
 
            parent_ids = []
1020
 
        else:
1021
 
            parent_ids = [last_rev_id]
1022
 
            if merge_parents is not None:
1023
 
                parent_ids.extend(merge_parents)
1024
 
        if self._tree.get_revision_id() != last_rev_id:
1025
 
            raise ValueError('TreeTransform not based on branch basis: %s' %
1026
 
                             self._tree.get_revision_id())
1027
 
        revprops = commit.Commit.update_revprops(revprops, branch, authors)
1028
 
        builder = branch.get_commit_builder(parent_ids,
1029
 
                                            timestamp=timestamp,
1030
 
                                            timezone=timezone,
1031
 
                                            committer=committer,
1032
 
                                            revprops=revprops,
1033
 
                                            revision_id=revision_id)
1034
 
        preview = self.get_preview_tree()
1035
 
        list(builder.record_iter_changes(preview, last_rev_id,
1036
 
                                         self.iter_changes()))
1037
 
        builder.finish_inventory()
1038
 
        revision_id = builder.commit(message)
1039
 
        branch.set_last_revision_info(revno + 1, revision_id)
1040
 
        return revision_id
1041
 
 
1042
 
    def _text_parent(self, trans_id):
1043
 
        file_id = self.tree_file_id(trans_id)
1044
 
        try:
1045
 
            if file_id is None or self._tree.kind(file_id) != 'file':
1046
 
                return None
1047
 
        except errors.NoSuchFile:
1048
 
            return None
1049
 
        return file_id
1050
 
 
1051
 
    def _get_parents_texts(self, trans_id):
1052
 
        """Get texts for compression parents of this file."""
1053
 
        file_id = self._text_parent(trans_id)
1054
 
        if file_id is None:
1055
 
            return ()
1056
 
        return (self._tree.get_file_text(file_id),)
1057
 
 
1058
 
    def _get_parents_lines(self, trans_id):
1059
 
        """Get lines for compression parents of this file."""
1060
 
        file_id = self._text_parent(trans_id)
1061
 
        if file_id is None:
1062
 
            return ()
1063
 
        return (self._tree.get_file_lines(file_id),)
1064
 
 
1065
 
    def serialize(self, serializer):
1066
 
        """Serialize this TreeTransform.
1067
 
 
1068
 
        :param serializer: A Serialiser like pack.ContainerSerializer.
1069
 
        """
1070
 
        new_name = dict((k, v.encode('utf-8')) for k, v in
1071
 
                        self._new_name.items())
1072
 
        new_executability = dict((k, int(v)) for k, v in
1073
 
                                 self._new_executability.items())
1074
 
        tree_path_ids = dict((k.encode('utf-8'), v)
1075
 
                             for k, v in self._tree_path_ids.items())
1076
 
        attribs = {
1077
 
            '_id_number': self._id_number,
1078
 
            '_new_name': new_name,
1079
 
            '_new_parent': self._new_parent,
1080
 
            '_new_executability': new_executability,
1081
 
            '_new_id': self._new_id,
1082
 
            '_tree_path_ids': tree_path_ids,
1083
 
            '_removed_id': list(self._removed_id),
1084
 
            '_removed_contents': list(self._removed_contents),
1085
 
            '_non_present_ids': self._non_present_ids,
1086
 
            }
1087
 
        yield serializer.bytes_record(bencode.bencode(attribs),
1088
 
                                      (('attribs',),))
1089
 
        for trans_id, kind in self._new_contents.items():
1090
 
            if kind == 'file':
1091
 
                lines = osutils.chunks_to_lines(
1092
 
                    self._read_file_chunks(trans_id))
1093
 
                parents = self._get_parents_lines(trans_id)
1094
 
                mpdiff = multiparent.MultiParent.from_lines(lines, parents)
1095
 
                content = ''.join(mpdiff.to_patch())
1096
 
            if kind == 'directory':
1097
 
                content = ''
1098
 
            if kind == 'symlink':
1099
 
                content = self._read_symlink_target(trans_id)
1100
 
            yield serializer.bytes_record(content, ((trans_id, kind),))
1101
 
 
1102
 
    def deserialize(self, records):
1103
 
        """Deserialize a stored TreeTransform.
1104
 
 
1105
 
        :param records: An iterable of (names, content) tuples, as per
1106
 
            pack.ContainerPushParser.
1107
 
        """
1108
 
        names, content = records.next()
1109
 
        attribs = bencode.bdecode(content)
1110
 
        self._id_number = attribs['_id_number']
1111
 
        self._new_name = dict((k, v.decode('utf-8'))
1112
 
                            for k, v in attribs['_new_name'].items())
1113
 
        self._new_parent = attribs['_new_parent']
1114
 
        self._new_executability = dict((k, bool(v)) for k, v in
1115
 
            attribs['_new_executability'].items())
1116
 
        self._new_id = attribs['_new_id']
1117
 
        self._r_new_id = dict((v, k) for k, v in self._new_id.items())
1118
 
        self._tree_path_ids = {}
1119
 
        self._tree_id_paths = {}
1120
 
        for bytepath, trans_id in attribs['_tree_path_ids'].items():
1121
 
            path = bytepath.decode('utf-8')
1122
 
            self._tree_path_ids[path] = trans_id
1123
 
            self._tree_id_paths[trans_id] = path
1124
 
        self._removed_id = set(attribs['_removed_id'])
1125
 
        self._removed_contents = set(attribs['_removed_contents'])
1126
 
        self._non_present_ids = attribs['_non_present_ids']
1127
 
        for ((trans_id, kind),), content in records:
1128
 
            if kind == 'file':
1129
 
                mpdiff = multiparent.MultiParent.from_patch(content)
1130
 
                lines = mpdiff.to_lines(self._get_parents_texts(trans_id))
1131
 
                self.create_file(lines, trans_id)
1132
 
            if kind == 'directory':
1133
 
                self.create_directory(trans_id)
1134
 
            if kind == 'symlink':
1135
 
                self.create_symlink(content.decode('utf-8'), trans_id)
1136
 
 
1137
 
 
1138
 
class DiskTreeTransform(TreeTransformBase):
1139
 
    """Tree transform storing its contents on disk."""
1140
 
 
1141
 
    def __init__(self, tree, limbodir, pb=None,
1142
 
                 case_sensitive=True):
1143
 
        """Constructor.
1144
 
        :param tree: The tree that will be transformed, but not necessarily
1145
 
            the output tree.
1146
 
        :param limbodir: A directory where new files can be stored until
1147
 
            they are installed in their proper places
1148
 
        :param pb: ignored
1149
 
        :param case_sensitive: If True, the target of the transform is
1150
 
            case sensitive, not just case preserving.
1151
 
        """
1152
 
        TreeTransformBase.__init__(self, tree, pb, case_sensitive)
1153
 
        self._limbodir = limbodir
1154
 
        self._deletiondir = None
1155
 
        # A mapping of transform ids to their limbo filename
1156
 
        self._limbo_files = {}
1157
 
        # A mapping of transform ids to a set of the transform ids of children
1158
 
        # that their limbo directory has
1159
 
        self._limbo_children = {}
1160
 
        # Map transform ids to maps of child filename to child transform id
1161
 
        self._limbo_children_names = {}
1162
 
        # List of transform ids that need to be renamed from limbo into place
1163
 
        self._needs_rename = set()
1164
 
        self._creation_mtime = None
1165
 
 
1166
 
    def finalize(self):
1167
 
        """Release the working tree lock, if held, clean up limbo dir.
1168
 
 
1169
 
        This is required if apply has not been invoked, but can be invoked
1170
 
        even after apply.
1171
 
        """
1172
 
        if self._tree is None:
1173
 
            return
1174
 
        try:
1175
 
            entries = [(self._limbo_name(t), t, k) for t, k in
1176
 
                       self._new_contents.iteritems()]
1177
 
            entries.sort(reverse=True)
1178
 
            for path, trans_id, kind in entries:
1179
 
                delete_any(path)
1180
 
            try:
1181
 
                delete_any(self._limbodir)
1182
 
            except OSError:
1183
 
                # We don't especially care *why* the dir is immortal.
1184
 
                raise ImmortalLimbo(self._limbodir)
1185
 
            try:
1186
 
                if self._deletiondir is not None:
1187
 
                    delete_any(self._deletiondir)
1188
 
            except OSError:
1189
 
                raise errors.ImmortalPendingDeletion(self._deletiondir)
1190
 
        finally:
1191
 
            TreeTransformBase.finalize(self)
1192
 
 
1193
 
    def _limbo_name(self, trans_id):
1194
 
        """Generate the limbo name of a file"""
1195
 
        limbo_name = self._limbo_files.get(trans_id)
1196
 
        if limbo_name is None:
1197
 
            limbo_name = self._generate_limbo_path(trans_id)
1198
 
            self._limbo_files[trans_id] = limbo_name
1199
 
        return limbo_name
1200
 
 
1201
 
    def _generate_limbo_path(self, trans_id):
1202
 
        """Generate a limbo path using the trans_id as the relative path.
1203
 
 
1204
 
        This is suitable as a fallback, and when the transform should not be
1205
 
        sensitive to the path encoding of the limbo directory.
1206
 
        """
1207
 
        self._needs_rename.add(trans_id)
1208
 
        return pathjoin(self._limbodir, trans_id)
1209
 
 
1210
 
    def adjust_path(self, name, parent, trans_id):
1211
 
        previous_parent = self._new_parent.get(trans_id)
1212
 
        previous_name = self._new_name.get(trans_id)
1213
 
        TreeTransformBase.adjust_path(self, name, parent, trans_id)
1214
 
        if (trans_id in self._limbo_files and
1215
 
            trans_id not in self._needs_rename):
1216
 
            self._rename_in_limbo([trans_id])
1217
 
            if previous_parent != parent:
1218
 
                self._limbo_children[previous_parent].remove(trans_id)
1219
 
            if previous_parent != parent or previous_name != name:
1220
 
                del self._limbo_children_names[previous_parent][previous_name]
1221
 
 
1222
 
    def _rename_in_limbo(self, trans_ids):
1223
 
        """Fix limbo names so that the right final path is produced.
1224
 
 
1225
 
        This means we outsmarted ourselves-- we tried to avoid renaming
1226
 
        these files later by creating them with their final names in their
1227
 
        final parents.  But now the previous name or parent is no longer
1228
 
        suitable, so we have to rename them.
1229
 
 
1230
 
        Even for trans_ids that have no new contents, we must remove their
1231
 
        entries from _limbo_files, because they are now stale.
1232
 
        """
1233
 
        for trans_id in trans_ids:
1234
 
            old_path = self._limbo_files.pop(trans_id)
1235
 
            if trans_id not in self._new_contents:
1236
 
                continue
1237
 
            new_path = self._limbo_name(trans_id)
1238
 
            os.rename(old_path, new_path)
1239
 
            for descendant in self._limbo_descendants(trans_id):
1240
 
                desc_path = self._limbo_files[descendant]
1241
 
                desc_path = new_path + desc_path[len(old_path):]
1242
 
                self._limbo_files[descendant] = desc_path
1243
 
 
1244
 
    def _limbo_descendants(self, trans_id):
1245
 
        """Return the set of trans_ids whose limbo paths descend from this."""
1246
 
        descendants = set(self._limbo_children.get(trans_id, []))
1247
 
        for descendant in list(descendants):
1248
 
            descendants.update(self._limbo_descendants(descendant))
1249
 
        return descendants
1250
 
 
1251
 
    def create_file(self, contents, trans_id, mode_id=None, sha1=None):
1252
 
        """Schedule creation of a new file.
1253
 
 
1254
 
        :seealso: new_file.
1255
 
 
1256
 
        :param contents: an iterator of strings, all of which will be written
1257
 
            to the target destination.
1258
 
        :param trans_id: TreeTransform handle
1259
 
        :param mode_id: If not None, force the mode of the target file to match
1260
 
            the mode of the object referenced by mode_id.
1261
 
            Otherwise, we will try to preserve mode bits of an existing file.
1262
 
        :param sha1: If the sha1 of this content is already known, pass it in.
1263
 
            We can use it to prevent future sha1 computations.
1264
 
        """
1265
 
        name = self._limbo_name(trans_id)
1266
 
        f = open(name, 'wb')
1267
 
        try:
1268
 
            try:
1269
 
                unique_add(self._new_contents, trans_id, 'file')
1270
 
            except:
1271
 
                # Clean up the file, it never got registered so
1272
 
                # TreeTransform.finalize() won't clean it up.
1273
 
                f.close()
1274
 
                os.unlink(name)
1275
 
                raise
1276
 
            f.writelines(contents)
1277
 
        finally:
1278
 
            f.close()
1279
 
        self._set_mtime(name)
1280
 
        self._set_mode(trans_id, mode_id, S_ISREG)
1281
 
        # It is unfortunate we have to use lstat instead of fstat, but we just
1282
 
        # used utime and chmod on the file, so we need the accurate final
1283
 
        # details.
1284
 
        if sha1 is not None:
1285
 
            self._observed_sha1s[trans_id] = (sha1, osutils.lstat(name))
1286
 
 
1287
 
    def _read_file_chunks(self, trans_id):
1288
 
        cur_file = open(self._limbo_name(trans_id), 'rb')
1289
 
        try:
1290
 
            return cur_file.readlines()
1291
 
        finally:
1292
 
            cur_file.close()
1293
 
 
1294
 
    def _read_symlink_target(self, trans_id):
1295
 
        return os.readlink(self._limbo_name(trans_id))
1296
 
 
1297
 
    def _set_mtime(self, path):
1298
 
        """All files that are created get the same mtime.
1299
 
 
1300
 
        This time is set by the first object to be created.
1301
 
        """
1302
 
        if self._creation_mtime is None:
1303
 
            self._creation_mtime = time.time()
1304
 
        os.utime(path, (self._creation_mtime, self._creation_mtime))
1305
 
 
1306
 
    def create_hardlink(self, path, trans_id):
1307
 
        """Schedule creation of a hard link"""
1308
 
        name = self._limbo_name(trans_id)
1309
 
        try:
1310
 
            os.link(path, name)
1311
 
        except OSError, e:
1312
 
            if e.errno != errno.EPERM:
1313
 
                raise
1314
 
            raise errors.HardLinkNotSupported(path)
1315
 
        try:
1316
 
            unique_add(self._new_contents, trans_id, 'file')
1317
 
        except:
1318
 
            # Clean up the file, it never got registered so
1319
 
            # TreeTransform.finalize() won't clean it up.
1320
 
            os.unlink(name)
1321
 
            raise
1322
 
 
1323
 
    def create_directory(self, trans_id):
1324
 
        """Schedule creation of a new directory.
1325
 
 
1326
 
        See also new_directory.
1327
 
        """
1328
 
        os.mkdir(self._limbo_name(trans_id))
1329
 
        unique_add(self._new_contents, trans_id, 'directory')
1330
 
 
1331
 
    def create_symlink(self, target, trans_id):
1332
 
        """Schedule creation of a new symbolic link.
1333
 
 
1334
 
        target is a bytestring.
1335
 
        See also new_symlink.
1336
 
        """
1337
 
        if has_symlinks():
1338
 
            os.symlink(target, self._limbo_name(trans_id))
1339
 
            unique_add(self._new_contents, trans_id, 'symlink')
1340
 
        else:
1341
 
            try:
1342
 
                path = FinalPaths(self).get_path(trans_id)
1343
 
            except KeyError:
1344
 
                path = None
1345
 
            raise UnableCreateSymlink(path=path)
1346
 
 
1347
 
    def cancel_creation(self, trans_id):
1348
 
        """Cancel the creation of new file contents."""
1349
 
        del self._new_contents[trans_id]
1350
 
        if trans_id in self._observed_sha1s:
1351
 
            del self._observed_sha1s[trans_id]
1352
 
        children = self._limbo_children.get(trans_id)
1353
 
        # if this is a limbo directory with children, move them before removing
1354
 
        # the directory
1355
 
        if children is not None:
1356
 
            self._rename_in_limbo(children)
1357
 
            del self._limbo_children[trans_id]
1358
 
            del self._limbo_children_names[trans_id]
1359
 
        delete_any(self._limbo_name(trans_id))
1360
 
 
1361
 
    def new_orphan(self, trans_id, parent_id):
1362
 
        # FIXME: There is no tree config, so we use the branch one (it's weird
1363
 
        # to define it this way as orphaning can only occur in a working tree,
1364
 
        # but that's all we have (for now). It will find the option in
1365
 
        # locations.conf or bazaar.conf though) -- vila 20100916
1366
 
        conf = self._tree.branch.get_config()
1367
 
        conf_var_name = 'bzr.transform.orphan_policy'
1368
 
        orphan_policy = conf.get_user_option(conf_var_name)
1369
 
        default_policy = orphaning_registry.default_key
1370
 
        if orphan_policy is None:
1371
 
            orphan_policy = default_policy
1372
 
        if orphan_policy not in orphaning_registry:
1373
 
            trace.warning('%s (from %s) is not a known policy, defaulting '
1374
 
                'to %s' % (orphan_policy, conf_var_name, default_policy))
1375
 
            orphan_policy = default_policy
1376
 
        handle_orphan = orphaning_registry.get(orphan_policy)
1377
 
        handle_orphan(self, trans_id, parent_id)
1378
 
 
1379
 
 
1380
 
class OrphaningError(errors.BzrError):
1381
 
 
1382
 
    # Only bugs could lead to such exception being seen by the user
1383
 
    internal_error = True
1384
 
    _fmt = "Error while orphaning %s in %s directory"
1385
 
 
1386
 
    def __init__(self, orphan, parent):
1387
 
        errors.BzrError.__init__(self)
1388
 
        self.orphan = orphan
1389
 
        self.parent = parent
1390
 
 
1391
 
 
1392
 
class OrphaningForbidden(OrphaningError):
1393
 
 
1394
 
    _fmt = "Policy: %s doesn't allow creating orphans."
1395
 
 
1396
 
    def __init__(self, policy):
1397
 
        errors.BzrError.__init__(self)
1398
 
        self.policy = policy
1399
 
 
1400
 
 
1401
 
def move_orphan(tt, orphan_id, parent_id):
1402
 
    """See TreeTransformBase.new_orphan.
1403
 
 
1404
 
    This creates a new orphan in the `bzr-orphans` dir at the root of the
1405
 
    `TreeTransform`.
1406
 
 
1407
 
    :param tt: The TreeTransform orphaning `trans_id`.
1408
 
 
1409
 
    :param orphan_id: The trans id that should be orphaned.
1410
 
 
1411
 
    :param parent_id: The orphan parent trans id.
1412
 
    """
1413
 
    # Add the orphan dir if it doesn't exist
1414
 
    orphan_dir_basename = 'bzr-orphans'
1415
 
    od_id = tt.trans_id_tree_path(orphan_dir_basename)
1416
 
    if tt.final_kind(od_id) is None:
1417
 
        tt.create_directory(od_id)
1418
 
    parent_path = tt._tree_id_paths[parent_id]
1419
 
    # Find a name that doesn't exist yet in the orphan dir
1420
 
    actual_name = tt.final_name(orphan_id)
1421
 
    new_name = tt._available_backup_name(actual_name, od_id)
1422
 
    tt.adjust_path(new_name, od_id, orphan_id)
1423
 
    trace.warning('%s has been orphaned in %s'
1424
 
                  % (joinpath(parent_path, actual_name), orphan_dir_basename))
1425
 
 
1426
 
 
1427
 
def refuse_orphan(tt, orphan_id, parent_id):
1428
 
    """See TreeTransformBase.new_orphan.
1429
 
 
1430
 
    This refuses to create orphan, letting the caller handle the conflict.
1431
 
    """
1432
 
    raise OrphaningForbidden('never')
1433
 
 
1434
 
 
1435
 
orphaning_registry = registry.Registry()
1436
 
orphaning_registry.register(
1437
 
    'conflict', refuse_orphan,
1438
 
    'Leave orphans in place and create a conflict on the directory.')
1439
 
orphaning_registry.register(
1440
 
    'move', move_orphan,
1441
 
    'Move orphans into the bzr-orphans directory.')
1442
 
orphaning_registry._set_default_key('conflict')
1443
 
 
1444
 
 
1445
 
class TreeTransform(DiskTreeTransform):
1446
 
    """Represent a tree transformation.
1447
 
 
1448
 
    This object is designed to support incremental generation of the transform,
1449
 
    in any order.
1450
 
 
1451
 
    However, it gives optimum performance when parent directories are created
1452
 
    before their contents.  The transform is then able to put child files
1453
 
    directly in their parent directory, avoiding later renames.
1454
 
 
1455
 
    It is easy to produce malformed transforms, but they are generally
1456
 
    harmless.  Attempting to apply a malformed transform will cause an
1457
 
    exception to be raised before any modifications are made to the tree.
1458
 
 
1459
 
    Many kinds of malformed transforms can be corrected with the
1460
 
    resolve_conflicts function.  The remaining ones indicate programming error,
1461
 
    such as trying to create a file with no path.
1462
 
 
1463
 
    Two sets of file creation methods are supplied.  Convenience methods are:
1464
 
     * new_file
1465
 
     * new_directory
1466
 
     * new_symlink
1467
 
 
1468
 
    These are composed of the low-level methods:
1469
 
     * create_path
1470
 
     * create_file or create_directory or create_symlink
1471
 
     * version_file
1472
 
     * set_executability
1473
 
 
1474
 
    Transform/Transaction ids
1475
 
    -------------------------
1476
 
    trans_ids are temporary ids assigned to all files involved in a transform.
1477
 
    It's possible, even common, that not all files in the Tree have trans_ids.
1478
 
 
1479
 
    trans_ids are used because filenames and file_ids are not good enough
1480
 
    identifiers; filenames change, and not all files have file_ids.  File-ids
1481
 
    are also associated with trans-ids, so that moving a file moves its
1482
 
    file-id.
1483
 
 
1484
 
    trans_ids are only valid for the TreeTransform that generated them.
1485
 
 
1486
 
    Limbo
1487
 
    -----
1488
 
    Limbo is a temporary directory use to hold new versions of files.
1489
 
    Files are added to limbo by create_file, create_directory, create_symlink,
1490
 
    and their convenience variants (new_*).  Files may be removed from limbo
1491
 
    using cancel_creation.  Files are renamed from limbo into their final
1492
 
    location as part of TreeTransform.apply
1493
 
 
1494
 
    Limbo must be cleaned up, by either calling TreeTransform.apply or
1495
 
    calling TreeTransform.finalize.
1496
 
 
1497
 
    Files are placed into limbo inside their parent directories, where
1498
 
    possible.  This reduces subsequent renames, and makes operations involving
1499
 
    lots of files faster.  This optimization is only possible if the parent
1500
 
    directory is created *before* creating any of its children, so avoid
1501
 
    creating children before parents, where possible.
1502
 
 
1503
 
    Pending-deletion
1504
 
    ----------------
1505
 
    This temporary directory is used by _FileMover for storing files that are
1506
 
    about to be deleted.  In case of rollback, the files will be restored.
1507
 
    FileMover does not delete files until it is sure that a rollback will not
1508
 
    happen.
1509
 
    """
1510
 
    def __init__(self, tree, pb=None):
1511
 
        """Note: a tree_write lock is taken on the tree.
1512
 
 
1513
 
        Use TreeTransform.finalize() to release the lock (can be omitted if
1514
 
        TreeTransform.apply() called).
1515
 
        """
1516
 
        tree.lock_tree_write()
1517
 
 
1518
 
        try:
1519
 
            limbodir = urlutils.local_path_from_url(
1520
 
                tree._transport.abspath('limbo'))
1521
 
            try:
1522
 
                os.mkdir(limbodir)
1523
 
            except OSError, e:
1524
 
                if e.errno == errno.EEXIST:
1525
 
                    raise ExistingLimbo(limbodir)
1526
 
            deletiondir = urlutils.local_path_from_url(
1527
 
                tree._transport.abspath('pending-deletion'))
1528
 
            try:
1529
 
                os.mkdir(deletiondir)
1530
 
            except OSError, e:
1531
 
                if e.errno == errno.EEXIST:
1532
 
                    raise errors.ExistingPendingDeletion(deletiondir)
1533
 
        except:
1534
 
            tree.unlock()
1535
 
            raise
1536
 
 
1537
 
        # Cache of realpath results, to speed up canonical_path
1538
 
        self._realpaths = {}
1539
 
        # Cache of relpath results, to speed up canonical_path
1540
 
        self._relpaths = {}
1541
 
        DiskTreeTransform.__init__(self, tree, limbodir, pb,
1542
 
                                   tree.case_sensitive)
1543
 
        self._deletiondir = deletiondir
1544
 
 
1545
 
    def canonical_path(self, path):
1546
 
        """Get the canonical tree-relative path"""
1547
 
        # don't follow final symlinks
1548
 
        abs = self._tree.abspath(path)
1549
 
        if abs in self._relpaths:
1550
 
            return self._relpaths[abs]
1551
 
        dirname, basename = os.path.split(abs)
1552
 
        if dirname not in self._realpaths:
1553
 
            self._realpaths[dirname] = os.path.realpath(dirname)
1554
 
        dirname = self._realpaths[dirname]
1555
 
        abs = pathjoin(dirname, basename)
1556
 
        if dirname in self._relpaths:
1557
 
            relpath = pathjoin(self._relpaths[dirname], basename)
1558
 
            relpath = relpath.rstrip('/\\')
1559
 
        else:
1560
 
            relpath = self._tree.relpath(abs)
1561
 
        self._relpaths[abs] = relpath
1562
 
        return relpath
1563
 
 
1564
 
    def tree_kind(self, trans_id):
1565
 
        """Determine the file kind in the working tree.
1566
 
 
1567
 
        :returns: The file kind or None if the file does not exist
1568
 
        """
1569
 
        path = self._tree_id_paths.get(trans_id)
1570
 
        if path is None:
1571
 
            return None
1572
 
        try:
1573
 
            return file_kind(self._tree.abspath(path))
1574
 
        except errors.NoSuchFile:
1575
 
            return None
1576
 
 
1577
 
    def _set_mode(self, trans_id, mode_id, typefunc):
1578
 
        """Set the mode of new file contents.
1579
 
        The mode_id is the existing file to get the mode from (often the same
1580
 
        as trans_id).  The operation is only performed if there's a mode match
1581
 
        according to typefunc.
1582
 
        """
1583
 
        if mode_id is None:
1584
 
            mode_id = trans_id
1585
 
        try:
1586
 
            old_path = self._tree_id_paths[mode_id]
1587
 
        except KeyError:
1588
 
            return
1589
 
        try:
1590
 
            mode = os.stat(self._tree.abspath(old_path)).st_mode
1591
 
        except OSError, e:
1592
 
            if e.errno in (errno.ENOENT, errno.ENOTDIR):
1593
 
                # Either old_path doesn't exist, or the parent of the
1594
 
                # target is not a directory (but will be one eventually)
1595
 
                # Either way, we know it doesn't exist *right now*
1596
 
                # See also bug #248448
1597
 
                return
1598
 
            else:
1599
 
                raise
1600
 
        if typefunc(mode):
1601
 
            os.chmod(self._limbo_name(trans_id), mode)
1602
 
 
1603
 
    def iter_tree_children(self, parent_id):
1604
 
        """Iterate through the entry's tree children, if any"""
1605
 
        try:
1606
 
            path = self._tree_id_paths[parent_id]
1607
 
        except KeyError:
1608
 
            return
1609
 
        try:
1610
 
            children = os.listdir(self._tree.abspath(path))
1611
 
        except OSError, e:
1612
 
            if not (osutils._is_error_enotdir(e)
1613
 
                    or e.errno in (errno.ENOENT, errno.ESRCH)):
1614
 
                raise
1615
 
            return
1616
 
 
1617
 
        for child in children:
1618
 
            childpath = joinpath(path, child)
1619
 
            if self._tree.is_control_filename(childpath):
1620
 
                continue
1621
 
            yield self.trans_id_tree_path(childpath)
1622
 
 
1623
 
    def _generate_limbo_path(self, trans_id):
1624
 
        """Generate a limbo path using the final path if possible.
1625
 
 
1626
 
        This optimizes the performance of applying the tree transform by
1627
 
        avoiding renames.  These renames can be avoided only when the parent
1628
 
        directory is already scheduled for creation.
1629
 
 
1630
 
        If the final path cannot be used, falls back to using the trans_id as
1631
 
        the relpath.
1632
 
        """
1633
 
        parent = self._new_parent.get(trans_id)
1634
 
        # if the parent directory is already in limbo (e.g. when building a
1635
 
        # tree), choose a limbo name inside the parent, to reduce further
1636
 
        # renames.
1637
 
        use_direct_path = False
1638
 
        if self._new_contents.get(parent) == 'directory':
1639
 
            filename = self._new_name.get(trans_id)
1640
 
            if filename is not None:
1641
 
                if parent not in self._limbo_children:
1642
 
                    self._limbo_children[parent] = set()
1643
 
                    self._limbo_children_names[parent] = {}
1644
 
                    use_direct_path = True
1645
 
                # the direct path can only be used if no other file has
1646
 
                # already taken this pathname, i.e. if the name is unused, or
1647
 
                # if it is already associated with this trans_id.
1648
 
                elif self._case_sensitive_target:
1649
 
                    if (self._limbo_children_names[parent].get(filename)
1650
 
                        in (trans_id, None)):
1651
 
                        use_direct_path = True
1652
 
                else:
1653
 
                    for l_filename, l_trans_id in\
1654
 
                        self._limbo_children_names[parent].iteritems():
1655
 
                        if l_trans_id == trans_id:
1656
 
                            continue
1657
 
                        if l_filename.lower() == filename.lower():
1658
 
                            break
1659
 
                    else:
1660
 
                        use_direct_path = True
1661
 
 
1662
 
        if not use_direct_path:
1663
 
            return DiskTreeTransform._generate_limbo_path(self, trans_id)
1664
 
 
1665
 
        limbo_name = pathjoin(self._limbo_files[parent], filename)
1666
 
        self._limbo_children[parent].add(trans_id)
1667
 
        self._limbo_children_names[parent][filename] = trans_id
1668
 
        return limbo_name
1669
 
 
1670
 
 
1671
 
    def apply(self, no_conflicts=False, precomputed_delta=None, _mover=None):
1672
 
        """Apply all changes to the inventory and filesystem.
1673
 
 
1674
 
        If filesystem or inventory conflicts are present, MalformedTransform
1675
 
        will be thrown.
1676
 
 
1677
 
        If apply succeeds, finalize is not necessary.
1678
 
 
1679
 
        :param no_conflicts: if True, the caller guarantees there are no
1680
 
            conflicts, so no check is made.
1681
 
        :param precomputed_delta: An inventory delta to use instead of
1682
 
            calculating one.
1683
 
        :param _mover: Supply an alternate FileMover, for testing
1684
 
        """
1685
 
        if not no_conflicts:
1686
 
            self._check_malformed()
1687
 
        child_pb = ui.ui_factory.nested_progress_bar()
1688
 
        try:
1689
 
            if precomputed_delta is None:
1690
 
                child_pb.update('Apply phase', 0, 2)
1691
 
                inventory_delta = self._generate_inventory_delta()
1692
 
                offset = 1
1693
 
            else:
1694
 
                inventory_delta = precomputed_delta
1695
 
                offset = 0
1696
 
            if _mover is None:
1697
 
                mover = _FileMover()
1698
 
            else:
1699
 
                mover = _mover
1700
 
            try:
1701
 
                child_pb.update('Apply phase', 0 + offset, 2 + offset)
1702
 
                self._apply_removals(mover)
1703
 
                child_pb.update('Apply phase', 1 + offset, 2 + offset)
1704
 
                modified_paths = self._apply_insertions(mover)
1705
 
            except:
1706
 
                mover.rollback()
1707
 
                raise
1708
 
            else:
1709
 
                mover.apply_deletions()
1710
 
        finally:
1711
 
            child_pb.finished()
1712
 
        self._tree.apply_inventory_delta(inventory_delta)
1713
 
        self._apply_observed_sha1s()
1714
 
        self._done = True
1715
 
        self.finalize()
1716
 
        return _TransformResults(modified_paths, self.rename_count)
1717
 
 
1718
 
    def _generate_inventory_delta(self):
1719
 
        """Generate an inventory delta for the current transform."""
1720
 
        inventory_delta = []
1721
 
        child_pb = ui.ui_factory.nested_progress_bar()
1722
 
        new_paths = self._inventory_altered()
1723
 
        total_entries = len(new_paths) + len(self._removed_id)
1724
 
        try:
1725
 
            for num, trans_id in enumerate(self._removed_id):
1726
 
                if (num % 10) == 0:
1727
 
                    child_pb.update('removing file', num, total_entries)
1728
 
                if trans_id == self._new_root:
1729
 
                    file_id = self._tree.get_root_id()
1730
 
                else:
1731
 
                    file_id = self.tree_file_id(trans_id)
1732
 
                # File-id isn't really being deleted, just moved
1733
 
                if file_id in self._r_new_id:
1734
 
                    continue
1735
 
                path = self._tree_id_paths[trans_id]
1736
 
                inventory_delta.append((path, None, file_id, None))
1737
 
            new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1738
 
                                     new_paths)
1739
 
            entries = self._tree.iter_entries_by_dir(
1740
 
                new_path_file_ids.values())
1741
 
            old_paths = dict((e.file_id, p) for p, e in entries)
1742
 
            final_kinds = {}
1743
 
            for num, (path, trans_id) in enumerate(new_paths):
1744
 
                if (num % 10) == 0:
1745
 
                    child_pb.update('adding file',
1746
 
                                    num + len(self._removed_id), total_entries)
1747
 
                file_id = new_path_file_ids[trans_id]
1748
 
                if file_id is None:
1749
 
                    continue
1750
 
                needs_entry = False
1751
 
                kind = self.final_kind(trans_id)
1752
 
                if kind is None:
1753
 
                    kind = self._tree.stored_kind(file_id)
1754
 
                parent_trans_id = self.final_parent(trans_id)
1755
 
                parent_file_id = new_path_file_ids.get(parent_trans_id)
1756
 
                if parent_file_id is None:
1757
 
                    parent_file_id = self.final_file_id(parent_trans_id)
1758
 
                if trans_id in self._new_reference_revision:
1759
 
                    new_entry = inventory.TreeReference(
1760
 
                        file_id,
1761
 
                        self._new_name[trans_id],
1762
 
                        self.final_file_id(self._new_parent[trans_id]),
1763
 
                        None, self._new_reference_revision[trans_id])
1764
 
                else:
1765
 
                    new_entry = inventory.make_entry(kind,
1766
 
                        self.final_name(trans_id),
1767
 
                        parent_file_id, file_id)
1768
 
                old_path = old_paths.get(new_entry.file_id)
1769
 
                new_executability = self._new_executability.get(trans_id)
1770
 
                if new_executability is not None:
1771
 
                    new_entry.executable = new_executability
1772
 
                inventory_delta.append(
1773
 
                    (old_path, path, new_entry.file_id, new_entry))
1774
 
        finally:
1775
 
            child_pb.finished()
1776
 
        return inventory_delta
1777
 
 
1778
 
    def _apply_removals(self, mover):
1779
 
        """Perform tree operations that remove directory/inventory names.
1780
 
 
1781
 
        That is, delete files that are to be deleted, and put any files that
1782
 
        need renaming into limbo.  This must be done in strict child-to-parent
1783
 
        order.
1784
 
 
1785
 
        If inventory_delta is None, no inventory delta generation is performed.
1786
 
        """
1787
 
        tree_paths = list(self._tree_path_ids.iteritems())
1788
 
        tree_paths.sort(reverse=True)
1789
 
        child_pb = ui.ui_factory.nested_progress_bar()
1790
 
        try:
1791
 
            for num, data in enumerate(tree_paths):
1792
 
                path, trans_id = data
1793
 
                child_pb.update('removing file', num, len(tree_paths))
1794
 
                full_path = self._tree.abspath(path)
1795
 
                if trans_id in self._removed_contents:
1796
 
                    delete_path = os.path.join(self._deletiondir, trans_id)
1797
 
                    mover.pre_delete(full_path, delete_path)
1798
 
                elif (trans_id in self._new_name
1799
 
                      or trans_id in self._new_parent):
1800
 
                    try:
1801
 
                        mover.rename(full_path, self._limbo_name(trans_id))
1802
 
                    except errors.TransformRenameFailed, e:
1803
 
                        if e.errno != errno.ENOENT:
1804
 
                            raise
1805
 
                    else:
1806
 
                        self.rename_count += 1
1807
 
        finally:
1808
 
            child_pb.finished()
1809
 
 
1810
 
    def _apply_insertions(self, mover):
1811
 
        """Perform tree operations that insert directory/inventory names.
1812
 
 
1813
 
        That is, create any files that need to be created, and restore from
1814
 
        limbo any files that needed renaming.  This must be done in strict
1815
 
        parent-to-child order.
1816
 
 
1817
 
        If inventory_delta is None, no inventory delta is calculated, and
1818
 
        no list of modified paths is returned.
1819
 
        """
1820
 
        new_paths = self.new_paths(filesystem_only=True)
1821
 
        modified_paths = []
1822
 
        new_path_file_ids = dict((t, self.final_file_id(t)) for p, t in
1823
 
                                 new_paths)
1824
 
        child_pb = ui.ui_factory.nested_progress_bar()
1825
 
        try:
1826
 
            for num, (path, trans_id) in enumerate(new_paths):
1827
 
                if (num % 10) == 0:
1828
 
                    child_pb.update('adding file', num, len(new_paths))
1829
 
                full_path = self._tree.abspath(path)
1830
 
                if trans_id in self._needs_rename:
1831
 
                    try:
1832
 
                        mover.rename(self._limbo_name(trans_id), full_path)
1833
 
                    except errors.TransformRenameFailed, e:
1834
 
                        # We may be renaming a dangling inventory id
1835
 
                        if e.errno != errno.ENOENT:
1836
 
                            raise
1837
 
                    else:
1838
 
                        self.rename_count += 1
1839
 
                    # TODO: if trans_id in self._observed_sha1s, we should
1840
 
                    #       re-stat the final target, since ctime will be
1841
 
                    #       updated by the change.
1842
 
                if (trans_id in self._new_contents or
1843
 
                    self.path_changed(trans_id)):
1844
 
                    if trans_id in self._new_contents:
1845
 
                        modified_paths.append(full_path)
1846
 
                if trans_id in self._new_executability:
1847
 
                    self._set_executability(path, trans_id)
1848
 
                if trans_id in self._observed_sha1s:
1849
 
                    o_sha1, o_st_val = self._observed_sha1s[trans_id]
1850
 
                    st = osutils.lstat(full_path)
1851
 
                    self._observed_sha1s[trans_id] = (o_sha1, st)
1852
 
        finally:
1853
 
            child_pb.finished()
1854
 
        self._new_contents.clear()
1855
 
        return modified_paths
1856
 
 
1857
 
    def _apply_observed_sha1s(self):
1858
 
        """After we have finished renaming everything, update observed sha1s
1859
 
 
1860
 
        This has to be done after self._tree.apply_inventory_delta, otherwise
1861
 
        it doesn't know anything about the files we are updating. Also, we want
1862
 
        to do this as late as possible, so that most entries end up cached.
1863
 
        """
1864
 
        # TODO: this doesn't update the stat information for directories. So
1865
 
        #       the first 'bzr status' will still need to rewrite
1866
 
        #       .bzr/checkout/dirstate. However, we at least don't need to
1867
 
        #       re-read all of the files.
1868
 
        # TODO: If the operation took a while, we could do a time.sleep(3) here
1869
 
        #       to allow the clock to tick over and ensure we won't have any
1870
 
        #       problems. (we could observe start time, and finish time, and if
1871
 
        #       it is less than eg 10% overhead, add a sleep call.)
1872
 
        paths = FinalPaths(self)
1873
 
        for trans_id, observed in self._observed_sha1s.iteritems():
1874
 
            path = paths.get_path(trans_id)
1875
 
            # We could get the file_id, but dirstate prefers to use the path
1876
 
            # anyway, and it is 'cheaper' to determine.
1877
 
            # file_id = self._new_id[trans_id]
1878
 
            self._tree._observed_sha1(None, path, observed)
1879
 
 
1880
 
 
1881
 
class TransformPreview(DiskTreeTransform):
1882
 
    """A TreeTransform for generating preview trees.
1883
 
 
1884
 
    Unlike TreeTransform, this version works when the input tree is a
1885
 
    RevisionTree, rather than a WorkingTree.  As a result, it tends to ignore
1886
 
    unversioned files in the input tree.
1887
 
    """
1888
 
 
1889
 
    def __init__(self, tree, pb=None, case_sensitive=True):
1890
 
        tree.lock_read()
1891
 
        limbodir = osutils.mkdtemp(prefix='bzr-limbo-')
1892
 
        DiskTreeTransform.__init__(self, tree, limbodir, pb, case_sensitive)
1893
 
 
1894
 
    def canonical_path(self, path):
1895
 
        return path
1896
 
 
1897
 
    def tree_kind(self, trans_id):
1898
 
        path = self._tree_id_paths.get(trans_id)
1899
 
        if path is None:
1900
 
            return None
1901
 
        file_id = self._tree.path2id(path)
1902
 
        try:
1903
 
            return self._tree.kind(file_id)
1904
 
        except errors.NoSuchFile:
1905
 
            return None
1906
 
 
1907
 
    def _set_mode(self, trans_id, mode_id, typefunc):
1908
 
        """Set the mode of new file contents.
1909
 
        The mode_id is the existing file to get the mode from (often the same
1910
 
        as trans_id).  The operation is only performed if there's a mode match
1911
 
        according to typefunc.
1912
 
        """
1913
 
        # is it ok to ignore this?  probably
1914
 
        pass
1915
 
 
1916
 
    def iter_tree_children(self, parent_id):
1917
 
        """Iterate through the entry's tree children, if any"""
1918
 
        try:
1919
 
            path = self._tree_id_paths[parent_id]
1920
 
        except KeyError:
1921
 
            return
1922
 
        file_id = self.tree_file_id(parent_id)
1923
 
        if file_id is None:
1924
 
            return
1925
 
        entry = self._tree.iter_entries_by_dir([file_id]).next()[1]
1926
 
        children = getattr(entry, 'children', {})
1927
 
        for child in children:
1928
 
            childpath = joinpath(path, child)
1929
 
            yield self.trans_id_tree_path(childpath)
1930
 
 
1931
 
    def new_orphan(self, trans_id, parent_id):
1932
 
        raise NotImplementedError(self.new_orphan)
1933
 
 
1934
 
 
1935
 
class _PreviewTree(tree.InventoryTree):
1936
 
    """Partial implementation of Tree to support show_diff_trees"""
1937
 
 
1938
 
    def __init__(self, transform):
1939
 
        self._transform = transform
1940
 
        self._final_paths = FinalPaths(transform)
1941
 
        self.__by_parent = None
1942
 
        self._parent_ids = []
1943
 
        self._all_children_cache = {}
1944
 
        self._path2trans_id_cache = {}
1945
 
        self._final_name_cache = {}
1946
 
        self._iter_changes_cache = dict((c[0], c) for c in
1947
 
                                        self._transform.iter_changes())
1948
 
 
1949
 
    def _content_change(self, file_id):
1950
 
        """Return True if the content of this file changed"""
1951
 
        changes = self._iter_changes_cache.get(file_id)
1952
 
        # changes[2] is true if the file content changed.  See
1953
 
        # InterTree.iter_changes.
1954
 
        return (changes is not None and changes[2])
1955
 
 
1956
 
    def _get_repository(self):
1957
 
        repo = getattr(self._transform._tree, '_repository', None)
1958
 
        if repo is None:
1959
 
            repo = self._transform._tree.branch.repository
1960
 
        return repo
1961
 
 
1962
 
    def _iter_parent_trees(self):
1963
 
        for revision_id in self.get_parent_ids():
1964
 
            try:
1965
 
                yield self.revision_tree(revision_id)
1966
 
            except errors.NoSuchRevisionInTree:
1967
 
                yield self._get_repository().revision_tree(revision_id)
1968
 
 
1969
 
    def _get_file_revision(self, file_id, vf, tree_revision):
1970
 
        parent_keys = [(file_id, t.get_file_revision(file_id)) for t in
1971
 
                       self._iter_parent_trees()]
1972
 
        vf.add_lines((file_id, tree_revision), parent_keys,
1973
 
                     self.get_file_lines(file_id))
1974
 
        repo = self._get_repository()
1975
 
        base_vf = repo.texts
1976
 
        if base_vf not in vf.fallback_versionedfiles:
1977
 
            vf.fallback_versionedfiles.append(base_vf)
1978
 
        return tree_revision
1979
 
 
1980
 
    def _stat_limbo_file(self, file_id):
1981
 
        trans_id = self._transform.trans_id_file_id(file_id)
1982
 
        name = self._transform._limbo_name(trans_id)
1983
 
        return os.lstat(name)
1984
 
 
1985
 
    @property
1986
 
    def _by_parent(self):
1987
 
        if self.__by_parent is None:
1988
 
            self.__by_parent = self._transform.by_parent()
1989
 
        return self.__by_parent
1990
 
 
1991
 
    def _comparison_data(self, entry, path):
1992
 
        kind, size, executable, link_or_sha1 = self.path_content_summary(path)
1993
 
        if kind == 'missing':
1994
 
            kind = None
1995
 
            executable = False
1996
 
        else:
1997
 
            file_id = self._transform.final_file_id(self._path2trans_id(path))
1998
 
            executable = self.is_executable(file_id, path)
1999
 
        return kind, executable, None
2000
 
 
2001
 
    def is_locked(self):
2002
 
        return False
2003
 
 
2004
 
    def lock_read(self):
2005
 
        # Perhaps in theory, this should lock the TreeTransform?
2006
 
        return self
2007
 
 
2008
 
    def unlock(self):
2009
 
        pass
2010
 
 
2011
 
    @property
2012
 
    def inventory(self):
2013
 
        """This Tree does not use inventory as its backing data."""
2014
 
        raise NotImplementedError(_PreviewTree.inventory)
2015
 
 
2016
 
    def get_root_id(self):
2017
 
        return self._transform.final_file_id(self._transform.root)
2018
 
 
2019
 
    def all_file_ids(self):
2020
 
        tree_ids = set(self._transform._tree.all_file_ids())
2021
 
        tree_ids.difference_update(self._transform.tree_file_id(t)
2022
 
                                   for t in self._transform._removed_id)
2023
 
        tree_ids.update(self._transform._new_id.values())
2024
 
        return tree_ids
2025
 
 
2026
 
    def __iter__(self):
2027
 
        return iter(self.all_file_ids())
2028
 
 
2029
 
    def _has_id(self, file_id, fallback_check):
2030
 
        if file_id in self._transform._r_new_id:
2031
 
            return True
2032
 
        elif file_id in set([self._transform.tree_file_id(trans_id) for
2033
 
            trans_id in self._transform._removed_id]):
2034
 
            return False
2035
 
        else:
2036
 
            return fallback_check(file_id)
2037
 
 
2038
 
    def has_id(self, file_id):
2039
 
        return self._has_id(file_id, self._transform._tree.has_id)
2040
 
 
2041
 
    def has_or_had_id(self, file_id):
2042
 
        return self._has_id(file_id, self._transform._tree.has_or_had_id)
2043
 
 
2044
 
    def _path2trans_id(self, path):
2045
 
        # We must not use None here, because that is a valid value to store.
2046
 
        trans_id = self._path2trans_id_cache.get(path, object)
2047
 
        if trans_id is not object:
2048
 
            return trans_id
2049
 
        segments = splitpath(path)
2050
 
        cur_parent = self._transform.root
2051
 
        for cur_segment in segments:
2052
 
            for child in self._all_children(cur_parent):
2053
 
                final_name = self._final_name_cache.get(child)
2054
 
                if final_name is None:
2055
 
                    final_name = self._transform.final_name(child)
2056
 
                    self._final_name_cache[child] = final_name
2057
 
                if final_name == cur_segment:
2058
 
                    cur_parent = child
2059
 
                    break
2060
 
            else:
2061
 
                self._path2trans_id_cache[path] = None
2062
 
                return None
2063
 
        self._path2trans_id_cache[path] = cur_parent
2064
 
        return cur_parent
2065
 
 
2066
 
    def path2id(self, path):
2067
 
        return self._transform.final_file_id(self._path2trans_id(path))
2068
 
 
2069
 
    def id2path(self, file_id):
2070
 
        trans_id = self._transform.trans_id_file_id(file_id)
2071
 
        try:
2072
 
            return self._final_paths._determine_path(trans_id)
2073
 
        except NoFinalPath:
2074
 
            raise errors.NoSuchId(self, file_id)
2075
 
 
2076
 
    def _all_children(self, trans_id):
2077
 
        children = self._all_children_cache.get(trans_id)
2078
 
        if children is not None:
2079
 
            return children
2080
 
        children = set(self._transform.iter_tree_children(trans_id))
2081
 
        # children in the _new_parent set are provided by _by_parent.
2082
 
        children.difference_update(self._transform._new_parent.keys())
2083
 
        children.update(self._by_parent.get(trans_id, []))
2084
 
        self._all_children_cache[trans_id] = children
2085
 
        return children
2086
 
 
2087
 
    def iter_children(self, file_id):
2088
 
        trans_id = self._transform.trans_id_file_id(file_id)
2089
 
        for child_trans_id in self._all_children(trans_id):
2090
 
            yield self._transform.final_file_id(child_trans_id)
2091
 
 
2092
 
    def extras(self):
2093
 
        possible_extras = set(self._transform.trans_id_tree_path(p) for p
2094
 
                              in self._transform._tree.extras())
2095
 
        possible_extras.update(self._transform._new_contents)
2096
 
        possible_extras.update(self._transform._removed_id)
2097
 
        for trans_id in possible_extras:
2098
 
            if self._transform.final_file_id(trans_id) is None:
2099
 
                yield self._final_paths._determine_path(trans_id)
2100
 
 
2101
 
    def _make_inv_entries(self, ordered_entries, specific_file_ids=None,
2102
 
        yield_parents=False):
2103
 
        for trans_id, parent_file_id in ordered_entries:
2104
 
            file_id = self._transform.final_file_id(trans_id)
2105
 
            if file_id is None:
2106
 
                continue
2107
 
            if (specific_file_ids is not None
2108
 
                and file_id not in specific_file_ids):
2109
 
                continue
2110
 
            kind = self._transform.final_kind(trans_id)
2111
 
            if kind is None:
2112
 
                kind = self._transform._tree.stored_kind(file_id)
2113
 
            new_entry = inventory.make_entry(
2114
 
                kind,
2115
 
                self._transform.final_name(trans_id),
2116
 
                parent_file_id, file_id)
2117
 
            yield new_entry, trans_id
2118
 
 
2119
 
    def _list_files_by_dir(self):
2120
 
        todo = [ROOT_PARENT]
2121
 
        ordered_ids = []
2122
 
        while len(todo) > 0:
2123
 
            parent = todo.pop()
2124
 
            parent_file_id = self._transform.final_file_id(parent)
2125
 
            children = list(self._all_children(parent))
2126
 
            paths = dict(zip(children, self._final_paths.get_paths(children)))
2127
 
            children.sort(key=paths.get)
2128
 
            todo.extend(reversed(children))
2129
 
            for trans_id in children:
2130
 
                ordered_ids.append((trans_id, parent_file_id))
2131
 
        return ordered_ids
2132
 
 
2133
 
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
2134
 
        # This may not be a maximally efficient implementation, but it is
2135
 
        # reasonably straightforward.  An implementation that grafts the
2136
 
        # TreeTransform changes onto the tree's iter_entries_by_dir results
2137
 
        # might be more efficient, but requires tricky inferences about stack
2138
 
        # position.
2139
 
        ordered_ids = self._list_files_by_dir()
2140
 
        for entry, trans_id in self._make_inv_entries(ordered_ids,
2141
 
            specific_file_ids, yield_parents=yield_parents):
2142
 
            yield unicode(self._final_paths.get_path(trans_id)), entry
2143
 
 
2144
 
    def _iter_entries_for_dir(self, dir_path):
2145
 
        """Return path, entry for items in a directory without recursing down."""
2146
 
        dir_file_id = self.path2id(dir_path)
2147
 
        ordered_ids = []
2148
 
        for file_id in self.iter_children(dir_file_id):
2149
 
            trans_id = self._transform.trans_id_file_id(file_id)
2150
 
            ordered_ids.append((trans_id, file_id))
2151
 
        for entry, trans_id in self._make_inv_entries(ordered_ids):
2152
 
            yield unicode(self._final_paths.get_path(trans_id)), entry
2153
 
 
2154
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
2155
 
        """See WorkingTree.list_files."""
2156
 
        # XXX This should behave like WorkingTree.list_files, but is really
2157
 
        # more like RevisionTree.list_files.
2158
 
        if recursive:
2159
 
            prefix = None
2160
 
            if from_dir:
2161
 
                prefix = from_dir + '/'
2162
 
            entries = self.iter_entries_by_dir()
2163
 
            for path, entry in entries:
2164
 
                if entry.name == '' and not include_root:
2165
 
                    continue
2166
 
                if prefix:
2167
 
                    if not path.startswith(prefix):
2168
 
                        continue
2169
 
                    path = path[len(prefix):]
2170
 
                yield path, 'V', entry.kind, entry.file_id, entry
2171
 
        else:
2172
 
            if from_dir is None and include_root is True:
2173
 
                root_entry = inventory.make_entry('directory', '',
2174
 
                    ROOT_PARENT, self.get_root_id())
2175
 
                yield '', 'V', 'directory', root_entry.file_id, root_entry
2176
 
            entries = self._iter_entries_for_dir(from_dir or '')
2177
 
            for path, entry in entries:
2178
 
                yield path, 'V', entry.kind, entry.file_id, entry
2179
 
 
2180
 
    def kind(self, file_id):
2181
 
        trans_id = self._transform.trans_id_file_id(file_id)
2182
 
        return self._transform.final_kind(trans_id)
2183
 
 
2184
 
    def stored_kind(self, file_id):
2185
 
        trans_id = self._transform.trans_id_file_id(file_id)
2186
 
        try:
2187
 
            return self._transform._new_contents[trans_id]
2188
 
        except KeyError:
2189
 
            return self._transform._tree.stored_kind(file_id)
2190
 
 
2191
 
    def get_file_mtime(self, file_id, path=None):
2192
 
        """See Tree.get_file_mtime"""
2193
 
        if not self._content_change(file_id):
2194
 
            return self._transform._tree.get_file_mtime(file_id)
2195
 
        return self._stat_limbo_file(file_id).st_mtime
2196
 
 
2197
 
    def _file_size(self, entry, stat_value):
2198
 
        return self.get_file_size(entry.file_id)
2199
 
 
2200
 
    def get_file_size(self, file_id):
2201
 
        """See Tree.get_file_size"""
2202
 
        if self.kind(file_id) == 'file':
2203
 
            return self._transform._tree.get_file_size(file_id)
2204
 
        else:
2205
 
            return None
2206
 
 
2207
 
    def get_file_sha1(self, file_id, path=None, stat_value=None):
2208
 
        trans_id = self._transform.trans_id_file_id(file_id)
2209
 
        kind = self._transform._new_contents.get(trans_id)
2210
 
        if kind is None:
2211
 
            return self._transform._tree.get_file_sha1(file_id)
2212
 
        if kind == 'file':
2213
 
            fileobj = self.get_file(file_id)
2214
 
            try:
2215
 
                return sha_file(fileobj)
2216
 
            finally:
2217
 
                fileobj.close()
2218
 
 
2219
 
    def is_executable(self, file_id, path=None):
2220
 
        if file_id is None:
2221
 
            return False
2222
 
        trans_id = self._transform.trans_id_file_id(file_id)
2223
 
        try:
2224
 
            return self._transform._new_executability[trans_id]
2225
 
        except KeyError:
2226
 
            try:
2227
 
                return self._transform._tree.is_executable(file_id, path)
2228
 
            except OSError, e:
2229
 
                if e.errno == errno.ENOENT:
2230
 
                    return False
2231
 
                raise
2232
 
            except errors.NoSuchId:
2233
 
                return False
2234
 
 
2235
 
    def path_content_summary(self, path):
2236
 
        trans_id = self._path2trans_id(path)
2237
 
        tt = self._transform
2238
 
        tree_path = tt._tree_id_paths.get(trans_id)
2239
 
        kind = tt._new_contents.get(trans_id)
2240
 
        if kind is None:
2241
 
            if tree_path is None or trans_id in tt._removed_contents:
2242
 
                return 'missing', None, None, None
2243
 
            summary = tt._tree.path_content_summary(tree_path)
2244
 
            kind, size, executable, link_or_sha1 = summary
2245
 
        else:
2246
 
            link_or_sha1 = None
2247
 
            limbo_name = tt._limbo_name(trans_id)
2248
 
            if trans_id in tt._new_reference_revision:
2249
 
                kind = 'tree-reference'
2250
 
            if kind == 'file':
2251
 
                statval = os.lstat(limbo_name)
2252
 
                size = statval.st_size
2253
 
                if not supports_executable():
2254
 
                    executable = False
2255
 
                else:
2256
 
                    executable = statval.st_mode & S_IEXEC
2257
 
            else:
2258
 
                size = None
2259
 
                executable = None
2260
 
            if kind == 'symlink':
2261
 
                link_or_sha1 = os.readlink(limbo_name).decode(osutils._fs_enc)
2262
 
        executable = tt._new_executability.get(trans_id, executable)
2263
 
        return kind, size, executable, link_or_sha1
2264
 
 
2265
 
    def iter_changes(self, from_tree, include_unchanged=False,
2266
 
                      specific_files=None, pb=None, extra_trees=None,
2267
 
                      require_versioned=True, want_unversioned=False):
2268
 
        """See InterTree.iter_changes.
2269
 
 
2270
 
        This has a fast path that is only used when the from_tree matches
2271
 
        the transform tree, and no fancy options are supplied.
2272
 
        """
2273
 
        if (from_tree is not self._transform._tree or include_unchanged or
2274
 
            specific_files or want_unversioned):
2275
 
            return tree.InterTree(from_tree, self).iter_changes(
2276
 
                include_unchanged=include_unchanged,
2277
 
                specific_files=specific_files,
2278
 
                pb=pb,
2279
 
                extra_trees=extra_trees,
2280
 
                require_versioned=require_versioned,
2281
 
                want_unversioned=want_unversioned)
2282
 
        if want_unversioned:
2283
 
            raise ValueError('want_unversioned is not supported')
2284
 
        return self._transform.iter_changes()
2285
 
 
2286
 
    def get_file(self, file_id, path=None):
2287
 
        """See Tree.get_file"""
2288
 
        if not self._content_change(file_id):
2289
 
            return self._transform._tree.get_file(file_id, path)
2290
 
        trans_id = self._transform.trans_id_file_id(file_id)
2291
 
        name = self._transform._limbo_name(trans_id)
2292
 
        return open(name, 'rb')
2293
 
 
2294
 
    def get_file_with_stat(self, file_id, path=None):
2295
 
        return self.get_file(file_id, path), None
2296
 
 
2297
 
    def annotate_iter(self, file_id,
2298
 
                      default_revision=_mod_revision.CURRENT_REVISION):
2299
 
        changes = self._iter_changes_cache.get(file_id)
2300
 
        if changes is None:
2301
 
            get_old = True
2302
 
        else:
2303
 
            changed_content, versioned, kind = (changes[2], changes[3],
2304
 
                                                changes[6])
2305
 
            if kind[1] is None:
2306
 
                return None
2307
 
            get_old = (kind[0] == 'file' and versioned[0])
2308
 
        if get_old:
2309
 
            old_annotation = self._transform._tree.annotate_iter(file_id,
2310
 
                default_revision=default_revision)
2311
 
        else:
2312
 
            old_annotation = []
2313
 
        if changes is None:
2314
 
            return old_annotation
2315
 
        if not changed_content:
2316
 
            return old_annotation
2317
 
        # TODO: This is doing something similar to what WT.annotate_iter is
2318
 
        #       doing, however it fails slightly because it doesn't know what
2319
 
        #       the *other* revision_id is, so it doesn't know how to give the
2320
 
        #       other as the origin for some lines, they all get
2321
 
        #       'default_revision'
2322
 
        #       It would be nice to be able to use the new Annotator based
2323
 
        #       approach, as well.
2324
 
        return annotate.reannotate([old_annotation],
2325
 
                                   self.get_file(file_id).readlines(),
2326
 
                                   default_revision)
2327
 
 
2328
 
    def get_symlink_target(self, file_id):
2329
 
        """See Tree.get_symlink_target"""
2330
 
        if not self._content_change(file_id):
2331
 
            return self._transform._tree.get_symlink_target(file_id)
2332
 
        trans_id = self._transform.trans_id_file_id(file_id)
2333
 
        name = self._transform._limbo_name(trans_id)
2334
 
        return osutils.readlink(name)
2335
 
 
2336
 
    def walkdirs(self, prefix=''):
2337
 
        pending = [self._transform.root]
2338
 
        while len(pending) > 0:
2339
 
            parent_id = pending.pop()
2340
 
            children = []
2341
 
            subdirs = []
2342
 
            prefix = prefix.rstrip('/')
2343
 
            parent_path = self._final_paths.get_path(parent_id)
2344
 
            parent_file_id = self._transform.final_file_id(parent_id)
2345
 
            for child_id in self._all_children(parent_id):
2346
 
                path_from_root = self._final_paths.get_path(child_id)
2347
 
                basename = self._transform.final_name(child_id)
2348
 
                file_id = self._transform.final_file_id(child_id)
2349
 
                kind  = self._transform.final_kind(child_id)
2350
 
                if kind is not None:
2351
 
                    versioned_kind = kind
2352
 
                else:
2353
 
                    kind = 'unknown'
2354
 
                    versioned_kind = self._transform._tree.stored_kind(file_id)
2355
 
                if versioned_kind == 'directory':
2356
 
                    subdirs.append(child_id)
2357
 
                children.append((path_from_root, basename, kind, None,
2358
 
                                 file_id, versioned_kind))
2359
 
            children.sort()
2360
 
            if parent_path.startswith(prefix):
2361
 
                yield (parent_path, parent_file_id), children
2362
 
            pending.extend(sorted(subdirs, key=self._final_paths.get_path,
2363
 
                                  reverse=True))
2364
 
 
2365
 
    def get_parent_ids(self):
2366
 
        return self._parent_ids
2367
 
 
2368
 
    def set_parent_ids(self, parent_ids):
2369
 
        self._parent_ids = parent_ids
2370
 
 
2371
 
    def get_revision_tree(self, revision_id):
2372
 
        return self._transform._tree.get_revision_tree(revision_id)
2373
 
 
2374
1204
 
2375
1205
def joinpath(parent, child):
2376
1206
    """Join tree-relative paths, handling the tree root specially"""
2392
1222
        self.transform = transform
2393
1223
 
2394
1224
    def _determine_path(self, trans_id):
2395
 
        if (trans_id == self.transform.root or trans_id == ROOT_PARENT):
 
1225
        if trans_id == self.transform.root:
2396
1226
            return ""
2397
1227
        name = self.transform.final_name(trans_id)
2398
1228
        parent_id = self.transform.final_parent(trans_id)
2407
1237
            self._known_paths[trans_id] = self._determine_path(trans_id)
2408
1238
        return self._known_paths[trans_id]
2409
1239
 
2410
 
    def get_paths(self, trans_ids):
2411
 
        return [(self.get_path(t), t) for t in trans_ids]
2412
 
 
2413
 
 
2414
 
 
2415
1240
def topology_sorted_ids(tree):
2416
1241
    """Determine the topological order of the ids in a tree"""
2417
1242
    file_ids = list(tree)
2419
1244
    return file_ids
2420
1245
 
2421
1246
 
2422
 
def build_tree(tree, wt, accelerator_tree=None, hardlink=False,
2423
 
               delta_from_tree=False):
 
1247
def build_tree(tree, wt):
2424
1248
    """Create working tree for a branch, using a TreeTransform.
2425
 
 
 
1249
    
2426
1250
    This function should be used on empty trees, having a tree root at most.
2427
1251
    (see merge and revert functionality for working with existing trees)
2428
1252
 
2429
1253
    Existing files are handled like so:
2430
 
 
 
1254
    
2431
1255
    - Existing bzrdirs take precedence over creating new items.  They are
2432
1256
      created as '%s.diverted' % name.
2433
1257
    - Otherwise, if the content on disk matches the content we are building,
2434
1258
      it is silently replaced.
2435
1259
    - Otherwise, conflict resolution will move the old file to 'oldname.moved'.
2436
 
 
2437
 
    :param tree: The tree to convert wt into a copy of
2438
 
    :param wt: The working tree that files will be placed into
2439
 
    :param accelerator_tree: A tree which can be used for retrieving file
2440
 
        contents more quickly than tree itself, i.e. a workingtree.  tree
2441
 
        will be used for cases where accelerator_tree's content is different.
2442
 
    :param hardlink: If true, hard-link files to accelerator_tree, where
2443
 
        possible.  accelerator_tree must implement abspath, i.e. be a
2444
 
        working tree.
2445
 
    :param delta_from_tree: If true, build_tree may use the input Tree to
2446
 
        generate the inventory delta.
2447
1260
    """
2448
1261
    wt.lock_tree_write()
2449
1262
    try:
2450
1263
        tree.lock_read()
2451
1264
        try:
2452
 
            if accelerator_tree is not None:
2453
 
                accelerator_tree.lock_read()
2454
 
            try:
2455
 
                return _build_tree(tree, wt, accelerator_tree, hardlink,
2456
 
                                   delta_from_tree)
2457
 
            finally:
2458
 
                if accelerator_tree is not None:
2459
 
                    accelerator_tree.unlock()
 
1265
            return _build_tree(tree, wt)
2460
1266
        finally:
2461
1267
            tree.unlock()
2462
1268
    finally:
2463
1269
        wt.unlock()
2464
1270
 
2465
 
 
2466
 
def _build_tree(tree, wt, accelerator_tree, hardlink, delta_from_tree):
 
1271
def _build_tree(tree, wt):
2467
1272
    """See build_tree."""
2468
 
    for num, _unused in enumerate(wt.all_file_ids()):
2469
 
        if num > 0:  # more than just a root
2470
 
            raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
 
1273
    if len(wt.inventory) > 1:  # more than just a root
 
1274
        raise errors.WorkingTreeAlreadyPopulated(base=wt.basedir)
2471
1275
    file_trans_id = {}
2472
 
    top_pb = ui.ui_factory.nested_progress_bar()
 
1276
    top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
2473
1277
    pp = ProgressPhase("Build phase", 2, top_pb)
2474
1278
    if tree.inventory.root is not None:
2475
1279
        # This is kind of a hack: we should be altering the root
2479
1283
        # is set within the tree, nor setting the root and thus
2480
1284
        # marking the tree as dirty, because we use two different
2481
1285
        # idioms here: tree interfaces and inventory interfaces.
2482
 
        if wt.get_root_id() != tree.get_root_id():
2483
 
            wt.set_root_id(tree.get_root_id())
 
1286
        if wt.path2id('') != tree.inventory.root.file_id:
 
1287
            wt.set_root_id(tree.inventory.root.file_id)
2484
1288
            wt.flush()
2485
1289
    tt = TreeTransform(wt)
2486
1290
    divert = set()
2488
1292
        pp.next_phase()
2489
1293
        file_trans_id[wt.get_root_id()] = \
2490
1294
            tt.trans_id_tree_file_id(wt.get_root_id())
2491
 
        pb = ui.ui_factory.nested_progress_bar()
 
1295
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
2492
1296
        try:
2493
1297
            deferred_contents = []
2494
 
            num = 0
2495
 
            total = len(tree.inventory)
2496
 
            if delta_from_tree:
2497
 
                precomputed_delta = []
2498
 
            else:
2499
 
                precomputed_delta = None
2500
 
            # Check if tree inventory has content. If so, we populate
2501
 
            # existing_files with the directory content. If there are no
2502
 
            # entries we skip populating existing_files as its not used.
2503
 
            # This improves performance and unncessary work on large
2504
 
            # directory trees. (#501307)
2505
 
            if total > 0:
2506
 
                existing_files = set()
2507
 
                for dir, files in wt.walkdirs():
2508
 
                    existing_files.update(f[0] for f in files)
2509
1298
            for num, (tree_path, entry) in \
2510
1299
                enumerate(tree.inventory.iter_entries_by_dir()):
2511
 
                pb.update("Building tree", num - len(deferred_contents), total)
 
1300
                pb.update("Building tree", num - len(deferred_contents),
 
1301
                          len(tree.inventory))
2512
1302
                if entry.parent_id is None:
2513
1303
                    continue
2514
1304
                reparent = False
2515
1305
                file_id = entry.file_id
2516
 
                if delta_from_tree:
2517
 
                    precomputed_delta.append((None, tree_path, file_id, entry))
2518
 
                if tree_path in existing_files:
2519
 
                    target_path = wt.abspath(tree_path)
 
1306
                target_path = wt.abspath(tree_path)
 
1307
                try:
2520
1308
                    kind = file_kind(target_path)
 
1309
                except NoSuchFile:
 
1310
                    pass
 
1311
                else:
2521
1312
                    if kind == "directory":
2522
1313
                        try:
2523
1314
                            bzrdir.BzrDir.open(target_path)
2531
1322
                        tt.delete_contents(tt.trans_id_tree_path(tree_path))
2532
1323
                        if kind == 'directory':
2533
1324
                            reparent = True
 
1325
                if entry.parent_id not in file_trans_id:
 
1326
                    raise AssertionError(
 
1327
                        'entry %s parent id %r is not in file_trans_id %r'
 
1328
                        % (entry, entry.parent_id, file_trans_id))
2534
1329
                parent_id = file_trans_id[entry.parent_id]
2535
1330
                if entry.kind == 'file':
2536
1331
                    # We *almost* replicate new_by_entry, so that we can defer
2537
1332
                    # getting the file text, and get them all at once.
2538
1333
                    trans_id = tt.create_path(entry.name, parent_id)
2539
1334
                    file_trans_id[file_id] = trans_id
2540
 
                    tt.version_file(file_id, trans_id)
2541
 
                    executable = tree.is_executable(file_id, tree_path)
2542
 
                    if executable:
 
1335
                    tt.version_file(entry.file_id, trans_id)
 
1336
                    executable = tree.is_executable(entry.file_id, tree_path)
 
1337
                    if executable is not None:
2543
1338
                        tt.set_executability(executable, trans_id)
2544
 
                    trans_data = (trans_id, tree_path, entry.text_sha1)
2545
 
                    deferred_contents.append((file_id, trans_data))
 
1339
                    deferred_contents.append((entry.file_id, trans_id))
2546
1340
                else:
2547
1341
                    file_trans_id[file_id] = new_by_entry(tt, entry, parent_id,
2548
1342
                                                          tree)
2550
1344
                    new_trans_id = file_trans_id[file_id]
2551
1345
                    old_parent = tt.trans_id_tree_path(tree_path)
2552
1346
                    _reparent_children(tt, old_parent, new_trans_id)
2553
 
            offset = num + 1 - len(deferred_contents)
2554
 
            _create_files(tt, tree, deferred_contents, pb, offset,
2555
 
                          accelerator_tree, hardlink)
 
1347
            for num, (trans_id, bytes) in enumerate(
 
1348
                tree.iter_files_bytes(deferred_contents)):
 
1349
                tt.create_file(bytes, trans_id)
 
1350
                pb.update('Adding file contents',
 
1351
                          (num + len(tree.inventory) - len(deferred_contents)),
 
1352
                          len(tree.inventory))
2556
1353
        finally:
2557
1354
            pb.finished()
2558
1355
        pp.next_phase()
2559
1356
        divert_trans = set(file_trans_id[f] for f in divert)
2560
1357
        resolver = lambda t, c: resolve_checkout(t, c, divert_trans)
2561
1358
        raw_conflicts = resolve_conflicts(tt, pass_func=resolver)
2562
 
        if len(raw_conflicts) > 0:
2563
 
            precomputed_delta = None
2564
1359
        conflicts = cook_conflicts(raw_conflicts, tt)
2565
1360
        for conflict in conflicts:
2566
 
            trace.warning(conflict)
 
1361
            warning(conflict)
2567
1362
        try:
2568
1363
            wt.add_conflicts(conflicts)
2569
1364
        except errors.UnsupportedOperation:
2570
1365
            pass
2571
 
        result = tt.apply(no_conflicts=True,
2572
 
                          precomputed_delta=precomputed_delta)
 
1366
        result = tt.apply()
2573
1367
    finally:
2574
1368
        tt.finalize()
2575
1369
        top_pb.finished()
2576
1370
    return result
2577
1371
 
2578
1372
 
2579
 
def _create_files(tt, tree, desired_files, pb, offset, accelerator_tree,
2580
 
                  hardlink):
2581
 
    total = len(desired_files) + offset
2582
 
    wt = tt._tree
2583
 
    if accelerator_tree is None:
2584
 
        new_desired_files = desired_files
2585
 
    else:
2586
 
        iter = accelerator_tree.iter_changes(tree, include_unchanged=True)
2587
 
        unchanged = [(f, p[1]) for (f, p, c, v, d, n, k, e)
2588
 
                     in iter if not (c or e[0] != e[1])]
2589
 
        if accelerator_tree.supports_content_filtering():
2590
 
            unchanged = [(f, p) for (f, p) in unchanged
2591
 
                         if not accelerator_tree.iter_search_rules([p]).next()]
2592
 
        unchanged = dict(unchanged)
2593
 
        new_desired_files = []
2594
 
        count = 0
2595
 
        for file_id, (trans_id, tree_path, text_sha1) in desired_files:
2596
 
            accelerator_path = unchanged.get(file_id)
2597
 
            if accelerator_path is None:
2598
 
                new_desired_files.append((file_id,
2599
 
                    (trans_id, tree_path, text_sha1)))
2600
 
                continue
2601
 
            pb.update('Adding file contents', count + offset, total)
2602
 
            if hardlink:
2603
 
                tt.create_hardlink(accelerator_tree.abspath(accelerator_path),
2604
 
                                   trans_id)
2605
 
            else:
2606
 
                contents = accelerator_tree.get_file(file_id, accelerator_path)
2607
 
                if wt.supports_content_filtering():
2608
 
                    filters = wt._content_filter_stack(tree_path)
2609
 
                    contents = filtered_output_bytes(contents, filters,
2610
 
                        ContentFilterContext(tree_path, tree))
2611
 
                try:
2612
 
                    tt.create_file(contents, trans_id, sha1=text_sha1)
2613
 
                finally:
2614
 
                    try:
2615
 
                        contents.close()
2616
 
                    except AttributeError:
2617
 
                        # after filtering, contents may no longer be file-like
2618
 
                        pass
2619
 
            count += 1
2620
 
        offset += count
2621
 
    for count, ((trans_id, tree_path, text_sha1), contents) in enumerate(
2622
 
            tree.iter_files_bytes(new_desired_files)):
2623
 
        if wt.supports_content_filtering():
2624
 
            filters = wt._content_filter_stack(tree_path)
2625
 
            contents = filtered_output_bytes(contents, filters,
2626
 
                ContentFilterContext(tree_path, tree))
2627
 
        tt.create_file(contents, trans_id, sha1=text_sha1)
2628
 
        pb.update('Adding file contents', count + offset, total)
2629
 
 
2630
 
 
2631
1373
def _reparent_children(tt, old_parent, new_parent):
2632
1374
    for child in tt.iter_tree_children(old_parent):
2633
1375
        tt.adjust_path(tt.final_name(child), new_parent, child)
2634
1376
 
2635
1377
 
2636
 
def _reparent_transform_children(tt, old_parent, new_parent):
2637
 
    by_parent = tt.by_parent()
2638
 
    for child in by_parent[old_parent]:
2639
 
        tt.adjust_path(tt.final_name(child), new_parent, child)
2640
 
    return by_parent[old_parent]
2641
 
 
2642
 
 
2643
1378
def _content_match(tree, entry, file_id, kind, target_path):
2644
1379
    if entry.kind != kind:
2645
1380
        return False
2646
1381
    if entry.kind == "directory":
2647
1382
        return True
2648
1383
    if entry.kind == "file":
2649
 
        f = file(target_path, 'rb')
2650
 
        try:
2651
 
            if tree.get_file_text(file_id) == f.read():
2652
 
                return True
2653
 
        finally:
2654
 
            f.close()
 
1384
        if tree.get_file(file_id).read() == file(target_path, 'rb').read():
 
1385
            return True
2655
1386
    elif entry.kind == "symlink":
2656
1387
        if tree.get_symlink_target(file_id) == os.readlink(target_path):
2657
1388
            return True
2662
1393
    new_conflicts = set()
2663
1394
    for c_type, conflict in ((c[0], c) for c in conflicts):
2664
1395
        # Anything but a 'duplicate' would indicate programmer error
2665
 
        if c_type != 'duplicate':
2666
 
            raise AssertionError(c_type)
 
1396
        assert c_type == 'duplicate', c_type
2667
1397
        # Now figure out which is new and which is old
2668
1398
        if tt.new_contents(conflict[1]):
2669
1399
            new_file = conflict[1]
2695
1425
    if kind == 'file':
2696
1426
        contents = tree.get_file(entry.file_id).readlines()
2697
1427
        executable = tree.is_executable(entry.file_id)
2698
 
        return tt.new_file(name, parent_id, contents, entry.file_id,
 
1428
        return tt.new_file(name, parent_id, contents, entry.file_id, 
2699
1429
                           executable)
2700
1430
    elif kind in ('directory', 'tree-reference'):
2701
1431
        trans_id = tt.new_directory(name, parent_id, entry.file_id)
2702
1432
        if kind == 'tree-reference':
2703
1433
            tt.set_tree_reference(entry.reference_revision, trans_id)
2704
 
        return trans_id
 
1434
        return trans_id 
2705
1435
    elif kind == 'symlink':
2706
1436
        target = tree.get_symlink_target(entry.file_id)
2707
1437
        return tt.new_symlink(name, parent_id, target, entry.file_id)
2708
1438
    else:
2709
1439
        raise errors.BadFileKindError(name, kind)
2710
1440
 
2711
 
 
2712
 
def create_from_tree(tt, trans_id, tree, file_id, bytes=None,
2713
 
    filter_tree_path=None):
2714
 
    """Create new file contents according to tree contents.
2715
 
    
2716
 
    :param filter_tree_path: the tree path to use to lookup
2717
 
      content filters to apply to the bytes output in the working tree.
2718
 
      This only applies if the working tree supports content filtering.
2719
 
    """
2720
 
    kind = tree.kind(file_id)
2721
 
    if kind == 'directory':
 
1441
def create_by_entry(tt, entry, tree, trans_id, lines=None, mode_id=None):
 
1442
    """Create new file contents according to an inventory entry."""
 
1443
    if entry.kind == "file":
 
1444
        if lines is None:
 
1445
            lines = tree.get_file(entry.file_id).readlines()
 
1446
        tt.create_file(lines, trans_id, mode_id=mode_id)
 
1447
    elif entry.kind == "symlink":
 
1448
        tt.create_symlink(tree.get_symlink_target(entry.file_id), trans_id)
 
1449
    elif entry.kind == "directory":
2722
1450
        tt.create_directory(trans_id)
2723
 
    elif kind == "file":
2724
 
        if bytes is None:
2725
 
            tree_file = tree.get_file(file_id)
2726
 
            try:
2727
 
                bytes = tree_file.readlines()
2728
 
            finally:
2729
 
                tree_file.close()
2730
 
        wt = tt._tree
2731
 
        if wt.supports_content_filtering() and filter_tree_path is not None:
2732
 
            filters = wt._content_filter_stack(filter_tree_path)
2733
 
            bytes = filtered_output_bytes(bytes, filters,
2734
 
                ContentFilterContext(filter_tree_path, tree))
2735
 
        tt.create_file(bytes, trans_id)
2736
 
    elif kind == "symlink":
2737
 
        tt.create_symlink(tree.get_symlink_target(file_id), trans_id)
2738
 
    else:
2739
 
        raise AssertionError('Unknown kind %r' % kind)
2740
 
 
2741
1451
 
2742
1452
def create_entry_executability(tt, entry, trans_id):
2743
1453
    """Set the executability of a trans_id according to an inventory entry"""
2745
1455
        tt.set_executability(entry.executable, trans_id)
2746
1456
 
2747
1457
 
2748
 
@deprecated_function(deprecated_in((2, 3, 0)))
 
1458
@deprecated_function(zero_fifteen)
 
1459
def find_interesting(working_tree, target_tree, filenames):
 
1460
    """Find the ids corresponding to specified filenames.
 
1461
    
 
1462
    Deprecated: Please use tree1.paths2ids(filenames, [tree2]).
 
1463
    """
 
1464
    working_tree.lock_read()
 
1465
    try:
 
1466
        target_tree.lock_read()
 
1467
        try:
 
1468
            return working_tree.paths2ids(filenames, [target_tree])
 
1469
        finally:
 
1470
            target_tree.unlock()
 
1471
    finally:
 
1472
        working_tree.unlock()
 
1473
 
 
1474
 
 
1475
@deprecated_function(zero_ninety)
 
1476
def change_entry(tt, file_id, working_tree, target_tree, 
 
1477
                 trans_id_file_id, backups, trans_id, by_parent):
 
1478
    """Replace a file_id's contents with those from a target tree."""
 
1479
    if file_id is None and target_tree is None:
 
1480
        # skip the logic altogether in the deprecation test
 
1481
        return
 
1482
    e_trans_id = trans_id_file_id(file_id)
 
1483
    entry = target_tree.inventory[file_id]
 
1484
    has_contents, contents_mod, meta_mod, = _entry_changes(file_id, entry, 
 
1485
                                                           working_tree)
 
1486
    if contents_mod:
 
1487
        mode_id = e_trans_id
 
1488
        if has_contents:
 
1489
            if not backups:
 
1490
                tt.delete_contents(e_trans_id)
 
1491
            else:
 
1492
                parent_trans_id = trans_id_file_id(entry.parent_id)
 
1493
                backup_name = get_backup_name(entry, by_parent,
 
1494
                                              parent_trans_id, tt)
 
1495
                tt.adjust_path(backup_name, parent_trans_id, e_trans_id)
 
1496
                tt.unversion_file(e_trans_id)
 
1497
                e_trans_id = tt.create_path(entry.name, parent_trans_id)
 
1498
                tt.version_file(file_id, e_trans_id)
 
1499
                trans_id[file_id] = e_trans_id
 
1500
        create_by_entry(tt, entry, target_tree, e_trans_id, mode_id=mode_id)
 
1501
        create_entry_executability(tt, entry, e_trans_id)
 
1502
 
 
1503
    elif meta_mod:
 
1504
        tt.set_executability(entry.executable, e_trans_id)
 
1505
    if tt.final_name(e_trans_id) != entry.name:
 
1506
        adjust_path  = True
 
1507
    else:
 
1508
        parent_id = tt.final_parent(e_trans_id)
 
1509
        parent_file_id = tt.final_file_id(parent_id)
 
1510
        if parent_file_id != entry.parent_id:
 
1511
            adjust_path = True
 
1512
        else:
 
1513
            adjust_path = False
 
1514
    if adjust_path:
 
1515
        parent_trans_id = trans_id_file_id(entry.parent_id)
 
1516
        tt.adjust_path(entry.name, parent_trans_id, e_trans_id)
 
1517
 
 
1518
 
2749
1519
def get_backup_name(entry, by_parent, parent_trans_id, tt):
2750
1520
    return _get_backup_name(entry.name, by_parent, parent_trans_id, tt)
2751
1521
 
2752
1522
 
2753
 
@deprecated_function(deprecated_in((2, 3, 0)))
2754
1523
def _get_backup_name(name, by_parent, parent_trans_id, tt):
2755
1524
    """Produce a backup-style name that appears to be available"""
2756
1525
    def name_gen():
2783
1552
        if entry.kind != working_kind:
2784
1553
            contents_mod, meta_mod = True, False
2785
1554
        else:
2786
 
            cur_entry._read_tree_state(working_tree.id2path(file_id),
 
1555
            cur_entry._read_tree_state(working_tree.id2path(file_id), 
2787
1556
                                       working_tree)
2788
1557
            contents_mod, meta_mod = entry.detect_changes(cur_entry)
2789
1558
            cur_entry._forget_tree_state()
2791
1560
 
2792
1561
 
2793
1562
def revert(working_tree, target_tree, filenames, backups=False,
2794
 
           pb=None, change_reporter=None):
 
1563
           pb=DummyProgress(), change_reporter=None):
2795
1564
    """Revert a working tree's contents to those of a target tree."""
2796
1565
    target_tree.lock_read()
2797
 
    pb = ui.ui_factory.nested_progress_bar()
2798
1566
    tt = TreeTransform(working_tree, pb)
2799
1567
    try:
2800
1568
        pp = ProgressPhase("Revert phase", 3, pb)
2801
 
        conflicts, merge_modified = _prepare_revert_transform(
2802
 
            working_tree, target_tree, tt, filenames, backups, pp)
 
1569
        pp.next_phase()
 
1570
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1571
        try:
 
1572
            merge_modified = _alter_files(working_tree, target_tree, tt,
 
1573
                                          child_pb, filenames, backups)
 
1574
        finally:
 
1575
            child_pb.finished()
 
1576
        pp.next_phase()
 
1577
        child_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1578
        try:
 
1579
            raw_conflicts = resolve_conflicts(tt, child_pb)
 
1580
        finally:
 
1581
            child_pb.finished()
 
1582
        conflicts = cook_conflicts(raw_conflicts, tt)
2803
1583
        if change_reporter:
2804
1584
            change_reporter = delta._ChangeReporter(
2805
1585
                unversioned_filter=working_tree.is_ignored)
2806
 
            delta.report_changes(tt.iter_changes(), change_reporter)
 
1586
            delta.report_changes(tt._iter_changes(), change_reporter)
2807
1587
        for conflict in conflicts:
2808
 
            trace.warning(conflict)
 
1588
            warning(conflict)
2809
1589
        pp.next_phase()
2810
1590
        tt.apply()
2811
1591
        working_tree.set_merge_modified(merge_modified)
2816
1596
    return conflicts
2817
1597
 
2818
1598
 
2819
 
def _prepare_revert_transform(working_tree, target_tree, tt, filenames,
2820
 
                              backups, pp, basis_tree=None,
2821
 
                              merge_modified=None):
2822
 
    child_pb = ui.ui_factory.nested_progress_bar()
2823
 
    try:
2824
 
        if merge_modified is None:
2825
 
            merge_modified = working_tree.merge_modified()
2826
 
        merge_modified = _alter_files(working_tree, target_tree, tt,
2827
 
                                      child_pb, filenames, backups,
2828
 
                                      merge_modified, basis_tree)
2829
 
    finally:
2830
 
        child_pb.finished()
2831
 
    child_pb = ui.ui_factory.nested_progress_bar()
2832
 
    try:
2833
 
        raw_conflicts = resolve_conflicts(tt, child_pb,
2834
 
            lambda t, c: conflict_pass(t, c, target_tree))
2835
 
    finally:
2836
 
        child_pb.finished()
2837
 
    conflicts = cook_conflicts(raw_conflicts, tt)
2838
 
    return conflicts, merge_modified
2839
 
 
2840
 
 
2841
1599
def _alter_files(working_tree, target_tree, tt, pb, specific_files,
2842
 
                 backups, merge_modified, basis_tree=None):
2843
 
    if basis_tree is not None:
2844
 
        basis_tree.lock_read()
2845
 
    change_list = target_tree.iter_changes(working_tree,
 
1600
                 backups):
 
1601
    merge_modified = working_tree.merge_modified()
 
1602
    change_list = target_tree._iter_changes(working_tree,
2846
1603
        specific_files=specific_files, pb=pb)
2847
 
    if target_tree.get_root_id() is None:
 
1604
    if target_tree.inventory.root is None:
2848
1605
        skip_root = True
2849
1606
    else:
2850
1607
        skip_root = False
 
1608
    basis_tree = None
2851
1609
    try:
2852
1610
        deferred_files = []
2853
1611
        for id_num, (file_id, path, changed_content, versioned, parent, name,
2877
1635
                        tt.delete_contents(trans_id)
2878
1636
                    elif kind[1] is not None:
2879
1637
                        parent_trans_id = tt.trans_id_file_id(parent[0])
2880
 
                        backup_name = tt._available_backup_name(
2881
 
                            name[0], parent_trans_id)
 
1638
                        by_parent = tt.by_parent()
 
1639
                        backup_name = _get_backup_name(name[0], by_parent,
 
1640
                                                       parent_trans_id, tt)
2882
1641
                        tt.adjust_path(backup_name, parent_trans_id, trans_id)
2883
1642
                        new_trans_id = tt.create_path(name[0], parent_trans_id)
2884
1643
                        if versioned == (True, True):
2888
1647
                        # contents
2889
1648
                        mode_id = trans_id
2890
1649
                        trans_id = new_trans_id
2891
 
                if kind[1] in ('directory', 'tree-reference'):
 
1650
                if kind[1] == 'directory':
2892
1651
                    tt.create_directory(trans_id)
2893
 
                    if kind[1] == 'tree-reference':
2894
 
                        revision = target_tree.get_reference_revision(file_id,
2895
 
                                                                      path[1])
2896
 
                        tt.set_tree_reference(revision, trans_id)
2897
1652
                elif kind[1] == 'symlink':
2898
1653
                    tt.create_symlink(target_tree.get_symlink_target(file_id),
2899
1654
                                      trans_id)
2913
1668
                    # preserve the execute bit when backing up
2914
1669
                    if keep_content and executable[0] == executable[1]:
2915
1670
                        tt.set_executability(executable[1], trans_id)
2916
 
                elif kind[1] is not None:
2917
 
                    raise AssertionError(kind[1])
 
1671
                else:
 
1672
                    assert kind[1] is None
2918
1673
            if versioned == (False, True):
2919
1674
                tt.version_file(file_id, trans_id)
2920
1675
            if versioned == (True, False):
2921
1676
                tt.unversion_file(trans_id)
2922
 
            if (name[1] is not None and
 
1677
            if (name[1] is not None and 
2923
1678
                (name[0] != name[1] or parent[0] != parent[1])):
2924
 
                if name[1] == '' and parent[1] is None:
2925
 
                    parent_trans = ROOT_PARENT
2926
 
                else:
2927
 
                    parent_trans = tt.trans_id_file_id(parent[1])
2928
 
                if parent[0] is None and versioned[0]:
2929
 
                    tt.adjust_root_path(name[1], parent_trans)
2930
 
                else:
2931
 
                    tt.adjust_path(name[1], parent_trans, trans_id)
 
1679
                tt.adjust_path(
 
1680
                    name[1], tt.trans_id_file_id(parent[1]), trans_id)
2932
1681
            if executable[0] != executable[1] and kind[1] == "file":
2933
1682
                tt.set_executability(executable[1], trans_id)
2934
 
        if working_tree.supports_content_filtering():
2935
 
            for index, ((trans_id, mode_id), bytes) in enumerate(
2936
 
                target_tree.iter_files_bytes(deferred_files)):
2937
 
                file_id = deferred_files[index][0]
2938
 
                # We're reverting a tree to the target tree so using the
2939
 
                # target tree to find the file path seems the best choice
2940
 
                # here IMO - Ian C 27/Oct/2009
2941
 
                filter_tree_path = target_tree.id2path(file_id)
2942
 
                filters = working_tree._content_filter_stack(filter_tree_path)
2943
 
                bytes = filtered_output_bytes(bytes, filters,
2944
 
                    ContentFilterContext(filter_tree_path, working_tree))
2945
 
                tt.create_file(bytes, trans_id, mode_id)
2946
 
        else:
2947
 
            for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
2948
 
                deferred_files):
2949
 
                tt.create_file(bytes, trans_id, mode_id)
2950
 
        tt.fixup_new_roots()
 
1683
        for (trans_id, mode_id), bytes in target_tree.iter_files_bytes(
 
1684
            deferred_files):
 
1685
            tt.create_file(bytes, trans_id, mode_id)
2951
1686
    finally:
2952
1687
        if basis_tree is not None:
2953
1688
            basis_tree.unlock()
2954
1689
    return merge_modified
2955
1690
 
2956
1691
 
2957
 
def resolve_conflicts(tt, pb=None, pass_func=None):
 
1692
def resolve_conflicts(tt, pb=DummyProgress(), pass_func=None):
2958
1693
    """Make many conflict-resolution attempts, but die if they fail"""
2959
1694
    if pass_func is None:
2960
1695
        pass_func = conflict_pass
2961
1696
    new_conflicts = set()
2962
 
    pb = ui.ui_factory.nested_progress_bar()
2963
1697
    try:
2964
1698
        for n in range(10):
2965
1699
            pb.update('Resolution pass', n+1, 10)
2969
1703
            new_conflicts.update(pass_func(tt, conflicts))
2970
1704
        raise MalformedTransform(conflicts=conflicts)
2971
1705
    finally:
2972
 
        pb.finished()
 
1706
        pb.clear()
2973
1707
 
2974
1708
 
2975
1709
def conflict_pass(tt, conflicts, path_tree=None):
2987
1721
                               conflict[1], conflict[2], ))
2988
1722
        elif c_type == 'duplicate':
2989
1723
            # files that were renamed take precedence
 
1724
            new_name = tt.final_name(conflict[1])+'.moved'
2990
1725
            final_parent = tt.final_parent(conflict[1])
2991
1726
            if tt.path_changed(conflict[1]):
2992
 
                existing_file, new_file = conflict[2], conflict[1]
 
1727
                tt.adjust_path(new_name, final_parent, conflict[2])
 
1728
                new_conflicts.add((c_type, 'Moved existing file to', 
 
1729
                                   conflict[2], conflict[1]))
2993
1730
            else:
2994
 
                existing_file, new_file = conflict[1], conflict[2]
2995
 
            new_name = tt.final_name(existing_file)+'.moved'
2996
 
            tt.adjust_path(new_name, final_parent, existing_file)
2997
 
            new_conflicts.add((c_type, 'Moved existing file to',
2998
 
                               existing_file, new_file))
 
1731
                tt.adjust_path(new_name, final_parent, conflict[1])
 
1732
                new_conflicts.add((c_type, 'Moved existing file to', 
 
1733
                                  conflict[1], conflict[2]))
2999
1734
        elif c_type == 'parent loop':
3000
1735
            # break the loop by undoing one of the ops that caused the loop
3001
1736
            cur = conflict[1]
3004
1739
            new_conflicts.add((c_type, 'Cancelled move', cur,
3005
1740
                               tt.final_parent(cur),))
3006
1741
            tt.adjust_path(tt.final_name(cur), tt.get_tree_parent(cur), cur)
3007
 
 
 
1742
            
3008
1743
        elif c_type == 'missing parent':
3009
1744
            trans_id = conflict[1]
3010
 
            if trans_id in tt._removed_contents:
3011
 
                cancel_deletion = True
3012
 
                orphans = tt._get_potential_orphans(trans_id)
3013
 
                if orphans:
3014
 
                    cancel_deletion = False
3015
 
                    # All children are orphans
3016
 
                    for o in orphans:
3017
 
                        try:
3018
 
                            tt.new_orphan(o, trans_id)
3019
 
                        except OrphaningError:
3020
 
                            # Something bad happened so we cancel the directory
3021
 
                            # deletion which will leave it in place with a
3022
 
                            # conflict. The user can deal with it from there.
3023
 
                            # Note that this also catch the case where we don't
3024
 
                            # want to create orphans and leave the directory in
3025
 
                            # place.
3026
 
                            cancel_deletion = True
3027
 
                            break
3028
 
                if cancel_deletion:
3029
 
                    # Cancel the directory deletion
3030
 
                    tt.cancel_deletion(trans_id)
3031
 
                    new_conflicts.add(('deleting parent', 'Not deleting',
3032
 
                                       trans_id))
3033
 
            else:
3034
 
                create = True
 
1745
            try:
 
1746
                tt.cancel_deletion(trans_id)
 
1747
                new_conflicts.add(('deleting parent', 'Not deleting', 
 
1748
                                   trans_id))
 
1749
            except KeyError:
 
1750
                tt.create_directory(trans_id)
 
1751
                new_conflicts.add((c_type, 'Created directory', trans_id))
3035
1752
                try:
3036
1753
                    tt.final_name(trans_id)
3037
1754
                except NoFinalPath:
3038
 
                    if path_tree is not None:
3039
 
                        file_id = tt.final_file_id(trans_id)
3040
 
                        if file_id is None:
3041
 
                            file_id = tt.inactive_file_id(trans_id)
3042
 
                        _, entry = path_tree.iter_entries_by_dir(
3043
 
                            [file_id]).next()
3044
 
                        # special-case the other tree root (move its
3045
 
                        # children to current root)
3046
 
                        if entry.parent_id is None:
3047
 
                            create = False
3048
 
                            moved = _reparent_transform_children(
3049
 
                                tt, trans_id, tt.root)
3050
 
                            for child in moved:
3051
 
                                new_conflicts.add((c_type, 'Moved to root',
3052
 
                                                   child))
3053
 
                        else:
3054
 
                            parent_trans_id = tt.trans_id_file_id(
3055
 
                                entry.parent_id)
3056
 
                            tt.adjust_path(entry.name, parent_trans_id,
3057
 
                                           trans_id)
3058
 
                if create:
3059
 
                    tt.create_directory(trans_id)
3060
 
                    new_conflicts.add((c_type, 'Created directory', trans_id))
 
1755
                    file_id = tt.final_file_id(trans_id)
 
1756
                    entry = path_tree.inventory[file_id]
 
1757
                    parent_trans_id = tt.trans_id_file_id(entry.parent_id)
 
1758
                    tt.adjust_path(entry.name, parent_trans_id, trans_id)
3061
1759
        elif c_type == 'unversioned parent':
3062
 
            file_id = tt.inactive_file_id(conflict[1])
3063
 
            # special-case the other tree root (move its children instead)
3064
 
            if path_tree and file_id in path_tree:
3065
 
                if path_tree.path2id('') == file_id:
3066
 
                    # This is the root entry, skip it
3067
 
                    continue
3068
 
            tt.version_file(file_id, conflict[1])
 
1760
            tt.version_file(tt.inactive_file_id(conflict[1]), conflict[1])
3069
1761
            new_conflicts.add((c_type, 'Versioned directory', conflict[1]))
3070
 
        elif c_type == 'non-directory parent':
3071
 
            parent_id = conflict[1]
3072
 
            parent_parent = tt.final_parent(parent_id)
3073
 
            parent_name = tt.final_name(parent_id)
3074
 
            parent_file_id = tt.final_file_id(parent_id)
3075
 
            new_parent_id = tt.new_directory(parent_name + '.new',
3076
 
                parent_parent, parent_file_id)
3077
 
            _reparent_transform_children(tt, parent_id, new_parent_id)
3078
 
            if parent_file_id is not None:
3079
 
                tt.unversion_file(parent_id)
3080
 
            new_conflicts.add((c_type, 'Created directory', new_parent_id))
3081
 
        elif c_type == 'versioning no contents':
3082
 
            tt.cancel_versioning(conflict[1])
3083
1762
    return new_conflicts
3084
1763
 
3085
1764
 
3101
1780
        if len(conflict) == 3:
3102
1781
            yield Conflict.factory(c_type, action=action, path=modified_path,
3103
1782
                                     file_id=modified_id)
3104
 
 
 
1783
             
3105
1784
        else:
3106
1785
            conflicting_path = fp.get_path(conflict[3])
3107
1786
            conflicting_id = tt.final_file_id(conflict[3])
3108
1787
            yield Conflict.factory(c_type, action=action, path=modified_path,
3109
 
                                   file_id=modified_id,
 
1788
                                   file_id=modified_id, 
3110
1789
                                   conflict_path=conflicting_path,
3111
1790
                                   conflict_file_id=conflicting_id)
3112
1791
 
3119
1798
        self.pending_deletions = []
3120
1799
 
3121
1800
    def rename(self, from_, to):
3122
 
        """Rename a file from one path to another."""
3123
 
        try:
3124
 
            os.rename(from_, to)
3125
 
        except OSError, e:
3126
 
            if e.errno in (errno.EEXIST, errno.ENOTEMPTY):
3127
 
                raise errors.FileExists(to, str(e))
3128
 
            # normal OSError doesn't include filenames so it's hard to see where
3129
 
            # the problem is, see https://bugs.launchpad.net/bzr/+bug/491763
3130
 
            raise errors.TransformRenameFailed(from_, to, str(e), e.errno)
 
1801
        """Rename a file from one path to another.  Functions like os.rename"""
 
1802
        os.rename(from_, to)
3131
1803
        self.past_renames.append((from_, to))
3132
1804
 
3133
1805
    def pre_delete(self, from_, to):
3143
1815
    def rollback(self):
3144
1816
        """Reverse all renames that have been performed"""
3145
1817
        for from_, to in reversed(self.past_renames):
3146
 
            try:
3147
 
                os.rename(to, from_)
3148
 
            except OSError, e:
3149
 
                raise errors.TransformRenameFailed(to, from_, str(e), e.errno)
 
1818
            os.rename(to, from_)
3150
1819
        # after rollback, don't reuse _FileMover
3151
1820
        past_renames = None
3152
1821
        pending_deletions = None