/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5273.1.5 by Vincent Ladeuil
Merge bzr.dev into cleanup
1
# Copyright (C) 2009, 2010 Canonical Ltd
4454.3.1 by John Arbash Meinel
Initial api for Annotator.
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
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
17
"""Functionality for doing annotations in the 'optimal' way"""
18
6379.6.1 by Jelmer Vernooij
Import absolute_import in a few places.
19
from __future__ import absolute_import
20
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
21
from .lazy_import import lazy_import
4454.3.77 by John Arbash Meinel
Add support for compatibility with old '_break_annotation_tie' function.
22
lazy_import(globals(), """
7290.14.1 by Jelmer Vernooij
Use external patiencediff.
23
24
import patiencediff
25
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
26
from breezy import (
5279.1.1 by Andrew Bennetts
lazy_import most things in merge.py; add a few representative modules to the import tariff tests; tweak a couple of other modules so that patiencediff is not necessarily imported; remove a bunch of unused imports from test_knit.py.
27
    annotate, # Must be lazy to avoid circular importing
28
    graph as _mod_graph,
29
    )
4454.3.77 by John Arbash Meinel
Add support for compatibility with old '_break_annotation_tie' function.
30
""")
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
31
from . import (
4454.3.1 by John Arbash Meinel
Initial api for Annotator.
32
    errors,
33
    osutils,
4454.3.21 by John Arbash Meinel
Assert that entries in the annotation cache also get cleaned up.
34
    ui,
4454.3.1 by John Arbash Meinel
Initial api for Annotator.
35
    )
36
37
38
class Annotator(object):
39
    """Class that drives performing annotations."""
40
41
    def __init__(self, vf):
42
        """Create a new Annotator from a VersionedFile."""
43
        self._vf = vf
4454.3.2 by John Arbash Meinel
Start moving bits into helper functions. Add tests for multiple revs.
44
        self._parent_map = {}
4454.3.8 by John Arbash Meinel
Factor out the 'get the lines to annotate' into a helper.
45
        self._text_cache = {}
4454.3.18 by John Arbash Meinel
Start tracking the number of children that need a given text.
46
        # Map from key => number of nexts that will be built from this key
47
        self._num_needed_children = {}
4454.3.3 by John Arbash Meinel
Start implementing the reannotation functionality directly.
48
        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.
49
        self._heads_provider = None
4454.3.73 by John Arbash Meinel
inherit from _annotator_py.Annotator in _annotator_pyx.Annotator.
50
        self._ann_tuple_cache = {}
4454.3.1 by John Arbash Meinel
Initial api for Annotator.
51
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
52
    def _update_needed_children(self, key, parent_keys):
53
        for parent_key in parent_keys:
54
            if parent_key in self._num_needed_children:
55
                self._num_needed_children[parent_key] += 1
56
            else:
57
                self._num_needed_children[parent_key] = 1
58
4454.3.18 by John Arbash Meinel
Start tracking the number of children that need a given text.
59
    def _get_needed_keys(self, key):
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
60
        """Determine the texts we need to get from the backing vf.
61
62
        :return: (vf_keys_needed, ann_keys_needed)
63
            vf_keys_needed  These are keys that we need to get from the vf
64
            ann_keys_needed Texts which we have in self._text_cache but we
65
                            don't have annotations for. We need to yield these
66
                            in the proper order so that we can get proper
67
                            annotations.
68
        """
69
        parent_map = self._parent_map
4454.3.18 by John Arbash Meinel
Start tracking the number of children that need a given text.
70
        # We need 1 extra copy of the node we will be looking at when we are
71
        # done
72
        self._num_needed_children[key] = 1
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
73
        vf_keys_needed = set()
74
        ann_keys_needed = set()
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
75
        needed_keys = {key}
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
76
        while needed_keys:
77
            parent_lookup = []
78
            next_parent_map = {}
79
            for key in needed_keys:
80
                if key in self._parent_map:
81
                    # We don't need to lookup this key in the vf
