/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4454.3.1 by John Arbash Meinel
Initial api for Annotator.
1
# Copyright (C) 2009 Canonical Ltd
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
17
"""Functionality for doing annotations in the 'optimal' way"""
18
19
from bzrlib import (
20
    errors,
21
    graph as _mod_graph,
22
    osutils,
4454.3.3 by John Arbash Meinel
Start implementing the reannotation functionality directly.
23
    patiencediff,
4454.3.21 by John Arbash Meinel
Assert that entries in the annotation cache also get cleaned up.
24
    ui,
4454.3.1 by John Arbash Meinel
Initial api for Annotator.
25
    )
26
27
28
class AnnotatorPolicy(object):
29
    """Variables that define annotations."""
30
31
32
class Annotator(object):
33
    """Class that drives performing annotations."""
34
35
    def __init__(self, vf):
36
        """Create a new Annotator from a VersionedFile."""
37
        self._vf = vf
4454.3.2 by John Arbash Meinel
Start moving bits into helper functions. Add tests for multiple revs.
38
        self._parent_map = {}
4454.3.8 by John Arbash Meinel
Factor out the 'get the lines to annotate' into a helper.
39
        self._text_cache = {}
4454.3.18 by John Arbash Meinel
Start tracking the number of children that need a given text.
40
        # Map from key => number of nexts that will be built from this key
41
        self._num_needed_children = {}
4454.3.3 by John Arbash Meinel
Start implementing the reannotation functionality directly.
42
        self._annotations_cache = {}
4454.3.41 by John Arbash Meinel
Cache the heads provider as long as we know that the parent_map hasn't changed.
43
        self._heads_provider = None
4454.3.1 by John Arbash Meinel
Initial api for Annotator.
44
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
45
    def _update_needed_children(self, key, parent_keys):
46
        for parent_key in parent_keys:
47
            if parent_key in self._num_needed_children:
48
                self._num_needed_children[parent_key] += 1
49
            else:
50
                self._num_needed_children[parent_key] = 1
51
4454.3.18 by John Arbash Meinel
Start tracking the number of children that need a given text.
52
    def _get_needed_keys(self, key):
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
53
        """Determine the texts we need to get from the backing vf.
54
55
        :return: (vf_keys_needed, ann_keys_needed)
56
            vf_keys_needed  These are keys that we need to get from the vf
57
            ann_keys_needed Texts which we have in self._text_cache but we
58
                            don't have annotations for. We need to yield these
59
                            in the proper order so that we can get proper
60
                            annotations.
61
        """
62
        parent_map = self._parent_map
4454.3.18 by John Arbash Meinel
Start tracking the number of children that need a given text.
63
        # We need 1 extra copy of the node we will be looking at when we are
64
        # done
65
        self._num_needed_children[key] = 1
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
66
        vf_keys_needed = set()
67
        ann_keys_needed = set()
68
        needed_keys = set([key])
69
        while needed_keys:
70
            parent_lookup = []
71
            next_parent_map = {}
72
            for key in needed_keys:
73
                if key in self._parent_map:
74
                    # We don't need to lookup this key in the vf
75
                    if key not in self._text_cache:
76
                        # Extract this text from the vf
77
                        vf_keys_needed.add(key)
78
                    elif key not in self._annotations_cache:
79
                        # We do need to annotate
80
                        ann_keys_needed.add(key)
81
                        next_parent_map[key] = self._parent_map[key]
4454.3.18 by John Arbash Meinel
Start tracking the number of children that need a given text.
82
                else:
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
83
                    parent_lookup.append(key)
84
                    vf_keys_needed.add(key)
85
            needed_keys = set()
86
            next_parent_map.update(self._vf.get_parent_map(parent_lookup))
87
            for key, parent_keys in next_parent_map.iteritems():
4454.3.66 by John Arbash Meinel
Implement no-graph support for the Python version.
88
                if parent_keys is None: # No graph versionedfile
89
                    parent_keys = ()
90
                    next_parent_map[key] = ()
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
91
                self._update_needed_children(key, parent_keys)
92
                needed_keys.update([key for key in parent_keys
93
                                         if key not in parent_map])
94
            parent_map.update(next_parent_map)
