/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to brzlib/annotate.py

  • Committer: Jelmer Vernooij
  • Date: 2017-05-21 12:41:27 UTC
  • mto: This revision was merged to the branch mainline in revision 6623.
  • Revision ID: jelmer@jelmer.uk-20170521124127-iv8etg0vwymyai6y
s/bzr/brz/ in apport config.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""File annotate based on weave storage"""
18
18
 
 
19
from __future__ import absolute_import
 
20
 
19
21
# TODO: Choice of more or less verbose formats:
20
22
#
21
23
# interposed: show more details between blocks of modified lines
28
30
import sys
29
31
import time
30
32
 
31
 
from .lazy_import import lazy_import
 
33
from brzlib.lazy_import import lazy_import
32
34
lazy_import(globals(), """
33
 
 
34
 
import patiencediff
35
 
 
36
 
from breezy import (
 
35
from brzlib import (
 
36
    patiencediff,
37
37
    tsort,
38
38
    )
39
39
""")
40
 
from . import (
41
 
    config,
 
40
from brzlib import (
42
41
    errors,
43
42
    osutils,
44
43
    )
45
 
from .repository import _strip_NULL_ghosts
46
 
from .revision import (
 
44
from brzlib.config import extract_email_address
 
45
from brzlib.repository import _strip_NULL_ghosts
 
46
from brzlib.revision import (
47
47
    CURRENT_REVISION,
48
48
    Revision,
49
49
    )
50
50
 
51
51
 
52
 
def annotate_file_tree(tree, path, to_file, verbose=False, full=False,
53
 
                       show_ids=False, branch=None):
54
 
    """Annotate path in a tree.
 
52
def annotate_file_tree(tree, file_id, to_file, verbose=False, full=False,
 
53
    show_ids=False, branch=None):
 
54
    """Annotate file_id in a tree.
55
55
 
56
56
    The tree should already be read_locked() when annotate_file_tree is called.
57
57
 
58
58
    :param tree: The tree to look for revision numbers and history from.
59
 
    :param path: The path to annotate
 
59
    :param file_id: The file_id to annotate.
60
60
    :param to_file: The file to output the annotation to.
61
61
    :param verbose: Show all details rather than truncating to ensure
62
62
        reasonable text width.
69
69
    if to_file is None:
70
70
        to_file = sys.stdout
71
71
 
72
 
    encoding = osutils.get_terminal_encoding()
73
72
    # Handle the show_ids case
74
 
    annotations = list(tree.annotate_iter(path))
 
73
    annotations = list(tree.annotate_iter(file_id))
75
74
    if show_ids:
76
 
        return _show_id_annotations(annotations, to_file, full, encoding)
 
75
        return _show_id_annotations(annotations, to_file, full)
77
76
 
78
77
    if not getattr(tree, "get_revision_id", False):
79
78
        # Create a virtual revision to represent the current tree state.
90
89
        current_rev.timezone = osutils.local_time_offset()
91
90
    else:
92
91
        current_rev = None
93
 
    annotation = list(_expand_annotations(
94
 
        annotations, branch, current_rev))
95
 
    _print_annotations(annotation, verbose, to_file, full, encoding)
96
 
 
97
 
 
98
 
def _print_annotations(annotation, verbose, to_file, full, encoding):
 
92
    annotation = list(_expand_annotations(annotations, branch,
 
93
        current_rev))
 
94
    _print_annotations(annotation, verbose, to_file, full)
 
95
 
 
96
 
 
97
def _print_annotations(annotation, verbose, to_file, full):
99
98
    """Print annotations to to_file.
100
99
 
101
100
    :param to_file: The file to output the annotation to.
104
103
    :param full: XXXX Not sure what this does.
105
104
    """
106
105
    if len(annotation) == 0:
107
 
        max_origin_len = max_revno_len = 0
 
106
        max_origin_len = max_revno_len = max_revid_len = 0
108
107
    else:
109
108
        max_origin_len = max(len(x[1]) for x in annotation)
110
109
        max_revno_len = max(len(x[0]) for x in annotation)
 
110
        max_revid_len = max(len(x[3]) for x in annotation)
111
111
    if not verbose:
112
112
        max_revno_len = min(max_revno_len, 12)
113
113
    max_revno_len = max(max_revno_len, 3)
114
114
 
115
115
    # Output the annotations
116
116
    prevanno = ''
 
117
    encoding = getattr(to_file, 'encoding', None) or \
 
118
            osutils.get_terminal_encoding()
117
119
    for (revno_str, author, date_str, line_rev_id, text) in annotation:
118
120
        if verbose:
119
121
            anno = '%-*s %-*s %8s ' % (max_revno_len, revno_str,
120
122
                                       max_origin_len, author, date_str)
121
123
        else:
122
124
            if len(revno_str) > max_revno_len:
123
 
                revno_str = revno_str[:max_revno_len - 1] + '>'
 
125
                revno_str = revno_str[:max_revno_len-1] + '>'
124
126
            anno = "%-*s %-7s " % (max_revno_len, revno_str, author[:7])
125
127
        if anno.lstrip() == "" and full:
126
128
            anno = prevanno
127
 
        # GZ 2017-05-21: Writing both unicode annotation and bytes from file
128
 
        # which the given to_file must cope with.
129
 
        to_file.write(anno)
130
 
        to_file.write('| %s\n' % (text.decode(encoding),))
 
129
        try:
 
130
            to_file.write(anno)
 
131
        except UnicodeEncodeError:
 
132
            # cmd_annotate should be passing in an 'exact' object, which means
 
133
            # we have a direct handle to sys.stdout or equivalent. It may not
 
134
            # be able to handle the exact Unicode characters, but 'annotate' is
 
135
            # a user function (non-scripting), so shouldn't die because of
 
136
            # unrepresentable annotation characters. So encode using 'replace',
 
137
            # and write them again.
 
138
            to_file.write(anno.encode(encoding, 'replace'))
 
139
        to_file.write('| %s\n' % (text,))
131
140
        prevanno = anno
132
141
 
133
142
 
134
 
def _show_id_annotations(annotations, to_file, full, encoding):
 
143
def _show_id_annotations(annotations, to_file, full):
135
144
    if not annotations:
136
145
        return
137
146
    last_rev_id = None
140
149
        if full or last_rev_id != origin:
141
150
            this = origin
142
151
        else:
143
 
            this = b''
144
 
        to_file.write('%*s | %s' % (
145
 
            max_origin_len, this.decode('utf-8'), text.decode(encoding)))
 
152
            this = ''
 
153
        to_file.write('%*s | %s' % (max_origin_len, this, text))
146
154
        last_rev_id = origin
147
155
    return
148
156
 
158
166
    :param branch: A locked branch to query for revision details.
159
167
    """
160
168
    repository = branch.repository
161
 
    revision_ids = set(o for o, t in annotations)
162
169
    if current_rev is not None:
163
170
        # This can probably become a function on MutableTree, get_revno_map
164
171
        # there, or something.
169
176
        #      Once KnownGraph gets an 'add_node()' function, we can use
170
177
        #      VF.get_known_graph_ancestry().
171
178
        graph = repository.get_graph()
172
 
        revision_graph = {
173
 
            key: value for key, value in
174
 
            graph.iter_ancestry(current_rev.parent_ids) if value is not None}
 
179
        revision_graph = dict(((key, value) for key, value in
 
180
            graph.iter_ancestry(current_rev.parent_ids) if value is not None))
175
181
        revision_graph = _strip_NULL_ghosts(revision_graph)
176
182
        revision_graph[last_revision] = current_rev.parent_ids
177
183
        merge_sorted_revisions = tsort.merge_sort(
179
185
            last_revision,
180
186
            None,
181
187
            generate_revno=True)
182
 
        revision_id_to_revno = {
183
 
            rev_id: revno
 
188
        revision_id_to_revno = dict((rev_id, revno)
184
189
            for seq_num, rev_id, depth, revno, end_of_merge in
185
 
            merge_sorted_revisions}
 
190
                merge_sorted_revisions)
186
191
    else:
187
 
        # TODO(jelmer): Only look up the revision ids that we need (i.e. those
188
 
        # in revision_ids). Possibly add a HPSS call that can look those up
189
 
        # in bulk over HPSS.
190
192
        revision_id_to_revno = branch.get_revision_id_to_revno_map()
191
193
    last_origin = None
 
194
    revision_ids = set(o for o, t in annotations)
192
195
    revisions = {}
193
196
    if CURRENT_REVISION in revision_ids:
194
197
        revision_id_to_revno[CURRENT_REVISION] = (
195
198
            "%d?" % (branch.revno() + 1),)
196
199
        revisions[CURRENT_REVISION] = current_rev
197
 
    revisions.update(
198
 
        entry for entry in
199
 
        repository.iter_revisions(revision_ids)
200
 
        if entry[1] is not None)
 
200
    revision_ids = [o for o in revision_ids if
 
201
                    repository.has_revision(o)]
 
202
    revisions.update((r.revision_id, r) for r in
 
203
                     repository.get_revisions(revision_ids))
201
204
    for origin, text in annotations:
202
 
        text = text.rstrip(b'\r\n')
 
205
        text = text.rstrip('\r\n')
203
206
        if origin == last_origin:
204
 
            (revno_str, author, date_str) = ('', '', '')
 
207
            (revno_str, author, date_str) = ('','','')
205
208
        else:
206
209
            last_origin = origin
207
210
            if origin not in revisions:
208
 
                (revno_str, author, date_str) = ('?', '?', '?')
 
211
                (revno_str, author, date_str) = ('?','?','?')
209
212
            else:
210
 
                revno_str = '.'.join(
211
 
                    str(i) for i in revision_id_to_revno[origin])
 
213
                revno_str = '.'.join(str(i) for i in
 
214
                                            revision_id_to_revno[origin])
212
215
            rev = revisions[origin]
213
216
            tz = rev.timezone or 0
214
217
            date_str = time.strftime('%Y%m%d',
215
 
                                     time.gmtime(rev.timestamp + tz))
 
218
                                     osutils.gmtime(rev.timestamp + tz))
