~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tree.py

  • Committer: INADA Naoki
  • Date: 2011-05-05 09:15:34 UTC
  • mto: (5830.3.3 i18n-msgfmt)
  • mto: This revision was merged to the branch mainline in revision 5873.
  • Revision ID: songofacandy@gmail.com-20110505091534-7sv835xpofwrmpt4
Add update-pot command to Makefile and tools/bzrgettext script that
extracts help text from bzr commands.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
18
18
"""
19
19
 
20
20
import os
21
 
from collections import deque
22
 
from cStringIO import StringIO
23
 
 
24
 
import bzrlib
 
21
 
 
22
from bzrlib.lazy_import import lazy_import
 
23
lazy_import(globals(), """
 
24
import collections
 
25
 
25
26
from bzrlib import (
26
27
    conflicts as _mod_conflicts,
27
28
    debug,
28
29
    delta,
 
30
    errors,
29
31
    filters,
 
32
    inventory,
30
33
    osutils,
31
34
    revision as _mod_revision,
32
35
    rules,
33
 
    symbol_versioning,
 
36
    trace,
34
37
    )
 
38
""")
 
39
 
35
40
from bzrlib.decorators import needs_read_lock
36
 
from bzrlib.errors import BzrError, BzrCheckError, NoSuchId
37
 
from bzrlib import errors
38
 
from bzrlib.inventory import Inventory, InventoryFile
39
41
from bzrlib.inter import InterObject
40
 
from bzrlib.osutils import fingerprint_file
41
 
import bzrlib.revision
42
 
from bzrlib.symbol_versioning import deprecated_function, deprecated_in
43
 
from bzrlib.trace import mutter, note
44
42
 
45
43
 
46
44
class Tree(object):
52
50
 
53
51
    * `RevisionTree` is a tree as recorded at some point in the past.
54
52
 
55
 
    Trees contain an `Inventory` object, and also know how to retrieve
56
 
    file texts mentioned in the inventory, either from a working
57
 
    directory or from a store.
58
 
 
59
 
    It is possible for trees to contain files that are not described
60
 
    in their inventory or vice versa; for this use `filenames()`.
61
 
 
62
53
    Trees can be compared, etc, regardless of whether they are working
63
54
    trees or versioned trees.
64
55
    """
100
91
    def iter_changes(self, from_tree, include_unchanged=False,
101
92
                     specific_files=None, pb=None, extra_trees=None,
102
93
                     require_versioned=True, want_unversioned=False):
 
94
        """See InterTree.iter_changes"""
103
95
        intertree = InterTree.get(from_tree, self)
104
96
        return intertree.iter_changes(include_unchanged, specific_files, pb,
105
97
            extra_trees, require_versioned, want_unversioned=want_unversioned)
129
121
        raise NotImplementedError(self.has_filename)
130
122
 
131
123
    def has_id(self, file_id):
132
 
        return self.inventory.has_id(file_id)
 
124
        raise NotImplementedError(self.has_id)
133
125
 
134
126
    def __contains__(self, file_id):
135
127
        return self.has_id(file_id)
136
128
 
137
129
    def has_or_had_id(self, file_id):
138
 
        if file_id == self.inventory.root.file_id:
139
 
            return True
140
 
        return self.inventory.has_id(file_id)
 
130
        raise NotImplementedError(self.has_or_had_id)
141
131
 
142
132
    def is_ignored(self, filename):
143
133
        """Check whether the filename is ignored by this tree.
148
138
        return False
149
139
 
150
140
    def __iter__(self):
151
 
        return iter(self.inventory)
 
141
        """Yield all file ids in this tree."""
 
142
        raise NotImplementedError(self.__iter__)
152
143
 
153
144
    def all_file_ids(self):
154
145
        """Iterate through all file ids, including ids for missing files."""
159
150
 
160
151
        :raises NoSuchId:
161
152
        """
162
 
        return self.inventory.id2path(file_id)
163
 
 
164
 
    def is_control_filename(self, filename):
165
 
        """True if filename is the name of a control file in this tree.
166
 
 
167
 
        :param filename: A filename within the tree. This is a relative path
168
 
        from the root of this tree.
169
 
 
170
 
        This is true IF and ONLY IF the filename is part of the meta data
171
 
        that bzr controls in this tree. I.E. a random .bzr directory placed
172
 
        on disk will not be a control file for this tree.
173
 
        """
174
 
        return self.bzrdir.is_control_filename(filename)
175
 
 
176
 
    @needs_read_lock
177
 
    def iter_entries_by_dir(self, specific_file_ids=None):
 
153
        raise NotImplementedError(self.id2path)
 
154
 
 
155
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
178
156
        """Walk the tree in 'by_dir' order.
179
157
 
180
158
        This will yield each entry in the tree as a (path, entry) tuple.
197
175
 
198
176
        The yield order (ignoring root) would be::
199
177
          a, f, a/b, a/d, a/b/c, a/d/e, f/g
200
 
        """
201
 
        return self.inventory.iter_entries_by_dir(
202
 
            specific_file_ids=specific_file_ids)
 
178
 
 
179
        :param yield_parents: If True, yield the parents from the root leading
 
180
            down to specific_file_ids that have been requested. This has no
 
181
            impact if specific_file_ids is None.
 
182
        """
 
183
        raise NotImplementedError(self.iter_entries_by_dir)
 
184
 
 
185
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
186
        """List all files in this tree.
 
187
 
 
188
        :param include_root: Whether to include the entry for the tree root
 
189
        :param from_dir: Directory under which to list files
 
190
        :param recursive: Whether to list files recursively
 
191
        :return: iterator over tuples of (path, versioned, kind, file_id,
 
192
            inventory entry)
 
