~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tree.py

  • Committer: Vincent Ladeuil
  • Date: 2009-07-02 13:07:14 UTC
  • mto: (4524.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4525.
  • Revision ID: v.ladeuil+lp@free.fr-20090702130714-hsyqfusi8vn3a11m
Use tree.has_changes() where appropriate (the test suite caught a
bug in has_changes() (not filtering out the root) in an impressive
number of tests)

* bzrlib/send.py:
(send): Use tree.has_changes() instead of tree.changes_from().

* bzrlib/reconfigure.py:
(Reconfigure._check): Use tree.has_changes() instead of
tree.changes_from().

* bzrlib/merge.py:
(Merger.ensure_revision_trees, Merger.compare_basis): Use
tree.has_changes() instead of tree.changes_from().

* bzrlib/builtins.py:
(cmd_remove_tree.run, cmd_push.run, cmd_merge.run): Use
tree.has_changes() instead of tree.changes_from().

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
 
1
# Copyright (C) 2005, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""Tree classes, representing directory at point in time.
18
18
"""
24
24
import bzrlib
25
25
from bzrlib import (
26
26
    conflicts as _mod_conflicts,
 
27
    debug,
27
28
    delta,
 
29
    filters,
28
30
    osutils,
29
31
    revision as _mod_revision,
30
32
    rules,
45
47
    """Abstract file tree.
46
48
 
47
49
    There are several subclasses:
48
 
    
 
50
 
49
51
    * `WorkingTree` exists as files on disk editable by the user.
50
52
 
51
53
    * `RevisionTree` is a tree as recorded at some point in the past.
60
62
    Trees can be compared, etc, regardless of whether they are working
61
63
    trees or versioned trees.
62
64
    """
63
 
    
 
65
 
64
66
    def changes_from(self, other, want_unchanged=False, specific_files=None,
65
67
        extra_trees=None, require_versioned=False, include_root=False,
66
68
        want_unversioned=False):
80
82
            a PathsNotVersionedError will be thrown.
81
83
        :param want_unversioned: Scan for unversioned paths.
82
84
 
83
 
        The comparison will be performed by an InterTree object looked up on 
 
85
        The comparison will be performed by an InterTree object looked up on
84
86
        self and other.
85
87
        """
86
88
        # Martin observes that Tree.changes_from returns a TreeDelta and this
95
97
            want_unversioned=want_unversioned,
96
98
            )
97
99
 
98
 
    @symbol_versioning.deprecated_method(symbol_versioning.one_three)
99
 
    def _iter_changes(self, *args, **kwargs):
100
 
        return self.iter_changes(*args, **kwargs)
101
 
 
102
100
    def iter_changes(self, from_tree, include_unchanged=False,
103
101
                     specific_files=None, pb=None, extra_trees=None,
104
102
                     require_versioned=True, want_unversioned=False):
105
103
        intertree = InterTree.get(from_tree, self)
106
104
        return intertree.iter_changes(include_unchanged, specific_files, pb,
107
105
            extra_trees, require_versioned, want_unversioned=want_unversioned)
108
 
    
 
106
 
 
107
 
 
108
    @needs_read_lock
 
109
    def has_changes(self, from_tree):
 
110
        """Quickly check that the tree contains at least one change.
 
111
 
 
112
        :return: True if a change is found. False otherwise
 
113
        """
 
114
        changes = self.iter_changes(from_tree)
 
115
        try:
 
116
            change = changes.next()
 
117
            # Exclude root (talk about black magic... --vila 20090629)
 
118
            if change[4] == (None, None):
 
119
                change = changes.next()
 
120
            return True
 
121
        except StopIteration:
 
122
            # No changes
 
123
            return False
 
124
 
109
125
    def conflicts(self):
110
126
        """Get a list of the conflicts in the tree.
111
127
 
118
134
        return []
119
135
 
120
136
    def get_parent_ids(self):
121
 
        """Get the parent ids for this tree. 
 
137
        """Get the parent ids for this tree.
122
138
 
123
139
        :return: a list of parent ids. [] is returned to indicate
124
140
        a tree with no parents.
125
141
        :raises: BzrError if the parents are not known.
126
142
        """
127
143
        raise NotImplementedError(self.get_parent_ids)
128
 
    
 
144
 
129
145
    def has_filename(self, filename):
130
146
        """True if the tree has given filename."""
131
147
        raise NotImplementedError(self.has_filename)
165
181
 
166
182
    def is_control_filename(self, filename):
