/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: John Arbash Meinel
  • Date: 2011-04-22 14:12:22 UTC
  • mfrom: (5809 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5836.
  • Revision ID: john@arbash-meinel.com-20110422141222-nx2j0hbkihcb8j16
Merge newer bzr.dev and resolve conflicts.
Try to write some documentation about how the _dirblock_state works.
Fix up the tests so that they pass again.

Show diffs side-by-side

added added

removed removed

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