82
                    if key not in self._text_cache:
83
                        # Extract this text from the vf
84
                        vf_keys_needed.add(key)
85
                    elif key not in self._annotations_cache:
86
                        # We do need to annotate
87
                        ann_keys_needed.add(key)
88
                        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.
89
                else:
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
90
                    parent_lookup.append(key)
91
                    vf_keys_needed.add(key)
92
            needed_keys = set()
93
            next_parent_map.update(self._vf.get_parent_map(parent_lookup))
7479.2.1 by Jelmer Vernooij
Drop python2 support.
94
            for key, parent_keys in next_parent_map.items():
7143.15.1 by Jelmer Vernooij
Fix style issues.
95
                if parent_keys is None:  # No graph versionedfile
4454.3.66 by John Arbash Meinel
Implement no-graph support for the Python version.
96
                    parent_keys = ()
97
                    next_parent_map[key] = ()
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
98
                self._update_needed_children(key, parent_keys)
99
                needed_keys.update([key for key in parent_keys
7143.15.1 by Jelmer Vernooij
Fix style issues.
100
                                    if key not in parent_map])
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
101
            parent_map.update(next_parent_map)
7143.15.1 by Jelmer Vernooij
Fix style issues.
102
            # _heads_provider does some graph caching, so it is only valid
103
            # while self._parent_map hasn't changed
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
104
            self._heads_provider = None
105
        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.
106
4454.3.21 by John Arbash Meinel
Assert that entries in the annotation cache also get cleaned up.
107
    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.
108
        """Get the texts we need to properly annotate key.
109
110
        :param key: A Key that is present in self._vf
111
        :return: Yield (this_key, text, num_lines)
112
            'text' is an opaque object that just has to work with whatever
113
            matcher object we are using. Currently it is always 'lines' but
114
            future improvements may change this to a simple text string.
115
        """
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
116
        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.
117
        if pb is not None:
118
            pb.update('getting stream', 0, len(keys))
7143.15.1 by Jelmer Vernooij
Fix style issues.
119
        stream = self._vf.get_record_stream(keys, 'topological', True)
4454.3.21 by John Arbash Meinel
Assert that entries in the annotation cache also get cleaned up.
120
        for idx, record in enumerate(stream):
121
            if pb is not None:
122
                pb.update('extracting', 0, len(keys))
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
123
            if record.storage_kind == 'absent':
124
                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.
125
            this_key = record.key
7459.3.2 by Jelmer Vernooij
Add a 'lines' storage type.
126
            lines = record.get_bytes_as('lines')
4454.3.8 by John Arbash Meinel
Factor out the 'get the lines to annotate' into a helper.
127
            num_lines = len(lines)
4454.3.16 by John Arbash Meinel
Move more access patterns into helper functions.
128
            self._text_cache[this_key] = lines
4454.3.8 by John Arbash Meinel
Factor out the 'get the lines to annotate' into a helper.
129
            yield this_key, lines, num_lines
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
130
        for key in ann_keys:
131
            lines = self._text_cache[key]
132
            num_lines = len(lines)
133
            yield key, lines, num_lines
4454.3.2 by John Arbash Meinel
Start moving bits into helper functions. Add tests for multiple revs.
134
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
135
    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.
136
        """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.
137
4454.3.9 by John Arbash Meinel
Remove heads_provider, as we don't use it now.
138
        :param text: The opaque value given by _get_needed_texts
139
        :param parent_key: The key for the parent text
140
        :return: (parent_annotations, matching_blocks)
141
            parent_annotations is a list as long as the number of lines in
142
                parent
143
            matching_blocks is a list of (parent_idx, text_idx, len) tuples
144
                indicating which lines match between the two texts
145
        """
4454.3.8 by John Arbash Meinel
Factor out the 'get the lines to annotate' into a helper.
146
        parent_lines = self._text_cache[parent_key]
4454.3.3 by John Arbash Meinel
Start implementing the reannotation functionality directly.
147
        parent_annotations = self._annotations_cache[parent_key]