167
183
        """True if filename is the name of a control file in this tree.
168
 
        
 
184
 
169
185
        :param filename: A filename within the tree. This is a relative path
170
186
        from the root of this tree.
171
187
 
204
220
            specific_file_ids=specific_file_ids)
205
221
 
206
222
    def iter_references(self):
207
 
        for path, entry in self.iter_entries_by_dir():
208
 
            if entry.kind == 'tree-reference':
209
 
                yield path, entry.file_id
 
223
        if self.supports_tree_reference():
 
224
            for path, entry in self.iter_entries_by_dir():
 
225
                if entry.kind == 'tree-reference':
 
226
                    yield path, entry.file_id
210
227
 
211
228
    def kind(self, file_id):
212
229
        raise NotImplementedError("Tree subclass %s must implement kind"
222
239
 
223
240
    def path_content_summary(self, path):
224
241
        """Get a summary of the information about path.
225
 
        
 
242
 
226
243
        :param path: A relative path within the tree.
227
244
        :return: A tuple containing kind, size, exec, sha1-or-link.
228
245
            Kind is always present (see tree.kind()).
255
272
 
256
273
    def _get_inventory(self):
257
274
        return self._inventory
258
 
    
 
275
 
259
276
    def get_file(self, file_id, path=None):
260
277
        """Return a file object for the file file_id in the tree.
261
 
        
 
278
 
262
279
        If both file_id and path are defined, it is implementation defined as
263
280
        to which one is used.
264
281
        """
265
282
        raise NotImplementedError(self.get_file)
266
283
 
 
284
    def get_file_with_stat(self, file_id, path=None):
 
285
        """Get a file handle and stat object for file_id.
 
286
 
 
287
        The default implementation returns (self.get_file, None) for backwards
 
288
        compatibility.
 
289
 
 
290
        :param file_id: The file id to read.
 
291
        :param path: The path of the file, if it is known.
 
292
        :return: A tuple (file_handle, stat_value_or_None). If the tree has
 
293
            no stat facility, or need for a stat cache feedback during commit,
 
294
            it may return None for the second element of the tuple.
 
295
        """
 
296
        return (self.get_file(file_id, path), None)
 
297
 
267
298
    def get_file_text(self, file_id, path=None):
268
299
        """Return the byte content of a file.
269
300
 
500
531
 
501
532
    def _check_retrieved(self, ie, f):
502
533
        if not __debug__:
503
 
            return  
 
534
            return
504
535
        fp = fingerprint_file(f)
505
536
        f.seek(0)
506
 
        
 
537
 
507
538
        if ie.text_size is not None:
508
539
            if ie.text_size != fp['size']:
509
540
                raise BzrError("mismatched size for file %r in %r" % (ie.file_id, self._store),
524
555
 
525
556
    def paths2ids(self, paths, trees=[], require_versioned=True):
526
557
        """Return all the ids that can be reached by walking from paths.
527
 
        
 
558
 
528
559
        Each path is looked up in this tree and any extras provided in
529
560
        trees, and this is repeated recursively: the children in an extra tree
530
561
        of a directory that has been renamed under a provided path in this tree
546
577
        for child in getattr(entry, 'children', {}).itervalues():
547
578
            yield child.file_id
548
579
 
549
 
    @symbol_versioning.deprecated_method(symbol_versioning.one_six)
550
 
    def print_file(self, file_id):
551
 
        """Print file with id `file_id` to stdout."""
552
 
        import sys
553
 
        sys.stdout.write(self.get_file_text(file_id))
554
 
 
555
580
    def lock_read(self):
556
581
        pass
557
582
 
560
585
 
561
586
        The intention of this method is to allow access to possibly cached
562
587
        tree data. Implementors of this method should raise NoSuchRevision if
563
 
        the tree is not locally available, even if they could obtain the 
564
 
        tree via a repository or some other means. Callers are responsible 
 
588
        the tree is not locally available, even if they could obtain the
 
589
        tree via a repository or some other means. Callers are responsible
565
590
        for finding the ultimate source for a revision tree.
566
591
 
567
592
        :param revision_id: The revision_id of the requested tree.
572
597
 
573
598
    def unknowns(self):
574
599
        """What files are present in this tree and unknown.
575
 
        
 
600
 
576
601
        :return: an iterator over the unknown files.
577
602
        """
578
603
        return iter([])
586
611
        :return: set of paths.