193
        """
 
194
        raise NotImplementedError(self.list_files)
203
195
 
204
196
    def iter_references(self):
205
 
        for path, entry in self.iter_entries_by_dir():
206
 
            if entry.kind == 'tree-reference':
207
 
                yield path, entry.file_id
 
197
        if self.supports_tree_reference():
 
198
            for path, entry in self.iter_entries_by_dir():
 
199
                if entry.kind == 'tree-reference':
 
200
                    yield path, entry.file_id
208
201
 
209
202
    def kind(self, file_id):
210
203
        raise NotImplementedError("Tree subclass %s must implement kind"
221
214
    def path_content_summary(self, path):
222
215
        """Get a summary of the information about path.
223
216
 
 
217
        All the attributes returned are for the canonical form, not the
 
218
        convenient form (if content filters are in use.)
 
219
 
224
220
        :param path: A relative path within the tree.
225
221
        :return: A tuple containing kind, size, exec, sha1-or-link.
226
222
            Kind is always present (see tree.kind()).
227
 
            size is present if kind is file, None otherwise.
 
223
            size is present if kind is file and the size of the 
 
224
                canonical form can be cheaply determined, None otherwise.
228
225
            exec is None unless kind is file and the platform supports the 'x'
229
226
                bit.
230
227
            sha1-or-link is the link target if kind is symlink, or the sha1 if
251
248
    def _file_size(self, entry, stat_value):
252
249
        raise NotImplementedError(self._file_size)
253
250
 
254
 
    def _get_inventory(self):
255
 
        return self._inventory
256
 
 
257
251
    def get_file(self, file_id, path=None):
258
252
        """Return a file object for the file file_id in the tree.
259
253
 
262
256
        """
263
257
        raise NotImplementedError(self.get_file)
264
258
 
 
259
    def get_file_with_stat(self, file_id, path=None):
 
260
        """Get a file handle and stat object for file_id.
 
261
 
 
262
        The default implementation returns (self.get_file, None) for backwards
 
263
        compatibility.
 
264
 
 
265
        :param file_id: The file id to read.
 
266
        :param path: The path of the file, if it is known.
 
267
        :return: A tuple (file_handle, stat_value_or_None). If the tree has
 
268
            no stat facility, or need for a stat cache feedback during commit,
 
269
            it may return None for the second element of the tuple.
 
270
        """
 
271
        return (self.get_file(file_id, path), None)
 
272
 
265
273
    def get_file_text(self, file_id, path=None):
266
274
        """Return the byte content of a file.
267
275
 
286
294
        """
287
295
        return osutils.split_lines(self.get_file_text(file_id, path))
288
296
 
 
297
    def get_file_sha1(self, file_id, path=None):
 
298
        """Return the SHA1 file for a file.
 
299
 
 
300
        :param file_id: The handle for this file.
 
301
        :param path: The path that this file can be found at.
 
302
            These must point to the same object.
 
303
        """
 
304
        raise NotImplementedError(self.get_file_sha1)
 
305
 
289
306
    def get_file_mtime(self, file_id, path=None):
290
307
        """Return the modification time for a file.
291
308
 
305
322
        raise NotImplementedError(self.get_file_size)
306
323
 
307
324
    def get_file_by_path(self, path):
308
 
        return self.get_file(self._inventory.path2id(path), path)
 
325
        raise NotImplementedError(self.get_file_by_path)
 
326
 
 
327
    def is_executable(self, file_id, path=None):
 
328
        """Check if a file is executable.
 
329
 
 
330
        :param file_id: The handle for this file.
 
331
        :param path: The path that this file can be found at.
 
332
            These must point to the same object.
 
333
        """
 
334
        raise NotImplementedError(self.is_executable)
309
335
 
310
336
    def iter_files_bytes(self, desired_files):
311
337
        """Iterate through file contents.
343
369
        """
344
370
        raise NotImplementedError(self.get_symlink_target)
345
371
 
346
 
    def get_canonical_inventory_paths(self, paths):
347
 
        """Like get_canonical_inventory_path() but works on multiple items.
348
 
 
349
 
        :param paths: A sequence of paths relative to the root of the tree.
350
 
        :return: A list of paths, with each item the corresponding input path
351
 
        adjusted to account for existing elements that match case
352
 
        insensitively.
353
 
        """
354
 
        return list(self._yield_canonical_inventory_paths(paths))
355
 
 
356
 
    def get_canonical_inventory_path(self, path):
357
 
        """Returns the first inventory item that case-insensitively matches path.
358
 
 
359
 
        If a path matches exactly, it is returned. If no path matches exactly
360
 
        but more than one path matches case-insensitively, it is implementation
361
 
        defined which is returned.
362
 
 
363
 
        If no path matches case-insensitively, the input path is returned, but
364
 
        with as many path entries that do exist changed to their canonical
365
 
        form.
366
 
 
367
 
        If you need to resolve many names from the same tree, you should
368
 
        use get_canonical_inventory_paths() to avoid O(N) behaviour.
369
 
 
370
 
        :param path: A paths relative to the root of the tree.
371
 
        :return: The input path adjusted to account for existing elements
372
 
        that match case insensitively.