95
            # _heads_provider does some graph caching, so it is only valid while
96
            # self._parent_map hasn't changed
97
            self._heads_provider = None
98
        return vf_keys_needed, ann_keys_needed
4454.3.18 by John Arbash Meinel
Start tracking the number of children that need a given text.
99
4454.3.21 by John Arbash Meinel
Assert that entries in the annotation cache also get cleaned up.
100
    def _get_needed_texts(self, key, pb=None):
4454.3.8 by John Arbash Meinel
Factor out the 'get the lines to annotate' into a helper.
101
        """Get the texts we need to properly annotate key.
102
103
        :param key: A Key that is present in self._vf
104
        :return: Yield (this_key, text, num_lines)
105
            'text' is an opaque object that just has to work with whatever
106
            matcher object we are using. Currently it is always 'lines' but
107
            future improvements may change this to a simple text string.
108
        """
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
109
        keys, ann_keys = self._get_needed_keys(key)
4454.3.21 by John Arbash Meinel
Assert that entries in the annotation cache also get cleaned up.
110
        if pb is not None:
111
            pb.update('getting stream', 0, len(keys))
112
        stream  = self._vf.get_record_stream(keys, 'topological', True)
113
        for idx, record in enumerate(stream):
114
            if pb is not None:
115
                pb.update('extracting', 0, len(keys))
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
116
            if record.storage_kind == 'absent':
117
                raise errors.RevisionNotPresent(record.key, self._vf)
4454.3.8 by John Arbash Meinel
Factor out the 'get the lines to annotate' into a helper.
118
            this_key = record.key
119
            lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
120
            num_lines = len(lines)
4454.3.16 by John Arbash Meinel
Move more access patterns into helper functions.
121
            self._text_cache[this_key] = lines
4454.3.8 by John Arbash Meinel
Factor out the 'get the lines to annotate' into a helper.
122
            yield this_key, lines, num_lines
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
123
        for key in ann_keys:
124
            lines = self._text_cache[key]
125
            num_lines = len(lines)
126
            yield key, lines, num_lines
4454.3.2 by John Arbash Meinel
Start moving bits into helper functions. Add tests for multiple revs.
127
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
128
    def _get_parent_annotations_and_matches(self, key, text, parent_key):
4454.3.9 by John Arbash Meinel
Remove heads_provider, as we don't use it now.
129
        """Get the list of annotations for the parent, and the matching lines.
4454.3.2 by John Arbash Meinel
Start moving bits into helper functions. Add tests for multiple revs.
130
4454.3.9 by John Arbash Meinel
Remove heads_provider, as we don't use it now.
131
        :param text: The opaque value given by _get_needed_texts
132
        :param parent_key: The key for the parent text
133
        :return: (parent_annotations, matching_blocks)
134
            parent_annotations is a list as long as the number of lines in
135
                parent
136
            matching_blocks is a list of (parent_idx, text_idx, len) tuples
137
                indicating which lines match between the two texts
138
        """
4454.3.8 by John Arbash Meinel
Factor out the 'get the lines to annotate' into a helper.
139
        parent_lines = self._text_cache[parent_key]
4454.3.3 by John Arbash Meinel
Start implementing the reannotation functionality directly.
140
        parent_annotations = self._annotations_cache[parent_key]
141
        # PatienceSequenceMatcher should probably be part of Policy
142
        matcher = patiencediff.PatienceSequenceMatcher(None,
4454.3.9 by John Arbash Meinel
Remove heads_provider, as we don't use it now.
143
            parent_lines, text)
4454.3.3 by John Arbash Meinel
Start implementing the reannotation functionality directly.
144
        matching_blocks = matcher.get_matching_blocks()
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
145
        return parent_annotations, matching_blocks
146
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
147
    def _update_from_one_parent(self, key, annotations, lines, parent_key):
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
148
        """Reannotate this text relative to its first parent."""
149
        parent_annotations, matching_blocks = self._get_parent_annotations_and_matches(
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
150
            key, lines, parent_key)
4454.3.3 by John Arbash Meinel
Start implementing the reannotation functionality directly.
151
152
        for parent_idx, lines_idx, match_len in matching_blocks:
153
            # For all matching regions we copy across the parent annotations