587
612
        """
588
613
        # NB: we specifically *don't* call self.has_filename, because for
589
 
        # WorkingTrees that can indicate files that exist on disk but that 
 
614
        # WorkingTrees that can indicate files that exist on disk but that
590
615
        # are not versioned.
591
616
        pred = self.inventory.has_filename
592
617
        return set((p for p in paths if not pred(p)))
597
622
        This yields all the data about the contents of a directory at a time.
598
623
        After each directory has been yielded, if the caller has mutated the
599
624
        list to exclude some directories, they are then not descended into.
600
 
        
 
625
 
601
626
        The data yielded is of the form:
602
627
        ((directory-relpath, directory-path-from-root, directory-fileid),
603
 
        [(relpath, basename, kind, lstat, path_from_tree_root, file_id, 
 
628
        [(relpath, basename, kind, lstat, path_from_tree_root, file_id,
604
629
          versioned_kind), ...]),
605
630
         - directory-relpath is the containing dirs relpath from prefix
606
631
         - directory-path-from-root is the containing dirs path from /
613
638
         - lstat is the stat data *if* the file was statted.
614
639
         - path_from_tree_root is the path from the root of the tree.
615
640
         - file_id is the file_id if the entry is versioned.
616
 
         - versioned_kind is the kind of the file as last recorded in the 
 
641
         - versioned_kind is the kind of the file as last recorded in the
617
642
           versioning system. If 'unknown' the file is not versioned.
618
643
        One of 'kind' and 'versioned_kind' must not be 'unknown'.
619
644
 
627
652
    def supports_content_filtering(self):
628
653
        return False
629
654
 
 
655
    def _content_filter_stack(self, path=None, file_id=None):
 
656
        """The stack of content filters for a path if filtering is supported.
 
657
 
 
658
        Readers will be applied in first-to-last order.
 
659
        Writers will be applied in last-to-first order.
 
660
        Either the path or the file-id needs to be provided.
 
661
 
 
662
        :param path: path relative to the root of the tree
 
663
            or None if unknown
 
664
        :param file_id: file_id or None if unknown
 
665
        :return: the list of filters - [] if there are none
 
666
        """
 
667
        filter_pref_names = filters._get_registered_names()
 
668
        if len(filter_pref_names) == 0:
 
669
            return []
 
670
        if path is None:
 
671
            path = self.id2path(file_id)
 
672
        prefs = self.iter_search_rules([path], filter_pref_names).next()
 
673
        stk = filters._get_filter_stack_for(prefs)
 
674
        if 'filters' in debug.debug_flags:
 
675
            note("*** %s content-filter: %s => %r" % (path,prefs,stk))
 
676
        return stk
 
677
 
 
678
    def _content_filter_stack_provider(self):
 
679
        """A function that returns a stack of ContentFilters.
 
680
 
 
681
        The function takes a path (relative to the top of the tree) and a
 
682
        file-id as parameters.
 
683
 
 
684
        :return: None if content filtering is not supported by this tree.
 
685
        """
 
686
        if self.supports_content_filtering():
 
687
            return lambda path, file_id: \
 
688
                    self._content_filter_stack(path, file_id)
 
689
        else:
 
690
            return None
 
691
 
630
692
    def iter_search_rules(self, path_names, pref_names=None,
631
 
        _default_searcher=rules._per_user_searcher):
 
693
        _default_searcher=None):
632
694
        """Find the preferences for filenames in a tree.
633
695
 
634
696
        :param path_names: an iterable of paths to find attributes for.
638
700
        :return: an iterator of tuple sequences, one per path-name.
639
701
          See _RulesSearcher.get_items for details on the tuple sequence.
640
702
        """
 
703
        if _default_searcher is None:
 
704
            _default_searcher = rules._per_user_searcher
641
705
        searcher = self._get_rules_searcher(_default_searcher)
642
706
        if searcher is not None:
643
707
            if pref_names is not None:
654
718
        return searcher
655
719
 
656
720
 
657
 
class EmptyTree(Tree):
658
 
 
659
 
    def __init__(self):
660
 
        self._inventory = Inventory(root_id=None)
661
 
        symbol_versioning.warn('EmptyTree is deprecated as of bzr 0.9 please'
662
 
                               ' use repository.revision_tree instead.',
663
 
                               DeprecationWarning, stacklevel=2)
664
 
 
665
 
    def get_parent_ids(self):
666
 
        return []
667
 
 
668
 
    def get_symlink_target(self, file_id):
669
 
        return None
670
 
 
671
 
    def has_filename(self, filename):
672
 
        return False
673
 
 
674
 
    def kind(self, file_id):
675
 
        return "directory"
676
 
 
677
 
    def list_files(self, include_root=False):
678
 
        return iter([])
679
 
    
680
 
    def __contains__(self, file_id):
681
 
        return (file_id in self._inventory)
682
 
 
683
 
    def get_file_sha1(self, file_id, path=None, stat_value=None):
684
 
        return None
685
 
 
686
 
 
687
721
######################################################################
688
722
# diff
689
723
 
736
770
 
737
771
    return 'wtf?'
738
772
 
739
 
    
 
773
 
740
774
@deprecated_function(deprecated_in((1, 9, 0)))
741
775
def find_renames(old_inv, new_inv):
742
776
    for file_id in old_inv:
750
784
 
751
785
def find_ids_across_trees(filenames, trees, require_versioned=True):
752
786
    """Find the ids corresponding to specified filenames.