216
219
            # a lazy way to get something like the email address
217
220
            # TODO: Get real email address
218
221
            author = rev.get_apparent_authors()[0]
219
 
            _, email = config.parse_username(author)
220
 
            if email:
221
 
                author = email
 
222
            try:
 
223
                author = extract_email_address(author)
 
224
            except errors.NoEmailInUsername:
 
225
                pass        # use the whole name
222
226
        yield (revno_str, author, date_str, origin, text)
223
227
 
224
228
 
278
282
    new_cur = 0
279
283
    if matching_blocks is None:
280
284
        plain_parent_lines = [l for r, l in parent_lines]
281
 
        matcher = patiencediff.PatienceSequenceMatcher(
282
 
            None, plain_parent_lines, new_lines)
 
285
        matcher = patiencediff.PatienceSequenceMatcher(None,
 
286
            plain_parent_lines, new_lines)
283
287
        matching_blocks = matcher.get_matching_blocks()
284
288
    lines = []
285
289
    for i, j, n in matching_blocks:
286
290
        for line in new_lines[new_cur:j]:
287
291
            lines.append((new_revision_id, line))
288
 
        lines.extend(parent_lines[i:i + n])
 
292
        lines.extend(parent_lines[i:i+n])
289
293
        new_cur = j + n
290
294
    return lines