154
            annotations[lines_idx:lines_idx + match_len] = \
155
                parent_annotations[parent_idx:parent_idx + match_len]
156
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
157
    def _update_from_other_parents(self, key, annotations, lines,
158
                                   this_annotation, parent_key):
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
159
        """Reannotate this text relative to a second (or more) parent."""
160
        parent_annotations, matching_blocks = self._get_parent_annotations_and_matches(
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
161
            key, lines, parent_key)
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
162
4454.3.6 by John Arbash Meinel
Adding a trivial 'last_entry' cache drops the time from 56s down to 40s
163
        last_ann = None
164
        last_parent = None
165
        last_res = None
4454.3.7 by John Arbash Meinel
Some minor changes
166
        # TODO: consider making all annotations unique and then using 'is'
167
        #       everywhere. Current results claim that isn't any faster,
168
        #       because of the time spent deduping
4454.3.21 by John Arbash Meinel
Assert that entries in the annotation cache also get cleaned up.
169
        #       deduping also saves a bit of memory. For NEWS it saves ~1MB,
170
        #       but that is out of 200-300MB for extracting everything, so a
171
        #       fairly trivial amount
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
172
        for parent_idx, lines_idx, match_len in matching_blocks:
173
            # For lines which match this parent, we will now resolve whether
174
            # this parent wins over the current annotation
4454.3.40 by John Arbash Meinel
Shave a bit more time off by using subset matching to skip whole regions.
175
            ann_sub = annotations[lines_idx:lines_idx + match_len]
176
            par_sub = parent_annotations[parent_idx:parent_idx + match_len]
177
            if ann_sub == par_sub:
178
                continue
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
179
            for idx in xrange(match_len):
4454.3.40 by John Arbash Meinel
Shave a bit more time off by using subset matching to skip whole regions.
180
                ann = ann_sub[idx]
181
                par_ann = par_sub[idx]
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
182
                ann_idx = lines_idx + idx
183
                if ann == par_ann:
184
                    # Nothing to change
185
                    continue
4454.3.7 by John Arbash Meinel
Some minor changes
186
                if ann == this_annotation:
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
187
                    # Originally claimed 'this', but it was really in this
188
                    # parent
189
                    annotations[ann_idx] = par_ann
190
                    continue
4454.3.7 by John Arbash Meinel
Some minor changes
191
                # Resolve the fact that both sides have a different value for
192
                # last modified
4454.3.6 by John Arbash Meinel
Adding a trivial 'last_entry' cache drops the time from 56s down to 40s
193
                if ann == last_ann and par_ann == last_parent:
194
                    annotations[ann_idx] = last_res
195
                else:
196
                    new_ann = set(ann)
197
                    new_ann.update(par_ann)
198
                    new_ann = tuple(sorted(new_ann))
199
                    annotations[ann_idx] = new_ann
200
                    last_ann = ann
201
                    last_parent = par_ann
202
                    last_res = new_ann
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
203
4454.3.19 by John Arbash Meinel
Have _record_annotation start to remove texts when they are no longer needed.
204
    def _record_annotation(self, key, parent_keys, annotations):
4454.3.16 by John Arbash Meinel
Move more access patterns into helper functions.
205
        self._annotations_cache[key] = annotations
4454.3.19 by John Arbash Meinel
Have _record_annotation start to remove texts when they are no longer needed.
206
        for parent_key in parent_keys:
207
            num = self._num_needed_children[parent_key]
208
            num -= 1
209
            if num == 0:
210
                del self._text_cache[parent_key]
4454.3.21 by John Arbash Meinel
Assert that entries in the annotation cache also get cleaned up.
211
                del self._annotations_cache[parent_key]
4454.3.19 by John Arbash Meinel
Have _record_annotation start to remove texts when they are no longer needed.
212
                # Do we want to clean up _num_needed_children at this point as
213
                # well?
214
            self._num_needed_children[parent_key] = num
4454.3.16 by John Arbash Meinel
Move more access patterns into helper functions.
215
4454.3.22 by John Arbash Meinel
Need to record the other annotations before we can record this,
216
    def _annotate_one(self, key, text, num_lines):
217
        this_annotation = (key,)
218
        # Note: annotations will be mutated by calls to _update_from*