373
 
        """
374
 
        return self._yield_canonical_inventory_paths([path]).next()
375
 
 
376
 
    def _yield_canonical_inventory_paths(self, paths):
377
 
        for path in paths:
378
 
            # First, if the path as specified exists exactly, just use it.
379
 
            if self.path2id(path) is not None:
380
 
                yield path
381
 
                continue
382
 
            # go walkin...
383
 
            cur_id = self.get_root_id()
384
 
            cur_path = ''
385
 
            bit_iter = iter(path.split("/"))
386
 
            for elt in bit_iter:
387
 
                lelt = elt.lower()
388
 
                for child in self.iter_children(cur_id):
389
 
                    try:
390
 
                        child_base = os.path.basename(self.id2path(child))
391
 
                        if child_base.lower() == lelt:
392
 
                            cur_id = child
393
 
                            cur_path = osutils.pathjoin(cur_path, child_base)
394
 
                            break
395
 
                    except NoSuchId:
396
 
                        # before a change is committed we can see this error...
397
 
                        continue
398
 
                else:
399
 
                    # got to the end of this directory and no entries matched.
400
 
                    # Return what matched so far, plus the rest as specified.
401
 
                    cur_path = osutils.pathjoin(cur_path, elt, *list(bit_iter))
402
 
                    break
403
 
            yield cur_path
404
 
        # all done.
405
372
 
406
373
    def get_root_id(self):
407
374
        """Return the file_id for the root of this tree."""
422
389
        raise NotImplementedError(self.annotate_iter)
423
390
 
424
391
    def _get_plan_merge_data(self, file_id, other, base):
425
 
        from bzrlib import merge, versionedfile
 
392
        from bzrlib import versionedfile
426
393
        vf = versionedfile._PlanMergeVersionedFile(file_id)
427
394
        last_revision_a = self._get_file_revision(file_id, vf, 'this:')
428
395
        last_revision_b = other._get_file_revision(file_id, vf, 'other:')
466
433
            except errors.NoSuchRevisionInTree:
467
434
                yield self.repository.revision_tree(revision_id)
468
435
 
469
 
    @staticmethod
470
 
    def _file_revision(revision_tree, file_id):
471
 
        """Determine the revision associated with a file in a given tree."""
472
 
        revision_tree.lock_read()
473
 
        try:
474
 
            return revision_tree.inventory[file_id].revision
475
 
        finally:
476
 
            revision_tree.unlock()
477
 
 
478
436
    def _get_file_revision(self, file_id, vf, tree_revision):
479
437
        """Ensure that file_id, tree_revision is in vf to plan the merge."""
480
438
 
481
439
        if getattr(self, '_repository', None) is None:
482
440
            last_revision = tree_revision
483
 
            parent_keys = [(file_id, self._file_revision(t, file_id)) for t in
 
441
            parent_keys = [(file_id, t.get_file_revision(file_id)) for t in
484
442
                self._iter_parent_trees()]
485
443
            vf.add_lines((file_id, last_revision), parent_keys,
486
 
                         self.get_file(file_id).readlines())
 
444
                         self.get_file_lines(file_id))
487
445
            repo = self.branch.repository
488
446
            base_vf = repo.texts
489
447
        else:
490
 
            last_revision = self._file_revision(self, file_id)
 
448
            last_revision = self.get_file_revision(file_id)
491
449
            base_vf = self._repository.texts
492
450
        if base_vf not in vf.fallback_versionedfiles:
493
451
            vf.fallback_versionedfiles.append(base_vf)
494
452
        return last_revision
495
453
 
496
 
    inventory = property(_get_inventory,
497
 
                         doc="Inventory of this Tree")
498
 
 
499
454
    def _check_retrieved(self, ie, f):
500
455
        if not __debug__:
501
456
            return
502
 
        fp = fingerprint_file(f)
 
457
        fp = osutils.fingerprint_file(f)
503
458
        f.seek(0)
504
459
 
505
460
        if ie.text_size is not None:
506
461
            if ie.text_size != fp['size']:
507
 
                raise BzrError("mismatched size for file %r in %r" % (ie.file_id, self._store),
 
462
                raise errors.BzrError(
 
463
                        "mismatched size for file %r in %r" %
 
464
                        (ie.file_id, self._store),
508
465
                        ["inventory expects %d bytes" % ie.text_size,
509
466
                         "file is actually %d bytes" % fp['size'],
510
467
                         "store is probably damaged/corrupt"])
511
468
 
512
469
        if ie.text_sha1 != fp['sha1']:
513
 
            raise BzrError("wrong SHA-1 for file %r in %r" % (ie.file_id, self._store),
 
470
            raise errors.BzrError("wrong SHA-1 for file %r in %r" %
 
471
                    (ie.file_id, self._store),
514
472
                    ["inventory expects %s" % ie.text_sha1,
515
473
                     "file is actually %s" % fp['sha1'],
516
474
                     "store is probably damaged/corrupt"])
517
475
 
518
 
    @needs_read_lock
519
476
    def path2id(self, path):
520
477
        """Return the id for path in this tree."""
521
 
        return self._inventory.path2id(path)
 
478
        raise NotImplementedError(self.path2id)
522
479
 
523
480
    def paths2ids(self, paths, trees=[], require_versioned=True):
524
481
        """Return all the ids that can be reached by walking from paths.
545
502
            yield child.file_id
546
503
 
547
504
    def lock_read(self):
 
505
        """Lock this tree for multiple read only operations.
 
506
        
 
507
        :return: A bzrlib.lock.LogicalLockResult.
 
508
        """
548
509
        pass
549
510
 
550
511
    def revision_tree(self, revision_id):
577
538
 
578
539
        :return: set of paths.
579
540
        """
580
 
        # NB: we specifically *don't* call self.has_filename, because for
581
 
        # WorkingTrees that can indicate files that exist on disk but that
582
 
        # are not versioned.
583
 
        pred = self.inventory.has_filename
584
 
        return set((p for p in paths if not pred(p)))
 
541
        raise NotImplementedError(self.filter_unversioned_files)
585
542
 
586
543
    def walkdirs(self, prefix=""):
587
544
        """Walk the contents of this tree from path down.