291
295
 
297
301
 
298
302
_break_annotation_tie = None
299
303
 
300
 
 
301
304
def _old_break_annotation_tie(annotated_lines):
302
305
    """Chose an attribution between several possible ones.
303
306
 
345
348
    output_extend = output_lines.extend
346
349
    output_append = output_lines.append
347
350
    # We need to see if any of the unannotated lines match
348
 
    plain_right_subset = [l for a, l in right_lines[start_right:end_right]]
 
351
    plain_right_subset = [l for a,l in right_lines[start_right:end_right]]
349
352
    plain_child_subset = plain_child_lines[start_child:end_child]
350
353
    match_blocks = _get_matching_blocks(plain_right_subset, plain_child_subset)
351
354
 
354
357
    for right_idx, child_idx, match_len in match_blocks:
355
358
        # All the lines that don't match are just passed along
356
359
        if child_idx > last_child_idx:
357
 
            output_extend(child_lines[start_child + last_child_idx:
358
 
                                      start_child + child_idx])
359
 
        for offset in range(match_len):
360
 
            left = child_lines[start_child + child_idx + offset]
361
 
            right = right_lines[start_right + right_idx + offset]
 
360
            output_extend(child_lines[start_child + last_child_idx
 
361
                                      :start_child + child_idx])
 
362
        for offset in xrange(match_len):
 
363
            left = child_lines[start_child+child_idx+offset]
 
364
            right = right_lines[start_right+right_idx+offset]
362
365
            if left[0] == right[0]:
363
366
                # The annotations match, just return the left one
364
367
                output_append(left)
373
376
                else:
374
377
                    heads = heads_provider.heads((left[0], right[0]))
375
378
                    if len(heads) == 1:
376
 
                        output_append((next(iter(heads)), left[1]))
 
379
                        output_append((iter(heads).next(), left[1]))
377
380
                    else:
378
381
                        # Both claim different origins, get a stable result.
379
382
                        # If the result is not stable, there is a risk a
408
411
    # be the bulk of the lines, and they will need no further processing.
409
412
    lines = []
410
413
    lines_extend = lines.extend
411
 
    # The line just after the last match from the right side
412
 
    last_right_idx = 0
 
414
    last_right_idx = 0 # The line just after the last match from the right side
413
415
    last_left_idx = 0
414
416
    matching_left_and_right = _get_matching_blocks(right_parent_lines,
415
417
                                                   annotated_lines)
437
439
 
438
440
 
439
441
try:
440
 
    from breezy._annotator_pyx import Annotator
441
 
except ImportError as e:
 
442
    from brzlib._annotator_pyx import Annotator
 
443
except ImportError, e:
442
444
    osutils.failed_to_load_extension(e)
443
 
    from breezy._annotator_py import Annotator  # noqa: F401
 
445
    from brzlib._annotator_py import Annotator