/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/transform.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2011-06-22 09:54:01 UTC
  • mfrom: (5991.2.1 trunk)
  • Revision ID: pqm@pqm.ubuntu.com-20110622095401-n1nkzancazl4h0kg
(vila) Slightly simplify whoami tests (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

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