639
596
        prefs = self.iter_search_rules([path], filter_pref_names).next()
640
597
        stk = filters._get_filter_stack_for(prefs)
641
598
        if 'filters' in debug.debug_flags:
642
 
            note("*** %s content-filter: %s => %r" % (path,prefs,stk))
 
599
            trace.note("*** %s content-filter: %s => %r" % (path,prefs,stk))
643
600
        return stk
644
601
 
645
602
    def _content_filter_stack_provider(self):
657
614
            return None
658
615
 
659
616
    def iter_search_rules(self, path_names, pref_names=None,
660
 
        _default_searcher=rules._per_user_searcher):
 
617
        _default_searcher=None):
661
618
        """Find the preferences for filenames in a tree.
662
619
 
663
620
        :param path_names: an iterable of paths to find attributes for.
667
624
        :return: an iterator of tuple sequences, one per path-name.
668
625
          See _RulesSearcher.get_items for details on the tuple sequence.
669
626
        """
 
627
        if _default_searcher is None:
 
628
            _default_searcher = rules._per_user_searcher
670
629
        searcher = self._get_rules_searcher(_default_searcher)
671
630
        if searcher is not None:
672
631
            if pref_names is not None:
676
635
                for path in path_names:
677
636
                    yield searcher.get_items(path)
678
637
 
679
 
    @needs_read_lock
680
638
    def _get_rules_searcher(self, default_searcher):
681
639
        """Get the RulesSearcher for this tree given the default one."""
682
640
        searcher = default_searcher
683
641
        return searcher
684
642
 
685
643
 
 
644
class InventoryTree(Tree):
 
645
    """A tree that relies on an inventory for its metadata.
 
646
 
 
647
    Trees contain an `Inventory` object, and also know how to retrieve
 
648
    file texts mentioned in the inventory, either from a working
 
649
    directory or from a store.
 
650
 
 
651
    It is possible for trees to contain files that are not described
 
652
    in their inventory or vice versa; for this use `filenames()`.
 
653
 
 
654
    Subclasses should set the _inventory attribute, which is considered
 
655
    private to external API users.
 
656
    """
 
657
 
 
658
    def get_canonical_inventory_paths(self, paths):
 
659
        """Like get_canonical_inventory_path() but works on multiple items.
 
660
 
 
661
        :param paths: A sequence of paths relative to the root of the tree.
 
662
        :return: A list of paths, with each item the corresponding input path
 
663
        adjusted to account for existing elements that match case
 
664
        insensitively.
 
665
        """
 
666
        return list(self._yield_canonical_inventory_paths(paths))
 
667
 
 
668
    def get_canonical_inventory_path(self, path):
 
669
        """Returns the first inventory item that case-insensitively matches path.
 
670
 
 
671
        If a path matches exactly, it is returned. If no path matches exactly
 
672
        but more than one path matches case-insensitively, it is implementation
 
673
        defined which is returned.
 
674
 
 
675
        If no path matches case-insensitively, the input path is returned, but
 
676
        with as many path entries that do exist changed to their canonical
 
677
        form.
 
678
 
 
679
        If you need to resolve many names from the same tree, you should
 
680
        use get_canonical_inventory_paths() to avoid O(N) behaviour.
 
681
 
 
682
        :param path: A paths relative to the root of the tree.
 
683
        :return: The input path adjusted to account for existing elements
 
684
        that match case insensitively.
 
685
        """
 
686
        return self._yield_canonical_inventory_paths([path]).next()
 
687
 
 
688
    def _yield_canonical_inventory_paths(self, paths):
 
689
        for path in paths:
 
690
            # First, if the path as specified exists exactly, just use it.
 
691
            if self.path2id(path) is not None:
 
692
                yield path
 
693
                continue
 
694
            # go walkin...
 
695
            cur_id = self.get_root_id()
 
696
            cur_path = ''
 
697
            bit_iter = iter(path.split("/"))
 
698
            for elt in bit_iter:
 
699
                lelt = elt.lower()
 
700
                new_path = None
 
701
                for child in self.iter_children(cur_id):
 
702
                    try:
 
703
                        # XXX: it seem like if the child is known to be in the
 
704
                        # tree, we shouldn't need to go from its id back to
 
705
                        # its path -- mbp 2010-02-11
 
706
                        #
 
707
                        # XXX: it seems like we could be more efficient
 
708
                        # by just directly looking up the original name and
 
709
                        # only then searching all children; also by not
 
710
                        # chopping paths so much. -- mbp 2010-02-11
 
711
                        child_base = os.path.basename(self.id2path(child))
 
712
                        if (child_base == elt):
 
713
                            # if we found an exact match, we can stop now; if
 
714
                            # we found an approximate match we need to keep
 
715
                            # searching because there might be an exact match
 
716
                            # later.  
 
717
                            cur_id = child
 
718
                            new_path = osutils.pathjoin(cur_path, child_base)
 
719
                            break
 
720
                        elif child_base.lower() == lelt:
 
721
                            cur_id = child
 
722
                            new_path = osutils.pathjoin(cur_path, child_base)
 
723
                    except errors.NoSuchId:
 
724
                        # before a change is committed we can see this error...
 
725
                        continue
 
726
                if new_path:
 
727
                    cur_path = new_path
 
728
                else:
 
729
                    # got to the end of this directory and no entries matched.
 
730
                    # Return what matched so far, plus the rest as specified.
 
731
                    cur_path = osutils.pathjoin(cur_path, elt, *list(bit_iter))
 
732
                    break
 
733
            yield cur_path
 
734
        # all done.
 
735
 
 
736
    def _get_inventory(self):
 
