/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: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

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