219
        annotations = [this_annotation] * num_lines
220
        parent_keys = self._parent_map[key]
221
        if parent_keys:
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
222
            self._update_from_one_parent(key, annotations, text, parent_keys[0])
4454.3.22 by John Arbash Meinel
Need to record the other annotations before we can record this,
223
            for parent in parent_keys[1:]:
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
224
                self._update_from_other_parents(key, annotations, text,
4454.3.22 by John Arbash Meinel
Need to record the other annotations before we can record this,
225
                                                this_annotation, parent)
226
        self._record_annotation(key, parent_keys, annotations)
227
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
228
    def add_special_text(self, key, parent_keys, text):
229
        """Add a specific text to the graph."""
230
        self._parent_map[key] = parent_keys
231
        self._text_cache[key] = osutils.split_lines(text)
232
        self._heads_provider = None
233
4454.3.2 by John Arbash Meinel
Start moving bits into helper functions. Add tests for multiple revs.
234
    def annotate(self, key):
235
        """Return annotated fulltext for the given key."""
4454.3.21 by John Arbash Meinel
Assert that entries in the annotation cache also get cleaned up.
236
        pb = ui.ui_factory.nested_progress_bar()
237
        try:
238
            for text_key, text, num_lines in self._get_needed_texts(key, pb=pb):
4454.3.22 by John Arbash Meinel
Need to record the other annotations before we can record this,
239
                self._annotate_one(text_key, text, num_lines)
4454.3.21 by John Arbash Meinel
Assert that entries in the annotation cache also get cleaned up.
240
        finally:
241
            pb.finished()
4454.3.1 by John Arbash Meinel
Initial api for Annotator.
242
        try:
4454.3.3 by John Arbash Meinel
Start implementing the reannotation functionality directly.
243
            annotations = self._annotations_cache[key]
244
        except KeyError:
4454.3.1 by John Arbash Meinel
Initial api for Annotator.
245
            raise errors.RevisionNotPresent(key, self._vf)
4454.3.8 by John Arbash Meinel
Factor out the 'get the lines to annotate' into a helper.
246
        return annotations, self._text_cache[key]
4454.3.10 by John Arbash Meinel
Start working on 'annotate_flat' which conforms to the original spec.
247
4454.3.41 by John Arbash Meinel
Cache the heads provider as long as we know that the parent_map hasn't changed.
248
    def _get_heads_provider(self):
249
        if self._heads_provider is None:
250
            self._heads_provider = _mod_graph.KnownGraph(self._parent_map)
251
        return self._heads_provider
252
4454.3.10 by John Arbash Meinel
Start working on 'annotate_flat' which conforms to the original spec.
253
    def annotate_flat(self, key):
254
        """Determine the single-best-revision to source for each line.
255
256
        This is meant as a compatibility thunk to how annotate() used to work.
257
        """
258
        annotations, lines = self.annotate(key)
259
        assert len(annotations) == len(lines)
260
        out = []
4454.3.41 by John Arbash Meinel
Cache the heads provider as long as we know that the parent_map hasn't changed.
261
        heads = self._get_heads_provider().heads
4454.3.13 by John Arbash Meinel
A bit of simplification to the annotate_flat logic.
262
        append = out.append
4454.3.10 by John Arbash Meinel
Start working on 'annotate_flat' which conforms to the original spec.
263
        for annotation, line in zip(annotations, lines):
264
            if len(annotation) == 1:
4454.3.13 by John Arbash Meinel
A bit of simplification to the annotate_flat logic.
265
                append((annotation[0], line))
4454.3.12 by John Arbash Meinel
Finish fleshing out the ability to determine a revision after conflicts.
266
            else:
267
                the_heads = heads(annotation)
268
                if len(the_heads) == 1:
269
                    for head in the_heads:
270
                        break
271
                else:
272
                    # We need to resolve the ambiguity, for now just pick the
273
                    # sorted smallest
4454.3.13 by John Arbash Meinel
A bit of simplification to the annotate_flat logic.
274
                    head = sorted(the_heads)[0]
275
                append((head, line))
4454.3.10 by John Arbash Meinel
Start working on 'annotate_flat' which conforms to the original spec.
276
        return out