737
        return self._inventory
 
738
 
 
739
    inventory = property(_get_inventory,
 
740
                         doc="Inventory of this Tree")
 
741
 
 
742
    @needs_read_lock
 
743
    def path2id(self, path):
 
744
        """Return the id for path in this tree."""
 
745
        return self._inventory.path2id(path)
 
746
 
 
747
    def id2path(self, file_id):
 
748
        """Return the path for a file id.
 
749
 
 
750
        :raises NoSuchId:
 
751
        """
 
752
        return self.inventory.id2path(file_id)
 
753
 
 
754
    def has_id(self, file_id):
 
755
        return self.inventory.has_id(file_id)
 
756
 
 
757
    def has_or_had_id(self, file_id):
 
758
        return self.inventory.has_id(file_id)
 
759
 
 
760
    def __iter__(self):
 
761
        return iter(self.inventory)
 
762
 
 
763
    def filter_unversioned_files(self, paths):
 
764
        """Filter out paths that are versioned.
 
765
 
 
766
        :return: set of paths.
 
767
        """
 
768
        # NB: we specifically *don't* call self.has_filename, because for
 
769
        # WorkingTrees that can indicate files that exist on disk but that
 
770
        # are not versioned.
 
771
        pred = self.inventory.has_filename
 
772
        return set((p for p in paths if not pred(p)))
 
773
 
 
774
    @needs_read_lock
 
775
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
 
776
        """Walk the tree in 'by_dir' order.
 
777
 
 
778
        This will yield each entry in the tree as a (path, entry) tuple.
 
779
        The order that they are yielded is:
 
780
 
 
781
        See Tree.iter_entries_by_dir for details.
 
782
 
 
783
        :param yield_parents: If True, yield the parents from the root leading
 
784
            down to specific_file_ids that have been requested. This has no
 
785
            impact if specific_file_ids is None.
 
786
        """
 
787
        return self.inventory.iter_entries_by_dir(
 
788
            specific_file_ids=specific_file_ids, yield_parents=yield_parents)
 
789
 
 
790
    def get_file_by_path(self, path):
 
791
        return self.get_file(self._inventory.path2id(path), path)
 
792
 
 
793
 
686
794
######################################################################
687
795
# diff
688
796
 
736
844
    return 'wtf?'
737
845
 
738
846
 
739
 
@deprecated_function(deprecated_in((1, 9, 0)))
740
 
def find_renames(old_inv, new_inv):
741
 
    for file_id in old_inv:
742
 
        if file_id not in new_inv:
743
 
            continue
744
 
        old_name = old_inv.id2path(file_id)
745
 
        new_name = new_inv.id2path(file_id)
746
 
        if old_name != new_name:
747
 
            yield (old_name, new_name)
748
 
 
749
 
 
750
847
def find_ids_across_trees(filenames, trees, require_versioned=True):
751
848
    """Find the ids corresponding to specified filenames.
752
849
 
810
907
        new_pending = set()
811
908
        for file_id in pending:
812
909
            for tree in trees:
813
 
                if not tree.has_id(file_id):
 
910
                if not tree.has_or_had_id(file_id):
814
911
                    continue
815
912
                for child_id in tree.iter_children(file_id):
816
913
                    if child_id not in interesting_ids:
831
928
    will pass through to InterTree as appropriate.
832
929
    """
833
930
 
 
931
    # Formats that will be used to test this InterTree. If both are
 
932
    # None, this InterTree will not be tested (e.g. because a complex
 
933
    # setup is required)
 
934
    _matching_from_tree_format = None
 
935
    _matching_to_tree_format = None
 
936
 
834
937
    _optimisers = []
835
938
 
 
939
    def _changes_from_entries(self, source_entry, target_entry,
 
940
        source_path=None, target_path=None):
 
941
        """Generate a iter_changes tuple between source_entry and target_entry.
 
942
 
 
943
        :param source_entry: An inventory entry from self.source, or None.
 
944
        :param target_entry: An inventory entry from self.target, or None.
 
945
        :param source_path: The path of source_entry, if known. If not known
 
946
            it will be looked up.
 
947
        :param target_path: The path of target_entry, if known. If not known
 
948
            it will be looked up.
 
949
        :return: A tuple, item 0 of which is an iter_changes result tuple, and
 
950
            item 1 is True if there are any changes in the result tuple.
 
951
        """
 
952
        if source_entry is None:
 
953
            if target_entry is None:
 
954
                return None
 
955
            file_id = target_entry.file_id
 
956
        else:
 
957
            file_id = source_entry.file_id
 
958
        if source_entry is not None:
 
959
            source_versioned = True
 
960
            source_name = source_entry.name
 
961
            source_parent = source_entry.parent_id
 
962
            if source_path is None:
 
963
                source_path = self.source.id2path(file_id)
 
964
            source_kind, source_executable, source_stat = \
 
965
                self.source._comparison_data(source_entry, source_path)
 
966
        else:
 
967
            source_versioned = False
 
968
            source_name = None
 
969
            source_parent = None
 
970
            source_kind = None
 
971
            source_executable = None
 
972
        if target_entry is not None:
 
973
            target_versioned = True
 
974
            target_name = target_entry.name
 
975
            target_parent = target_entry.parent_id
 
976
            if target_path is None:
 
977
                target_path = self.target.id2path(file_id)
 
978
            target_kind, target_executable, target_stat = \
 
979
                self.target._comparison_data(target_entry, target_path)
 
980
        else:
 
981
            target_versioned = False
 
982
            target_name = None
 
983
            target_parent = None
 
984
            target_kind = None
 
985
            target_executable = None
 
986
        versioned = (source_versioned, target_versioned)
 