753
 
    
 
787
 
754
788
    All matches in all trees will be used, and all children of matched
755
789
    directories will be used.
756
790
 
770
804
 
771
805
def _find_ids_across_trees(filenames, trees, require_versioned):
772
806
    """Find the ids corresponding to specified filenames.
773
 
    
 
807
 
774
808
    All matches in all trees will be used, but subdirectories are not scanned.
775
809
 
776
810
    :param filenames: The filenames to find file_ids for
797
831
 
798
832
def _find_children_across_trees(specified_ids, trees):
799
833
    """Return a set including specified ids and their children.
800
 
    
 
834
 
801
835
    All matches in all trees will be used.
802
836
 
803
837
    :param trees: The trees to find file_ids within
804
 
    :return: a set containing all specified ids and their children 
 
838
    :return: a set containing all specified ids and their children
805
839
    """
806
840
    interesting_ids = set(specified_ids)
807
841
    pending = interesting_ids
906
940
            output. An unversioned file is defined as one with (False, False)
907
941
            for the versioned pair.
908
942
        """
909
 
        result = []
910
943
        lookup_trees = [self.source]
911
944
        if extra_trees:
912
945
             lookup_trees.extend(extra_trees)
931
964
            specific_file_ids=specific_file_ids))
932
965
        num_entries = len(from_entries_by_dir) + len(to_entries_by_dir)
933
966
        entry_count = 0
934
 
        # the unversioned path lookup only occurs on real trees - where there 
 
967
        # the unversioned path lookup only occurs on real trees - where there
935
968
        # can be extras. So the fake_entry is solely used to look up
936
969
        # executable it values when execute is not supported.
937
970
        fake_entry = InventoryFile('unused', 'unused', 'unused')
971
1004
            if kind[0] != kind[1]:
972
1005
                changed_content = True
973
1006
            elif from_kind == 'file':
974
 
                from_size = self.source._file_size(from_entry, from_stat)
975
 
                to_size = self.target._file_size(to_entry, to_stat)
976
 
                if from_size != to_size:
977
 
                    changed_content = True
978
 
                elif (self.source.get_file_sha1(file_id, from_path, from_stat) !=
 
1007
                if (self.source.get_file_sha1(file_id, from_path, from_stat) !=
979
1008
                    self.target.get_file_sha1(file_id, to_path, to_stat)):
980
1009
                    changed_content = True
981
1010
            elif from_kind == 'symlink':
982
1011
                if (self.source.get_symlink_target(file_id) !=
983
1012
                    self.target.get_symlink_target(file_id)):
984
1013
                    changed_content = True
 
1014
                # XXX: Yes, the indentation below is wrong. But fixing it broke
 
1015
                # test_merge.TestMergerEntriesLCAOnDisk.
 
1016
                # test_nested_tree_subtree_renamed_and_modified. We'll wait for
 
1017
                # the fix from bzr.dev -- vila 2009026
985
1018
                elif from_kind == 'tree-reference':
986
1019
                    if (self.source.get_reference_revision(file_id, from_path)
987
1020
                        != self.target.get_reference_revision(file_id, to_path)):
988
 
                        changed_content = True 
 
1021
                        changed_content = True
989
1022
            parent = (from_parent, to_entry.parent_id)
990
1023
            name = (from_name, to_entry.name)
991
1024
            executable = (from_executable, to_executable)
992
1025
            if pb is not None:
993
1026
                pb.update('comparing files', entry_count, num_entries)
994
1027
            if (changed_content is not False or versioned[0] != versioned[1]
995
 
                or parent[0] != parent[1] or name[0] != name[1] or 
 
1028
                or parent[0] != parent[1] or name[0] != name[1] or
996
1029
                executable[0] != executable[1] or include_unchanged):
997
1030
                yield (file_id, (from_path, to_path), changed_content,
998
1031
                    versioned, parent, name, kind, executable)
1167
1200
 
1168
1201
    def _walk_master_tree(self):
1169
1202
        """First pass, walk all trees in lock-step.
1170
 
        
 
1203
 
1171
1204
        When we are done, all nodes in the master_tree will have been
1172
1205
        processed. _other_walkers, _other_entries, and _others_extra will be
1173
1206
        set on 'self' for future processing.