/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 breezy/annotate.py

  • Committer: Jelmer Vernooij
  • Date: 2019-06-02 21:21:39 UTC
  • mto: This revision was merged to the branch mainline in revision 7315.
  • Revision ID: jelmer@jelmer.uk-20190602212139-pfo8ekg0sw2y6pd6
Drop find_trees.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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
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 bzrlib import (
32
 
    errors,
 
33
from .lazy_import import lazy_import
 
34
lazy_import(globals(), """
 
35
 
 
36
import patiencediff
 
37
 
 
38
from breezy import (
 
39
    tsort,
 
40
    )
 
41
""")
 
42
from . import (
33
43
    osutils,
34
 
    patiencediff,
35
 
    tsort,
36
 
    )
37
 
from bzrlib.config import extract_email_address
38
 
from bzrlib.repository import _strip_NULL_ghosts
39
 
from bzrlib.revision import CURRENT_REVISION, Revision
40
 
 
41
 
 
42
 
def annotate_file(branch, rev_id, file_id, verbose=False, full=False,
43
 
                  to_file=None, show_ids=False):
44
 
    """Annotate file_id at revision rev_id in branch.
45
 
 
46
 
    The branch should already be read_locked() when annotate_file is called.
47
 
 
48
 
    :param branch: The branch to look for revision numbers and history from.
49
 
    :param rev_id: The revision id to annotate.
50
 
    :param file_id: The file_id to annotate.
 
44
    )
 
45
from .config import (
 
46
    NoEmailInUsername,
 
47
    NoWhoami,
 
48
    extract_email_address,
 
49
    )
 
50
from .repository import _strip_NULL_ghosts
 
51
from .revision import (
 
52
    CURRENT_REVISION,
 
53
    Revision,
 
54
    )
 
55
 
 
56
 
 
57
def annotate_file_tree(tree, path, to_file, verbose=False, full=False,
 
58
                       show_ids=False, branch=None):
 
59
    """Annotate path in a tree.
 
60
 
 
61
    The tree should already be read_locked() when annotate_file_tree is called.
 
62
 
 
63
    :param tree: The tree to look for revision numbers and history from.
 
64
    :param path: The path to annotate
 
65
    :param to_file: The file to output the annotation to.
51
66
    :param verbose: Show all details rather than truncating to ensure
52
67
        reasonable text width.
53
68
    :param full: XXXX Not sure what this does.
54
 
    :param to_file: The file to output the annotation to; if None stdout is
55
 
        used.
56
69
    :param show_ids: Show revision ids in the annotation output.
 
70
    :param branch: Branch to use for revision revno lookups
57
71
    """
 
72
    if branch is None:
 
73
        branch = tree.branch
58
74
    if to_file is None:
59
75
        to_file = sys.stdout
60
76
 
61
 
    # Handle the show_ids case
62
 
    annotations = _annotations(branch.repository, file_id, rev_id)
63
 
    if show_ids:
64
 
        return _show_id_annotations(annotations, to_file, full)
65
 
 
66
 
    # Calculate the lengths of the various columns
67
 
    annotation = list(_expand_annotations(annotations, branch))
68
 
    _print_annotations(annotation, verbose, to_file, full)
69
 
 
70
 
 
71
 
def annotate_file_tree(tree, file_id, to_file, verbose=False, full=False,
72
 
    show_ids=False):
73
 
    """Annotate file_id in a tree.
74
 
 
75
 
    The tree should already be read_locked() when annotate_file_tree is called.
76
 
 
77
 
    :param tree: The tree to look for revision numbers and history from.
78
 
    :param file_id: The file_id to annotate.
79
 
    :param to_file: The file to output the annotation to.
80
 
    :param verbose: Show all details rather than truncating to ensure
81
 
        reasonable text width.
82
 
    :param full: XXXX Not sure what this does.
83
 
    :param show_ids: Show revision ids in the annotation output.
84
 
    """
85
 
    rev_id = tree.last_revision()
86
 
    branch = tree.branch
87
 
 
88
 
    # Handle the show_ids case
89
 
    annotations = list(tree.annotate_iter(file_id))
90
 
    if show_ids:
91
 
        return _show_id_annotations(annotations, to_file, full)
92
 
 
93
 
    # Create a virtual revision to represent the current tree state.
94
 
    # Should get some more pending commit attributes, like pending tags,
95
 
    # bugfixes etc.
96
 
    current_rev = Revision(CURRENT_REVISION)
97
 
    current_rev.parent_ids = tree.get_parent_ids()
98
 
    current_rev.committer = tree.branch.get_config().username()
99
 
    current_rev.message = "?"
100
 
    current_rev.timestamp = round(time.time(), 3)
101
 
    current_rev.timezone = osutils.local_time_offset()
102
 
    annotation = list(_expand_annotations(annotations, tree.branch,
103
 
        current_rev))
104
 
    _print_annotations(annotation, verbose, to_file, full)
105
 
 
106
 
 
107
 
def _print_annotations(annotation, verbose, to_file, full):
 
77
    encoding = osutils.get_terminal_encoding()
 
78
    # Handle the show_ids case
 
79
    annotations = list(tree.annotate_iter(path))
 
80
    if show_ids:
 
81
        return _show_id_annotations(annotations, to_file, full, encoding)
 
82
 
 
83
    if not getattr(tree, "get_revision_id", False):
 
84
        # Create a virtual revision to represent the current tree state.
 
85
        # Should get some more pending commit attributes, like pending tags,
 
86
        # bugfixes etc.
 
87
        current_rev = Revision(CURRENT_REVISION)
 
88
        current_rev.parent_ids = tree.get_parent_ids()
 
89
        try:
 
90
            current_rev.committer = branch.get_config_stack().get('email')
 
91
        except NoWhoami:
 
92
            current_rev.committer = 'local user'
 
93
        current_rev.message = "?"
 
94
        current_rev.timestamp = round(time.time(), 3)
 
95
        current_rev.timezone = osutils.local_time_offset()
 
96
    else:
 
97
        current_rev = None
 
98
    annotation = list(_expand_annotations(
 
99
        annotations, branch, current_rev))
 
100
    _print_annotations(annotation, verbose, to_file, full, encoding)
 
101
 
 
102
 
 
103
def _print_annotations(annotation, verbose, to_file, full, encoding):
108
104
    """Print annotations to to_file.
109
105
 
110
106
    :param to_file: The file to output the annotation to.
113
109
    :param full: XXXX Not sure what this does.
114
110
    """
115
111
    if len(annotation) == 0:
116
 
        max_origin_len = max_revno_len = max_revid_len = 0
 
112
        max_origin_len = max_revno_len = 0
117
113
    else:
118
114
        max_origin_len = max(len(x[1]) for x in annotation)
119
115
        max_revno_len = max(len(x[0]) for x in annotation)
120
 
        max_revid_len = max(len(x[3]) for x in annotation)
121
116
    if not verbose:
122
117
        max_revno_len = min(max_revno_len, 12)
123
118
    max_revno_len = max(max_revno_len, 3)
124
119
 
125
120
    # Output the annotations
126
121
    prevanno = ''
127
 
    encoding = getattr(to_file, 'encoding', None) or \
128
 
            osutils.get_terminal_encoding()
129
122
    for (revno_str, author, date_str, line_rev_id, text) in annotation:
130
123
        if verbose:
131
124
            anno = '%-*s %-*s %8s ' % (max_revno_len, revno_str,
132
125
                                       max_origin_len, author, date_str)
133
126
        else:
134
127
            if len(revno_str) > max_revno_len:
135
 
                revno_str = revno_str[:max_revno_len-1] + '>'
 
128
                revno_str = revno_str[:max_revno_len - 1] + '>'
136
129
            anno = "%-*s %-7s " % (max_revno_len, revno_str, author[:7])
137
130
        if anno.lstrip() == "" and full:
138
131
            anno = prevanno
139
 
        try:
140
 
            to_file.write(anno)
141
 
        except UnicodeEncodeError:
142
 
            # cmd_annotate should be passing in an 'exact' object, which means
143
 
            # we have a direct handle to sys.stdout or equivalent. It may not
144
 
            # be able to handle the exact Unicode characters, but 'annotate' is
145
 
            # a user function (non-scripting), so shouldn't die because of
146
 
            # unrepresentable annotation characters. So encode using 'replace',
147
 
            # and write them again.
148
 
            to_file.write(anno.encode(encoding, 'replace'))
149
 
        to_file.write('| %s\n' % (text,))
 
132
        # GZ 2017-05-21: Writing both unicode annotation and bytes from file
 
133
        # which the given to_file must cope with.
 
134
        to_file.write(anno)
 
135
        to_file.write('| %s\n' % (text.decode(encoding),))
150
136
        prevanno = anno
151
137
 
152
138
 
153
 
def _show_id_annotations(annotations, to_file, full):
 
139
def _show_id_annotations(annotations, to_file, full, encoding):
154
140
    if not annotations:
155
141
        return
156
142
    last_rev_id = None
159
145
        if full or last_rev_id != origin:
160
146
            this = origin
161
147
        else:
162
 
            this = ''
163
 
        to_file.write('%*s | %s' % (max_origin_len, this, text))
 
148
            this = b''
 
149
        to_file.write('%*s | %s' % (
 
150
            max_origin_len, this.decode('utf-8'), text.decode(encoding)))
164
151
        last_rev_id = origin
165
152
    return
166
153
 
167
154
 
168
 
def _annotations(repo, file_id, rev_id):
169
 
    """Return the list of (origin_revision_id, line_text) for a revision of a file in a repository."""
170
 
    annotations = repo.texts.annotate((file_id, rev_id))
171
 
    #
172
 
    return [(key[-1], line) for (key, line) in annotations]
173
 
 
174
 
 
175
155
def _expand_annotations(annotations, branch, current_rev=None):
176
156
    """Expand a file's annotations into command line UI ready tuples.
177
157
 
183
163
    :param branch: A locked branch to query for revision details.
184
164
    """
185
165
    repository = branch.repository
 
166
    revision_ids = set(o for o, t in annotations)
186
167
    if current_rev is not None:
187
 
        # This can probably become a function on MutableTree, get_revno_map there,
188
 
        # or something.
 
168
        # This can probably become a function on MutableTree, get_revno_map
 
169
        # there, or something.
189
170
        last_revision = current_rev.revision_id
190
171
        # XXX: Partially Cloned from branch, uses the old_get_graph, eep.
191
172
        # XXX: The main difficulty is that we need to inject a single new node
193
174
        #      Once KnownGraph gets an 'add_node()' function, we can use
194
175
        #      VF.get_known_graph_ancestry().
195
176
        graph = repository.get_graph()
196
 
        revision_graph = dict(((key, value) for key, value in
197
 
            graph.iter_ancestry(current_rev.parent_ids) if value is not None))
 
177
        revision_graph = {
 
178
            key: value for key, value in
 
179
            graph.iter_ancestry(current_rev.parent_ids) if value is not None}
198
180
        revision_graph = _strip_NULL_ghosts(revision_graph)
199
181
        revision_graph[last_revision] = current_rev.parent_ids
200
182
        merge_sorted_revisions = tsort.merge_sort(
202
184
            last_revision,
203
185
            None,
204
186
            generate_revno=True)
205
 
        revision_id_to_revno = dict((rev_id, revno)
 
187
        revision_id_to_revno = {
 
188
            rev_id: revno
206
189
            for seq_num, rev_id, depth, revno, end_of_merge in
207
 
                merge_sorted_revisions)
 
190
            merge_sorted_revisions}
208
191
    else:
 
192
        # TODO(jelmer): Only look up the revision ids that we need (i.e. those
 
193
        # in revision_ids). Possibly add a HPSS call that can look those up
 
194
        # in bulk over HPSS.
209
195
        revision_id_to_revno = branch.get_revision_id_to_revno_map()
210
196
    last_origin = None
211
 
    revision_ids = set(o for o, t in annotations)
212
197
    revisions = {}
213
198
    if CURRENT_REVISION in revision_ids:
214
199
        revision_id_to_revno[CURRENT_REVISION] = (
215
200
            "%d?" % (branch.revno() + 1),)
216
201
        revisions[CURRENT_REVISION] = current_rev
217
 
    revision_ids = [o for o in revision_ids if
218
 
                    repository.has_revision(o)]
219
 
    revisions.update((r.revision_id, r) for r in
220
 
                     repository.get_revisions(revision_ids))
 
202
    revisions.update(
 
203
        entry for entry in
 
204
        repository.iter_revisions(revision_ids)
 
205
        if entry[1] is not None)
221
206
    for origin, text in annotations:
222
 
        text = text.rstrip('\r\n')
 
207
        text = text.rstrip(b'\r\n')
223
208
        if origin == last_origin:
224
 
            (revno_str, author, date_str) = ('','','')
 
209
            (revno_str, author, date_str) = ('', '', '')
225
210
        else:
226
211
            last_origin = origin
227
212
            if origin not in revisions:
228
 
                (revno_str, author, date_str) = ('?','?','?')
 
213
                (revno_str, author, date_str) = ('?', '?', '?')
229
214
            else:
230
 
                revno_str = '.'.join(str(i) for i in
231
 
                                            revision_id_to_revno[origin])
 
215
                revno_str = '.'.join(
 
216
                    str(i) for i in revision_id_to_revno[origin])
232
217
            rev = revisions[origin]
233
218
            tz = rev.timezone or 0
234
219
            date_str = time.strftime('%Y%m%d',
238
223
            author = rev.get_apparent_authors()[0]
239
224
            try:
240
225
                author = extract_email_address(author)
241
 
            except errors.NoEmailInUsername:
 
226
            except NoEmailInUsername:
242
227
                pass        # use the whole name
243
228
        yield (revno_str, author, date_str, origin, text)
244
229
 
299
284
    new_cur = 0
300
285
    if matching_blocks is None:
301
286
        plain_parent_lines = [l for r, l in parent_lines]
302
 
        matcher = patiencediff.PatienceSequenceMatcher(None,
303
 
            plain_parent_lines, new_lines)
 
287
        matcher = patiencediff.PatienceSequenceMatcher(
 
288
            None, plain_parent_lines, new_lines)
304
289
        matching_blocks = matcher.get_matching_blocks()
305
290
    lines = []
306
291
    for i, j, n in matching_blocks:
307
292
        for line in new_lines[new_cur:j]:
308
293
            lines.append((new_revision_id, line))
309
 
        lines.extend(parent_lines[i:i+n])
 
294
        lines.extend(parent_lines[i:i + n])
310
295
        new_cur = j + n
311
296
    return lines
312
297
 
313
298
 
314
299
def _get_matching_blocks(old, new):
315
 
    matcher = patiencediff.PatienceSequenceMatcher(None,
316
 
        old, new)
 
300
    matcher = patiencediff.PatienceSequenceMatcher(None, old, new)
317
301
    return matcher.get_matching_blocks()
318
302
 
319
303
 
320
304
_break_annotation_tie = None
321
305
 
 
306
 
322
307
def _old_break_annotation_tie(annotated_lines):
323
308
    """Chose an attribution between several possible ones.
324
309
 
366
351
    output_extend = output_lines.extend
367
352
    output_append = output_lines.append
368
353
    # We need to see if any of the unannotated lines match
369
 
    plain_right_subset = [l for a,l in right_lines[start_right:end_right]]
 
354
    plain_right_subset = [l for a, l in right_lines[start_right:end_right]]
370
355
    plain_child_subset = plain_child_lines[start_child:end_child]
371
356
    match_blocks = _get_matching_blocks(plain_right_subset, plain_child_subset)
372
357
 
375
360
    for right_idx, child_idx, match_len in match_blocks:
376
361
        # All the lines that don't match are just passed along
377
362
        if child_idx > last_child_idx:
378
 
            output_extend(child_lines[start_child + last_child_idx
379
 
                                      :start_child + child_idx])
380
 
        for offset in xrange(match_len):
381
 
            left = child_lines[start_child+child_idx+offset]
382
 
            right = right_lines[start_right+right_idx+offset]
 
363
            output_extend(child_lines[start_child + last_child_idx:
 
364
                                      start_child + child_idx])
 
365
        for offset in range(match_len):
 
366
            left = child_lines[start_child + child_idx + offset]
 
367
            right = right_lines[start_right + right_idx + offset]
383
368
            if left[0] == right[0]:
384
369
                # The annotations match, just return the left one
385
370
                output_append(left)
394
379
                else:
395
380
                    heads = heads_provider.heads((left[0], right[0]))
396
381
                    if len(heads) == 1:
397
 
                        output_append((iter(heads).next(), left[1]))
 
382
                        output_append((next(iter(heads)), left[1]))
398
383
                    else:
399
384
                        # Both claim different origins, get a stable result.
400
385
                        # If the result is not stable, there is a risk a
429
414
    # be the bulk of the lines, and they will need no further processing.
430
415
    lines = []
431
416
    lines_extend = lines.extend
432
 
    last_right_idx = 0 # The line just after the last match from the right side
 
417
    # The line just after the last match from the right side
 
418
    last_right_idx = 0
433
419
    last_left_idx = 0
434
420
    matching_left_and_right = _get_matching_blocks(right_parent_lines,
435
421
                                                   annotated_lines)
457
443
 
458
444
 
459
445
try:
460
 
    from bzrlib._annotator_pyx import Annotator
461
 
except ImportError, e:
 
446
    from breezy._annotator_pyx import Annotator
 
447
except ImportError as e:
462
448
    osutils.failed_to_load_extension(e)
463
 
    from bzrlib._annotator_py import Annotator
 
449
    from breezy._annotator_py import Annotator  # noqa: F401