987
        kind = (source_kind, target_kind)
 
988
        changed_content = False
 
989
        if source_kind != target_kind:
 
990
            changed_content = True
 
991
        elif source_kind == 'file':
 
992
            if (self.source.get_file_sha1(file_id, source_path, source_stat) !=
 
993
                self.target.get_file_sha1(file_id, target_path, target_stat)):
 
994
                changed_content = True
 
995
        elif source_kind == 'symlink':
 
996
            if (self.source.get_symlink_target(file_id) !=
 
997
                self.target.get_symlink_target(file_id)):
 
998
                changed_content = True
 
999
            # XXX: Yes, the indentation below is wrong. But fixing it broke
 
1000
            # test_merge.TestMergerEntriesLCAOnDisk.
 
1001
            # test_nested_tree_subtree_renamed_and_modified. We'll wait for
 
1002
            # the fix from bzr.dev -- vila 2009026
 
1003
            elif source_kind == 'tree-reference':
 
1004
                if (self.source.get_reference_revision(file_id, source_path)
 
1005
                    != self.target.get_reference_revision(file_id, target_path)):
 
1006
                    changed_content = True
 
1007
        parent = (source_parent, target_parent)
 
1008
        name = (source_name, target_name)
 
1009
        executable = (source_executable, target_executable)
 
1010
        if (changed_content is not False or versioned[0] != versioned[1]
 
1011
            or parent[0] != parent[1] or name[0] != name[1] or
 
1012
            executable[0] != executable[1]):
 
1013
            changes = True
 
1014
        else:
 
1015
            changes = False
 
1016
        return (file_id, (source_path, target_path), changed_content,
 
1017
                versioned, parent, name, kind, executable), changes
 
1018
 
836
1019
    @needs_read_lock
