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

  • Committer: Marius Kruger
  • Date: 2010-07-10 21:28:56 UTC
  • mto: (5384.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5385.
  • Revision ID: marius.kruger@enerweb.co.za-20100710212856-uq4ji3go0u5se7hx
* Update documentation
* add NEWS

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