148
        # PatienceSequenceMatcher should probably be part of Policy
7143.15.1 by Jelmer Vernooij
Fix style issues.
149
        matcher = patiencediff.PatienceSequenceMatcher(
150
            None, parent_lines, text)
4454.3.3 by John Arbash Meinel
Start implementing the reannotation functionality directly.
151
        matching_blocks = matcher.get_matching_blocks()
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
152
        return parent_annotations, matching_blocks
153
4454.3.73 by John Arbash Meinel
inherit from _annotator_py.Annotator in _annotator_pyx.Annotator.
154
    def _update_from_first_parent(self, key, annotations, lines, parent_key):
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
155
        """Reannotate this text relative to its first parent."""
4454.3.75 by John Arbash Meinel
Move the core loops into module-level helpers.
156
        (parent_annotations,
157
         matching_blocks) = self._get_parent_annotations_and_matches(
7143.15.1 by Jelmer Vernooij
Fix style issues.
158
             key, lines, parent_key)
4454.3.3 by John Arbash Meinel
Start implementing the reannotation functionality directly.
159
160
        for parent_idx, lines_idx, match_len in matching_blocks:
161
            # For all matching regions we copy across the parent annotations
162
            annotations[lines_idx:lines_idx + match_len] = \
163
                parent_annotations[parent_idx:parent_idx + match_len]
164
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
165
    def _update_from_other_parents(self, key, annotations, lines,
166
                                   this_annotation, parent_key):
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
167
        """Reannotate this text relative to a second (or more) parent."""
4454.3.75 by John Arbash Meinel
Move the core loops into module-level helpers.
168
        (parent_annotations,
169
         matching_blocks) = self._get_parent_annotations_and_matches(
7143.15.1 by Jelmer Vernooij
Fix style issues.
170
             key, lines, parent_key)
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
171
4454.3.6 by John Arbash Meinel
Adding a trivial 'last_entry' cache drops the time from 56s down to 40s
172
        last_ann = None
173
        last_parent = None
174
        last_res = None
4454.3.7 by John Arbash Meinel
Some minor changes
175
        # TODO: consider making all annotations unique and then using 'is'
176
        #       everywhere. Current results claim that isn't any faster,
177
        #       because of the time spent deduping
4454.3.21 by John Arbash Meinel
Assert that entries in the annotation cache also get cleaned up.
178
        #       deduping also saves a bit of memory. For NEWS it saves ~1MB,
179
        #       but that is out of 200-300MB for extracting everything, so a
180
        #       fairly trivial amount
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
181
        for parent_idx, lines_idx, match_len in matching_blocks:
182
            # For lines which match this parent, we will now resolve whether
183
            # 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.
184
            ann_sub = annotations[lines_idx:lines_idx + match_len]
185
            par_sub = parent_annotations[parent_idx:parent_idx + match_len]
186
            if ann_sub == par_sub:
187
                continue
6651.2.2 by Martin
Apply 2to3 xrange fix and fix up with sixish range
188
            for idx in range(match_len):
4454.3.40 by John Arbash Meinel
Shave a bit more time off by using subset matching to skip whole regions.
189
                ann = ann_sub[idx]
190
                par_ann = par_sub[idx]
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
191
                ann_idx = lines_idx + idx
192
                if ann == par_ann:
193
                    # Nothing to change
194
                    continue
4454.3.7 by John Arbash Meinel
Some minor changes
195
                if ann == this_annotation:
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
196
                    # Originally claimed 'this', but it was really in this
197
                    # parent
198
                    annotations[ann_idx] = par_ann
199
                    continue
4454.3.7 by John Arbash Meinel
Some minor changes
200
                # Resolve the fact that both sides have a different value for
201
                # last modified
4454.3.6 by John Arbash Meinel
Adding a trivial 'last_entry' cache drops the time from 56s down to 40s
202
                if ann == last_ann and par_ann == last_parent:
203
                    annotations[ann_idx] = last_res
204
                else:
205
                    new_ann = set(ann)
206
                    new_ann.update(par_ann)
207
                    new_ann = tuple(sorted(new_ann))
208
                    annotations[ann_idx] = new_ann
209
                    last_ann = ann
210
                    last_parent = par_ann
211
                    last_res = new_ann
4454.3.4 by John Arbash Meinel
New work on how to resolve conflict lines.
212
4454.3.19 by John Arbash Meinel
Have _record_annotation start to remove texts when they are no longer needed.
213
    def _record_annotation(self, key, parent_keys, annotations):
4454.3.16 by John Arbash Meinel
Move more access patterns into helper functions.
214
        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.
215
        for parent_key in parent_keys:
216
            num = self._num_needed_children[parent_key]
217
            num -= 1
218
            if num == 0:
219
                del self._text_cache[parent_key]
4454.3.21 by John Arbash Meinel
Assert that entries in the annotation cache also get cleaned up.
220
                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.
221
                # Do we want to clean up _num_needed_children at this point as
222
                # well?
223
            self._num_needed_children[parent_key] = num
4454.3.16 by John Arbash Meinel
Move more access patterns into helper functions.
224
4454.3.22 by John Arbash Meinel
Need to record the other annotations before we can record this,
225
    def _annotate_one(self, key, text, num_lines):
226
        this_annotation = (key,)
227
        # Note: annotations will be mutated by calls to _update_from*
228
        annotations = [this_annotation] * num_lines
229
        parent_keys = self._parent_map[key]
230
        if parent_keys:
4454.3.73 by John Arbash Meinel
inherit from _annotator_py.Annotator in _annotator_pyx.Annotator.
231
            self._update_from_first_parent(key, annotations, text,
232
                                           parent_keys[0])
4454.3.22 by John Arbash Meinel
Need to record the other annotations before we can record this,
233
            for parent in parent_keys[1:]:
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
234
                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,
235
                                                this_annotation, parent)
236
        self._record_annotation(key, parent_keys, annotations)
237
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
238
    def add_special_text(self, key, parent_keys, text):
4454.3.74 by John Arbash Meinel
Some small tweaks, add more documentation for 'add_special_text'.
239
        """Add a specific text to the graph.
240
241
        This is used to add a text which is not otherwise present in the
242
        versioned file. (eg. a WorkingTree injecting 'current:' into the
243
        graph to annotate the edited content.)
244
245
        :param key: The key to use to request this text be annotated
246
        :param parent_keys: The parents of this text
247
        :param text: A string containing the content of the text
248
        """
4454.3.61 by John Arbash Meinel
Start implementing an Annotator.add_special_text functionality.
249
        self._parent_map[key] = parent_keys
250
        self._text_cache[key] = osutils.split_lines(text)
251
        self._heads_provider = None
252
4454.3.2 by John Arbash Meinel
Start moving bits into helper functions. Add tests for multiple revs.
253
    def annotate(self, key):
4454.3.75 by John Arbash Meinel
Move the core loops into module-level helpers.
254
        """Return annotated fulltext for the given key.
255
256
        :param key: A tuple defining the text to annotate
257
        :return: ([annotations], [lines])
258
            annotations is a list of tuples of keys, one for each line in lines
259
                        each key is a possible source for the given line.
260
            lines the text of "key" as a list of lines
261
        """
6861.4.1 by Jelmer Vernooij
Make progress bars context managers.
262
        with ui.ui_factory.nested_progress_bar() as pb:
7143.15.1 by Jelmer Vernooij
Fix style issues.
263
            for text_key, text, num_lines in self._get_needed_texts(
264
                    key, pb=pb):
4454.3.22 by John Arbash Meinel
Need to record the other annotations before we can record this,
265
                self._annotate_one(text_key, text, num_lines)
4454.3.1 by John Arbash Meinel
Initial api for Annotator.
266
        try:
4454.3.3 by John Arbash Meinel
Start implementing the reannotation functionality directly.
267
            annotations = self._annotations_cache[key]
268
        except KeyError:
4454.3.1 by John Arbash Meinel
Initial api for Annotator.
269
            raise errors.RevisionNotPresent(key, self._vf)
4454.3.8 by John Arbash Meinel
Factor out the 'get the lines to annotate' into a helper.
270
        return annotations, self._text_cache[key]
4454.3.10 by John Arbash Meinel
Start working on 'annotate_flat' which conforms to the original spec.
271
4454.3.41 by John Arbash Meinel
Cache the heads provider as long as we know that the parent_map hasn't changed.
272
    def _get_heads_provider(self):
273
        if self._heads_provider is None:
274
            self._heads_provider = _mod_graph.KnownGraph(self._parent_map)
275
        return self._heads_provider
276
4454.3.77 by John Arbash Meinel
Add support for compatibility with old '_break_annotation_tie' function.
277
    def _resolve_annotation_tie(self, the_heads, line, tiebreaker):
278
        if tiebreaker is None:
279
            head = sorted(the_heads)[0]
280
        else:
281
            # Backwards compatibility, break up the heads into pairs and
282
            # resolve the result
283
            next_head = iter(the_heads)
6634.2.1 by Martin
Apply 2to3 next fixer and make compatible
284
            head = next(next_head)
4454.3.77 by John Arbash Meinel
Add support for compatibility with old '_break_annotation_tie' function.
285
            for possible_head in next_head:
286
                annotated_lines = ((head, line), (possible_head, line))
287
                head = tiebreaker(annotated_lines)[0]
288
        return head
289
4454.3.10 by John Arbash Meinel
Start working on 'annotate_flat' which conforms to the original spec.
290
    def annotate_flat(self, key):
291
        """Determine the single-best-revision to source for each line.
292
293
        This is meant as a compatibility thunk to how annotate() used to work.
4454.3.75 by John Arbash Meinel
Move the core loops into module-level helpers.
294
        :return: [(ann_key, line)]
295
            A list of tuples with a single annotation key for each line.
4454.3.10 by John Arbash Meinel
Start working on 'annotate_flat' which conforms to the original spec.
296
        """
4454.3.77 by John Arbash Meinel
Add support for compatibility with old '_break_annotation_tie' function.
297
        custom_tiebreaker = annotate._break_annotation_tie
4454.3.10 by John Arbash Meinel
Start working on 'annotate_flat' which conforms to the original spec.
298
        annotations, lines = self.annotate(key)
299
        out = []
4454.3.41 by John Arbash Meinel
Cache the heads provider as long as we know that the parent_map hasn't changed.
300
        heads = self._get_heads_provider().heads
4454.3.13 by John Arbash Meinel
A bit of simplification to the annotate_flat logic.
301
        append = out.append
4454.3.10 by John Arbash Meinel
Start working on 'annotate_flat' which conforms to the original spec.
302
        for annotation, line in zip(annotations, lines):
303
            if len(annotation) == 1:
4454.3.77 by John Arbash Meinel
Add support for compatibility with old '_break_annotation_tie' function.
304
                head = annotation[0]
4454.3.12 by John Arbash Meinel
Finish fleshing out the ability to determine a revision after conflicts.
305
            else:
306
                the_heads = heads(annotation)
307
                if len(the_heads) == 1:
7143.15.1 by Jelmer Vernooij
Fix style issues.
308
                    for head in the_heads:
309
                        break  # get the item out of the set
4454.3.12 by John Arbash Meinel
Finish fleshing out the ability to determine a revision after conflicts.
310
                else:
4454.3.77 by John Arbash Meinel
Add support for compatibility with old '_break_annotation_tie' function.
311
                    head = self._resolve_annotation_tie(the_heads, line,
312
                                                        custom_tiebreaker)
313
            append((head, line))
4454.3.10 by John Arbash Meinel
Start working on 'annotate_flat' which conforms to the original spec.
314
        return out