837
1020
    def compare(self, want_unchanged=False, specific_files=None,
838
1021
        extra_trees=None, require_versioned=False, include_root=False,
853
1036
            a PathsNotVersionedError will be thrown.
854
1037
        :param want_unversioned: Scan for unversioned paths.
855
1038
        """
856
 
        # NB: show_status depends on being able to pass in non-versioned files
857
 
        # and report them as unknown
858
1039
        trees = (self.source,)
859
1040
        if extra_trees is not None:
860
1041
            trees = trees + tuple(extra_trees)
865
1046
            # All files are unversioned, so just return an empty delta
866
1047
            # _compare_trees would think we want a complete delta
867
1048
            result = delta.TreeDelta()
868
 
            fake_entry = InventoryFile('unused', 'unused', 'unused')
 
1049
            fake_entry = inventory.InventoryFile('unused', 'unused', 'unused')
869
1050
            result.unversioned = [(path, None,
870
1051
                self.target._comparison_data(fake_entry, path)[0]) for path in
871
1052
                specific_files]
901
1082
        :param require_versioned: Raise errors.PathsNotVersionedError if a
902
1083
            path in the specific_files list is not versioned in one of
903
1084
            source, target or extra_trees.
 
1085
        :param specific_files: An optional list of file paths to restrict the
 
1086
            comparison to. When mapping filenames to ids, all matches in all
 
1087
            trees (including optional extra_trees) are used, and all children
 
1088
            of matched directories are included. The parents in the target tree
 
1089
            of the specific files up to and including the root of the tree are
 
1090
            always evaluated for changes too.
904
1091
        :param want_unversioned: Should unversioned files be returned in the
905
1092
            output. An unversioned file is defined as one with (False, False)
906
1093
            for the versioned pair.
908
1095
        lookup_trees = [self.source]
909
1096
        if extra_trees:
910
1097
             lookup_trees.extend(extra_trees)
 
1098
        # The ids of items we need to examine to insure delta consistency.
 
1099
        precise_file_ids = set()
 
1100
        changed_file_ids = []
911
1101
        if specific_files == []:
912
1102
            specific_file_ids = []
913
1103
        else:
914
1104
            specific_file_ids = self.target.paths2ids(specific_files,
915
1105
                lookup_trees, require_versioned=require_versioned)
 
1106
        if specific_files is not None:
 
1107
            # reparented or added entries must have their parents included
 
1108
            # so that valid deltas can be created. The seen_parents set
 
1109
            # tracks the parents that we need to have.
 
1110
            # The seen_dirs set tracks directory entries we've yielded.
 
1111
            # After outputting version object in to_entries we set difference
 
1112
            # the two seen sets and start checking parents.
 
1113
            seen_parents = set()
 
1114
            seen_dirs = set()
916
1115
        if want_unversioned:
917
1116
            all_unversioned = sorted([(p.split('/'), p) for p in
918
1117
                                     self.target.extras()
919
1118
                if specific_files is None or
920
1119
                    osutils.is_inside_any(specific_files, p)])
921
 
            all_unversioned = deque(all_unversioned)
 
1120
            all_unversioned = collections.deque(all_unversioned)
922
1121
        else:
923
 
            all_unversioned = deque()
 
1122
            all_unversioned = collections.deque()
924
1123
        to_paths = {}
925
1124
        from_entries_by_dir = list(self.source.iter_entries_by_dir(
926
1125
            specific_file_ids=specific_file_ids))
932
1131
        # the unversioned path lookup only occurs on real trees - where there
933
1132
        # can be extras. So the fake_entry is solely used to look up
934
1133
        # executable it values when execute is not supported.
935
 
        fake_entry = InventoryFile('unused', 'unused', 'unused')
936
 
        for to_path, to_entry in to_entries_by_dir:
937
 
            while all_unversioned and all_unversioned[0][0] < to_path.split('/'):
 
1134
        fake_entry = inventory.InventoryFile('unused', 'unused', 'unused')
 
1135
        for target_path, target_entry in to_entries_by_dir:
 
1136
            while (all_unversioned and
 
1137
                all_unversioned[0][0] < target_path.split('/')):
938
1138
                unversioned_path = all_unversioned.popleft()
939
 
                to_kind, to_executable, to_stat = \
 
1139
                target_kind, target_executable, target_stat = \
940
1140
                    self.target._comparison_data(fake_entry, unversioned_path[1])
941
1141
                yield (None, (None, unversioned_path[1]), True, (False, False),
942
1142
                    (None, None),
943
1143
                    (None, unversioned_path[0][-1]),
944
 
                    (None, to_kind),
945
 
                    (None, to_executable))
946
 
            file_id = to_entry.file_id
947
 
            to_paths[file_id] = to_path
 
1144
                    (None, target_kind),
 
1145
                    (None, target_executable))
 
1146
            source_path, source_entry = from_data.get(target_entry.file_id,
 
1147
                (None, None))
 
1148
            result, changes = self._changes_from_entries(source_entry,
 
1149
                target_entry, source_path=source_path, target_path=target_path)
 
1150
            to_paths[result[0]] = result[1][1]
948
1151
            entry_count += 1
949
 
            changed_content = False
950
 
            from_path, from_entry = from_data.get(file_id, (None, None))
951
 
            from_versioned = (from_entry is not None)
952
 
            if from_entry is not None:
953
 
                from_versioned = True
954
 
                from_name = from_entry.name
955
 
                from_parent = from_entry.parent_id
956
 
                from_kind, from_executable, from_stat = \
957
 
                    self.source._comparison_data(from_entry, from_path)
 
1152
            if result[3][0]:
958
1153
                entry_count += 1
959
 
            else:
960
 
                from_versioned = False
961
 
                from_kind = None
962
 
                from_parent = None
963
 
                from_name = None
964
 
                from_executable = None
965
 
            versioned = (from_versioned, True)
966
 
            to_kind, to_executable, to_stat = \
967
 
                self.target._comparison_data(to_entry, to_path)
968
 
            kind = (from_kind, to_kind)
969
 
            if kind[0] != kind[1]:
970
 
                changed_content = True
971
 
            elif from_kind == 'file':
972
 
                if (self.source.get_file_sha1(file_id, from_path, from_stat) !=
973
 
                    self.target.get_file_sha1(file_id, to_path, to_stat)):
974
 
                    changed_content = True
975
 
            elif from_kind == 'symlink':
976
 
                if (self.source.get_symlink_target(file_id) !=
977
 
                    self.target.get_symlink_target(file_id)):
978
 
                    changed_content = True
979
 
                # XXX: Yes, the indentation below is wrong. But fixing it broke
980
 
                # test_merge.TestMergerEntriesLCAOnDisk.
981
 
                # test_nested_tree_subtree_renamed_and_modified. We'll wait for
982
 
                # the fix from bzr.dev -- vila 2009026
983
 
                elif from_kind == 'tree-reference':
984
 
                    if (self.source.get_reference_revision(file_id, from_path)
985
 
                        != self.target.get_reference_revision(file_id, to_path)):
986
 
                        changed_content = True
987
 
            parent = (from_parent, to_entry.parent_id)
988
 
            name = (from_name, to_entry.name)
989
 
            executable = (from_executable, to_executable)
990
1154
            if pb is not None:
991
1155
                pb.update('comparing files', entry_count, num_entries)
992
 
            if (changed_content is not False or versioned[0] != versioned[1]
993
 
                or parent[0] != parent[1] or name[0] != name[1] or
994
 
                executable[0] != executable[1] or include_unchanged):
995
 
                yield (file_id, (from_path, to_path), changed_content,
996
 
                    versioned, parent, name, kind, executable)
997
 
 
 
1156
            if changes or include_unchanged:
 
1157
                if specific_file_ids is not None:
 
1158
                    new_parent_id = result[4][1]
 
1159
                    precise_file_ids.add(new_parent_id)
 
1160
                    changed_file_ids.append(result[0])
 
1161
                yield result
 
1162
            # Ensure correct behaviour for reparented/added specific files.
 
1163
            if specific_files is not None:
 
1164
                # Record output dirs
 
1165
                if result[6][1] == 'directory':
 
1166
                    seen_dirs.add(result[0])
 
1167
                # Record parents of reparented/added entries.
 
1168
                versioned = result[3]
 
1169
                parents = result[4]
 
1170
                if not versioned[0] or parents[0] != parents[1]:
 
1171
                    seen_parents.add(parents[1])
998
1172
        while all_unversioned:
999
1173
            # yield any trailing unversioned paths
1000
1174
            unversioned_path = all_unversioned.popleft()
1005
1179
                (None, unversioned_path[0][-1]),
1006
1180
                (None, to_kind),
1007
1181
                (None, to_executable))
1008
 
 
1009
 
        def get_to_path(to_entry):
1010
 
            if to_entry.parent_id is None:
1011
 
                to_path = '' # the root
1012
 
            else:
1013
 
                if to_entry.parent_id not in to_paths:
1014
 
                    # recurse up
1015
 
                    return get_to_path(self.target.inventory[to_entry.parent_id])
1016
 
                to_path = osutils.pathjoin(to_paths[to_entry.parent_id],
1017
 
                                           to_entry.name)
1018
 
            to_paths[to_entry.file_id] = to_path
1019
 
            return to_path
1020
 
 
 
1182
        # Yield all remaining source paths
1021
1183
        for path, from_entry in from_entries_by_dir:
1022
1184
            file_id = from_entry.file_id
1023
1185
            if file_id in to_paths:
1024
1186
                # already returned
1025
1187
                continue
1026
 
            if not file_id in self.target.all_file_ids():
 
1188
            if not self.target.has_id(file_id):
1027
1189
                # common case - paths we have not emitted are not present in
1028
1190
                # target.
1029
1191
                to_path = None
1030
1192
            else:
1031
 
                to_path = get_to_path(self.target.inventory[file_id])
 
1193
                to_path = self.target.id2path(file_id)
1032
1194
            entry_count += 1
1033
1195
            if pb is not None:
1034
1196
                pb.update('comparing files', entry_count, num_entries)
1041
1203
            executable = (from_executable, None)
1042
1204
            changed_content = from_kind is not None
1043
1205
            # the parent's path is necessarily known at this point.
 
1206
            changed_file_ids.append(file_id)
1044
1207
            yield(file_id, (path, to_path), changed_content, versioned, parent,
1045
1208
                  name, kind, executable)
 
1209
        changed_file_ids = set(changed_file_ids)
 
1210
        if specific_file_ids is not None:
 
1211
            for result in self._handle_precise_ids(precise_file_ids,
 
1212
                changed_file_ids):
 
1213
                yield result
 
1214
 
 
1215
    def _get_entry(self, tree, file_id):
 
1216
        """Get an inventory entry from a tree, with missing entries as None.
 
1217
 
 
1218
        If the tree raises NotImplementedError on accessing .inventory, then
 
1219
        this is worked around using iter_entries_by_dir on just the file id
 
1220
        desired.
 
1221
 
 
1222
        :param tree: The tree to lookup the entry in.
 
1223
        :param file_id: The file_id to lookup.
 
1224
        """
 
1225
        try:
 
1226
            inventory = tree.inventory
 
1227
        except NotImplementedError:
 
1228
            # No inventory available.
 
1229
            try:
 
1230
                iterator = tree.iter_entries_by_dir(specific_file_ids=[file_id])
 
1231
                return iterator.next()[1]
 
1232
            except StopIteration:
 
1233
                return None
 
1234
        else:
 
1235
            try:
 
1236
                return inventory[file_id]
 
1237
            except errors.NoSuchId:
 
1238
                return None
 
1239
 
 
1240
    def _handle_precise_ids(self, precise_file_ids, changed_file_ids,
 
1241
        discarded_changes=None):
 
1242
        """Fill out a partial iter_changes to be consistent.
 
1243
 
 
1244
        :param precise_file_ids: The file ids of parents that were seen during
 
1245
            the iter_changes.
 
1246
        :param changed_file_ids: The file ids of already emitted items.
 
1247
        :param discarded_changes: An optional dict of precalculated
 
1248
            iter_changes items which the partial iter_changes had not output
 
1249
            but had calculated.
 
1250
        :return: A generator of iter_changes items to output.
 
1251
        """
 
1252
        # process parents of things that had changed under the users
 
1253
        # requested paths to prevent incorrect paths or parent ids which
 
1254
        # aren't in the tree.
 
1255
        while precise_file_ids:
 
1256
            precise_file_ids.discard(None)
 
1257
            # Don't emit file_ids twice
 
1258
            precise_file_ids.difference_update(changed_file_ids)
 
1259
            if not precise_file_ids:
 
1260
                break
 
1261
            # If the there was something at a given output path in source, we
 
1262
            # have to include the entry from source in the delta, or we would
 
1263
            # be putting this entry into a used path.
 
1264
            paths = []
 
1265
            for parent_id in precise_file_ids:
 
1266
                try:
 
1267
                    paths.append(self.target.id2path(parent_id))
 
1268
                except errors.NoSuchId:
 
1269
                    # This id has been dragged in from the source by delta
 
1270
                    # expansion and isn't present in target at all: we don't
 
1271
                    # need to check for path collisions on it.
 
1272
                    pass
 
1273
            for path in paths:
 
1274
                old_id = self.source.path2id(path)
 
1275
                precise_file_ids.add(old_id)
 
1276
            precise_file_ids.discard(None)
 
1277
            current_ids = precise_file_ids
 
1278
            precise_file_ids = set()
 
1279
            # We have to emit all of precise_file_ids that have been altered.
 
1280
            # We may have to output the children of some of those ids if any
 
1281
            # directories have stopped being directories.
 
1282
            for file_id in current_ids:
 
1283
                # Examine file_id
 
1284
                if discarded_changes:
 
1285
                    result = discarded_changes.get(file_id)
 
1286
                    old_entry = None
 
1287
                else:
 
1288
                    result = None
 
1289
                if result is None:
 
1290
                    old_entry = self._get_entry(self.source, file_id)
 
1291
                    new_entry = self._get_entry(self.target, file_id)
 
1292
                    result, changes = self._changes_from_entries(
 
1293
                        old_entry, new_entry)
 
1294
                else:
 
1295
                    changes = True
 
1296
                # Get this parents parent to examine.
 
1297
                new_parent_id = result[4][1]
 
1298
                precise_file_ids.add(new_parent_id)
 
1299
                if changes:
 
1300
                    if (result[6][0] == 'directory' and
 
1301
                        result[6][1] != 'directory'):
 
1302
                        # This stopped being a directory, the old children have
 
1303
                        # to be included.
 
1304
                        if old_entry is None:
 
1305
                            # Reusing a discarded change.
 
1306
                            old_entry = self._get_entry(self.source, file_id)
 
1307
                        for child in old_entry.children.values():
 
1308
                            precise_file_ids.add(child.file_id)
 
1309
                    changed_file_ids.add(result[0])
 
1310
                    yield result
1046
1311
 
1047
1312
 
1048
1313
class MultiWalker(object):