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