/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/log.py

merge bzr.dev r3975

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
 
18
 
 
19
"""Code to show logs of changes.
 
20
 
 
21
Various flavors of log can be produced:
 
22
 
 
23
* for one file, or the whole tree, and (not done yet) for
 
24
  files in a given directory
 
25
 
 
26
* in "verbose" mode with a description of what changed from one
 
27
  version to the next
 
28
 
 
29
* with file-ids and revision-ids shown
 
30
 
 
31
Logs are actually written out through an abstract LogFormatter
 
32
interface, which allows for different preferred formats.  Plugins can
 
33
register formats too.
 
34
 
 
35
Logs can be produced in either forward (oldest->newest) or reverse
 
36
(newest->oldest) order.
 
37
 
 
38
Logs can be filtered to show only revisions matching a particular
 
39
search string, or within a particular range of revisions.  The range
 
40
can be given as date/times, which are reduced to revisions before
 
41
calling in here.
 
42
 
 
43
In verbose mode we show a summary of what changed in each particular
 
44
revision.  Note that this is the delta for changes in that revision
 
45
relative to its left-most parent, not the delta relative to the last
 
46
logged revision.  So for example if you ask for a verbose log of
 
47
changes touching hello.c you will get a list of those revisions also
 
48
listing other things that were changed in the same revision, but not
 
49
all the changes since the previous revision that touched hello.c.
 
50
"""
 
51
 
 
52
import codecs
 
53
from cStringIO import StringIO
 
54
from itertools import (
 
55
    chain,
 
56
    izip,
 
57
    )
 
58
import re
 
59
import sys
 
60
from warnings import (
 
61
    warn,
 
62
    )
 
63
 
 
64
from bzrlib.lazy_import import lazy_import
 
65
lazy_import(globals(), """
 
66
 
 
67
from bzrlib import (
 
68
    config,
 
69
    diff,
 
70
    errors,
 
71
    repository as _mod_repository,
 
72
    revision as _mod_revision,
 
73
    revisionspec,
 
74
    trace,
 
75
    tsort,
 
76
    )
 
77
""")
 
78
 
 
79
from bzrlib import (
 
80
    registry,
 
81
    )
 
82
from bzrlib.osutils import (
 
83
    format_date,
 
84
    get_terminal_encoding,
 
85
    terminal_width,
 
86
    )
 
87
 
 
88
 
 
89
def find_touching_revisions(branch, file_id):
 
90
    """Yield a description of revisions which affect the file_id.
 
91
 
 
92
    Each returned element is (revno, revision_id, description)
 
93
 
 
94
    This is the list of revisions where the file is either added,
 
95
    modified, renamed or deleted.
 
96
 
 
97
    TODO: Perhaps some way to limit this to only particular revisions,
 
98
    or to traverse a non-mainline set of revisions?
 
99
    """
 
100
    last_ie = None
 
101
    last_path = None
 
102
    revno = 1
 
103
    for revision_id in branch.revision_history():
 
104
        this_inv = branch.repository.get_revision_inventory(revision_id)
 
105
        if file_id in this_inv:
 
106
            this_ie = this_inv[file_id]
 
107
            this_path = this_inv.id2path(file_id)
 
108
        else:
 
109
            this_ie = this_path = None
 
110
 
 
111
        # now we know how it was last time, and how it is in this revision.
 
112
        # are those two states effectively the same or not?
 
113
 
 
114
        if not this_ie and not last_ie:
 
115
            # not present in either
 
116
            pass
 
117
        elif this_ie and not last_ie:
 
118
            yield revno, revision_id, "added " + this_path
 
119
        elif not this_ie and last_ie:
 
120
            # deleted here
 
121
            yield revno, revision_id, "deleted " + last_path
 
122
        elif this_path != last_path:
 
123
            yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
 
124
        elif (this_ie.text_size != last_ie.text_size
 
125
              or this_ie.text_sha1 != last_ie.text_sha1):
 
126
            yield revno, revision_id, "modified " + this_path
 
127
 
 
128
        last_ie = this_ie
 
129
        last_path = this_path
 
130
        revno += 1
 
131
 
 
132
 
 
133
def _enumerate_history(branch):
 
134
    rh = []
 
135
    revno = 1
 
136
    for rev_id in branch.revision_history():
 
137
        rh.append((revno, rev_id))
 
138
        revno += 1
 
139
    return rh
 
140
 
 
141
 
 
142
def show_log(branch,
 
143
             lf,
 
144
             specific_fileid=None,
 
145
             verbose=False,
 
146
             direction='reverse',
 
147
             start_revision=None,
 
148
             end_revision=None,
 
149
             search=None,
 
150
             limit=None,
 
151
             show_diff=False):
 
152
    """Write out human-readable log of commits to this branch.
 
153
 
 
154
    :param lf: The LogFormatter object showing the output.
 
155
 
 
156
    :param specific_fileid: If not None, list only the commits affecting the
 
157
        specified file, rather than all commits.
 
158
 
 
159
    :param verbose: If True show added/changed/deleted/renamed files.
 
160
 
 
161
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
 
162
        earliest to latest.
 
163
 
 
164
    :param start_revision: If not None, only show revisions >= start_revision
 
165
 
 
166
    :param end_revision: If not None, only show revisions <= end_revision
 
167
 
 
168
    :param search: If not None, only show revisions with matching commit
 
169
        messages
 
170
 
 
171
    :param limit: If set, shows only 'limit' revisions, all revisions are shown
 
172
        if None or 0.
 
173
 
 
174
    :param show_diff: If True, output a diff after each revision.
 
175
    """
 
176
    branch.lock_read()
 
177
    try:
 
178
        if getattr(lf, 'begin_log', None):
 
179
            lf.begin_log()
 
180
 
 
181
        _show_log(branch, lf, specific_fileid, verbose, direction,
 
182
                  start_revision, end_revision, search, limit, show_diff)
 
183
 
 
184
        if getattr(lf, 'end_log', None):
 
185
            lf.end_log()
 
186
    finally:
 
187
        branch.unlock()
 
188
 
 
189
 
 
190
def _show_log(branch,
 
191
             lf,
 
192
             specific_fileid=None,
 
193
             verbose=False,
 
194
             direction='reverse',
 
195
             start_revision=None,
 
196
             end_revision=None,
 
197
             search=None,
 
198
             limit=None,
 
199
             show_diff=False):
 
200
    """Worker function for show_log - see show_log."""
 
201
    if not isinstance(lf, LogFormatter):
 
202
        warn("not a LogFormatter instance: %r" % lf)
 
203
    if specific_fileid:
 
204
        trace.mutter('get log for file_id %r', specific_fileid)
 
205
 
 
206
    # Consult the LogFormatter about what it needs and can handle
 
207
    levels_to_display = lf.get_levels()
 
208
    generate_merge_revisions = levels_to_display != 1
 
209
    allow_single_merge_revision = True
 
210
    if not getattr(lf, 'supports_merge_revisions', False):
 
211
        allow_single_merge_revision = getattr(lf,
 
212
            'supports_single_merge_revision', False)
 
213
    view_revisions = calculate_view_revisions(branch, start_revision,
 
214
                                              end_revision, direction,
 
215
                                              specific_fileid,
 
216
                                              generate_merge_revisions,
 
217
                                              allow_single_merge_revision)
 
218
    rev_tag_dict = {}
 
219
    generate_tags = getattr(lf, 'supports_tags', False)
 
220
    if generate_tags and branch.supports_tags():
 
221
        rev_tag_dict = branch.tags.get_reverse_tag_dict()
 
222
    else:
 
223
        rev_tag_dict = {}
 
224
    generate_delta = verbose and getattr(lf, 'supports_delta', False)
 
225
    generate_diff = show_diff and getattr(lf, 'supports_diff', False)
 
226
 
 
227
    # Find and print the interesting revisions
 
228
    repo = branch.repository
 
229
    log_count = 0
 
230
    revision_iterator = _create_log_revision_iterator(branch,
 
231
        start_revision, end_revision, direction, specific_fileid, search,
 
232
        generate_merge_revisions, allow_single_merge_revision,
 
233
        generate_delta, limited_output=limit > 0)
 
234
    for revs in revision_iterator:
 
235
        for (rev_id, revno, merge_depth), rev, delta in revs:
 
236
            # Note: 0 levels means show everything; merge_depth counts from 0
 
237
            if levels_to_display != 0 and merge_depth >= levels_to_display:
 
238
                continue
 
239
            if generate_diff:
 
240
                diff = _format_diff(repo, rev, rev_id, specific_fileid)
 
241
            else:
 
242
                diff = None
 
243
            lr = LogRevision(rev, revno, merge_depth, delta,
 
244
                             rev_tag_dict.get(rev_id), diff)
 
245
            lf.log_revision(lr)
 
246
            if limit:
 
247
                log_count += 1
 
248
                if log_count >= limit:
 
249
                    return
 
250
 
 
251
 
 
252
def _format_diff(repo, rev, rev_id, specific_fileid):
 
253
    if len(rev.parent_ids) == 0:
 
254
        ancestor_id = _mod_revision.NULL_REVISION
 
255
    else:
 
256
        ancestor_id = rev.parent_ids[0]
 
257
    tree_1 = repo.revision_tree(ancestor_id)
 
258
    tree_2 = repo.revision_tree(rev_id)
 
259
    if specific_fileid:
 
260
        specific_files = [tree_2.id2path(specific_fileid)]
 
261
    else:
 
262
        specific_files = None
 
263
    s = StringIO()
 
264
    diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
 
265
        new_label='')
 
266
    return s.getvalue()
 
267
 
 
268
 
 
269
class _StartNotLinearAncestor(Exception):
 
270
    """Raised when a start revision is not found walking left-hand history."""
 
271
 
 
272
 
 
273
def _create_log_revision_iterator(branch, start_revision, end_revision,
 
274
    direction, specific_fileid, search, generate_merge_revisions,
 
275
    allow_single_merge_revision, generate_delta, limited_output=False):
 
276
    """Create a revision iterator for log.
 
277
 
 
278
    :param branch: The branch being logged.
 
279
    :param start_revision: If not None, only show revisions >= start_revision
 
280
    :param end_revision: If not None, only show revisions <= end_revision
 
281
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
 
282
        earliest to latest.
 
283
    :param specific_fileid: If not None, list only the commits affecting the
 
284
        specified file.
 
285
    :param search: If not None, only show revisions with matching commit
 
286
        messages.
 
287
    :param generate_merge_revisions: If False, show only mainline revisions.
 
288
    :param allow_single_merge_revision: If True, logging of a single
 
289
        revision off the mainline is to be allowed
 
290
    :param generate_delta: Whether to generate a delta for each revision.
 
291
    :param limited_output: if True, the user only wants a limited result
 
292
 
 
293
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
294
        delta).
 
295
    """
 
296
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
 
297
        end_revision)
 
298
 
 
299
    # Decide how file-ids are matched: delta-filtering vs per-file graph.
 
300
    # Delta filtering allows revisions to be displayed incrementally
 
301
    # though the total time is much slower for huge repositories: log -v
 
302
    # is the *lower* performance bound. At least until the split
 
303
    # inventory format arrives, per-file-graph needs to remain the
 
304
    # default when no limits are given. Delta filtering should give more
 
305
    # accurate results (e.g. inclusion of FILE deletions) so arguably
 
306
    # it should always be used in the future.
 
307
    use_deltas_for_matching = specific_fileid and (
 
308
            generate_delta or start_rev_id or end_rev_id)
 
309
    delayed_graph_generation = not specific_fileid and (
 
310
            start_rev_id or end_rev_id or limited_output)
 
311
    generate_merges = generate_merge_revisions or (specific_fileid and
 
312
        not use_deltas_for_matching)
 
313
    view_revisions = _calc_view_revisions(branch, start_rev_id, end_rev_id,
 
314
        direction, generate_merges, allow_single_merge_revision,
 
315
        delayed_graph_generation=delayed_graph_generation)
 
316
    search_deltas_for_fileids = None
 
317
    if use_deltas_for_matching:
 
318
        search_deltas_for_fileids = set([specific_fileid])
 
319
    elif specific_fileid:
 
320
        if not isinstance(view_revisions, list):
 
321
            view_revisions = list(view_revisions)
 
322
        view_revisions = _filter_revisions_touching_file_id(branch,
 
323
            specific_fileid, view_revisions,
 
324
            include_merges=generate_merge_revisions)
 
325
    return make_log_rev_iterator(branch, view_revisions, generate_delta,
 
326
        search, file_ids=search_deltas_for_fileids, direction=direction)
 
327
 
 
328
 
 
329
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
 
330
    generate_merge_revisions, allow_single_merge_revision,
 
331
    delayed_graph_generation=False):
 
332
    """Calculate the revisions to view.
 
333
 
 
334
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
 
335
             a list of the same tuples.
 
336
    """
 
337
    br_revno, br_rev_id = branch.last_revision_info()
 
338
    if br_revno == 0:
 
339
        return []
 
340
 
 
341
    # If a single revision is requested, check we can handle it
 
342
    generate_single_revision = (end_rev_id and start_rev_id == end_rev_id and
 
343
        (not generate_merge_revisions or not _has_merges(branch, end_rev_id)))
 
344
    if generate_single_revision:
 
345
        if end_rev_id == br_rev_id:
 
346
            # It's the tip
 
347
            return [(br_rev_id, br_revno, 0)]
 
348
        else:
 
349
            revno = branch.revision_id_to_dotted_revno(end_rev_id)
 
350
            if len(revno) > 1 and not allow_single_merge_revision:
 
351
                # It's a merge revision and the log formatter is
 
352
                # completely brain dead. This "feature" of allowing
 
353
                # log formatters incapable of displaying dotted revnos
 
354
                # ought to be deprecated IMNSHO. IGC 20091022
 
355
                raise errors.BzrCommandError('Selected log formatter only'
 
356
                    ' supports mainline revisions.')
 
357
            revno_str = '.'.join(str(n) for n in revno)
 
358
            return [(end_rev_id, revno_str, 0)]
 
359
 
 
360
    # If we only want to see linear revisions, we can iterate ...
 
361
    if not generate_merge_revisions:
 
362
        result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
 
363
        # If a start limit was given and it's not obviously an
 
364
        # ancestor of the end limit, check it before outputting anything
 
365
        if start_rev_id and not (_is_obvious_ancestor(branch, start_rev_id,
 
366
            end_rev_id)):
 
367
            try:
 
368
                result = list(result)
 
369
            except _StartNotLinearAncestor:
 
370
                raise errors.BzrCommandError('Start revision not found in'
 
371
                    ' left-hand history of end revision.')
 
372
        if direction == 'forward':
 
373
            result = reversed(list(result))
 
374
        return result
 
375
 
 
376
    # On large trees, generating the merge graph can take 30-60 seconds
 
377
    # so we delay doing it until a merge is detected, incrementally
 
378
    # returning initial (non-merge) revisions while we can.
 
379
    initial_revisions = []
 
380
    if delayed_graph_generation:
 
381
        try:
 
382
            for rev_id, revno, depth in \
 
383
                _linear_view_revisions(branch, start_rev_id, end_rev_id):
 
384
                if _has_merges(branch, rev_id):
 
385
                    end_rev_id = rev_id
 
386
                    break
 
387
                else:
 
388
                    initial_revisions.append((rev_id, revno, depth))
 
389
            else:
 
390
                # No merged revisions found
 
391
                if direction == 'reverse':
 
392
                    return initial_revisions
 
393
                elif direction == 'forward':
 
394
                    return reversed(initial_revisions)
 
395
                else:
 
396
                    raise ValueError('invalid direction %r' % direction)
 
397
        except _StartNotLinearAncestor:
 
398
            # A merge was never detected so the lower revision limit can't
 
399
            # be nested down somewhere
 
400
            raise errors.BzrCommandError('Start revision not found in'
 
401
                ' history of end revision.')
 
402
 
 
403
    # A log including nested merges is required. If the direction is reverse,
 
404
    # we rebase the initial merge depths so that the development line is
 
405
    # shown naturally, i.e. just like it is for linear logging. We can easily
 
406
    # make forward the exact opposite display, but showing the merge revisions
 
407
    # indented at the end seems slightly nicer in that case.
 
408
    view_revisions = chain(iter(initial_revisions),
 
409
        _graph_view_revisions(branch, start_rev_id, end_rev_id,
 
410
        rebase_initial_depths=direction == 'reverse'))
 
411
    if direction == 'reverse':
 
412
        return view_revisions
 
413
    elif direction == 'forward':
 
414
        # Forward means oldest first, adjusting for depth.
 
415
        view_revisions = reverse_by_depth(list(view_revisions))
 
416
        return _rebase_merge_depth(view_revisions)
 
417
    else:
 
418
        raise ValueError('invalid direction %r' % direction)
 
419
 
 
420
 
 
421
def _has_merges(branch, rev_id):
 
422
    """Does a revision have multiple parents or not?"""
 
423
    return len(branch.repository.get_revision(rev_id).parent_ids) > 1
 
424
 
 
425
 
 
426
def _is_obvious_ancestor(branch, start_rev_id, end_rev_id):
 
427
    """Is start_rev_id an obvious ancestor of end_rev_id?"""
 
428
    if start_rev_id and end_rev_id:
 
429
        start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
 
430
        end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
 
431
        if len(start_dotted) == 1 and len(end_dotted) == 1:
 
432
            # both on mainline
 
433
            return start_dotted[0] <= end_dotted[0]
 
434
        elif (len(start_dotted) == 3 and len(end_dotted) == 3 and
 
435
            start_dotted[0:1] == end_dotted[0:1]):
 
436
            # both on same development line
 
437
            return start_dotted[2] <= end_dotted[2]
 
438
        else:
 
439
            # not obvious
 
440
            return False
 
441
    return True
 
442
 
 
443
 
 
444
def _linear_view_revisions(branch, start_rev_id, end_rev_id):
 
445
    """Calculate a sequence of revisions to view, newest to oldest.
 
446
 
 
447
    :param start_rev_id: the lower revision-id
 
448
    :param end_rev_id: the upper revision-id
 
449
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
 
450
    :raises _StartNotLinearAncestor: if a start_rev_id is specified but
 
451
      is not found walking the left-hand history
 
452
    """
 
453
    br_revno, br_rev_id = branch.last_revision_info()
 
454
    repo = branch.repository
 
455
    if start_rev_id is None and end_rev_id is None:
 
456
        cur_revno = br_revno
 
457
        for revision_id in repo.iter_reverse_revision_history(br_rev_id):
 
458
            yield revision_id, str(cur_revno), 0
 
459
            cur_revno -= 1
 
460
    else:
 
461
        if end_rev_id is None:
 
462
            end_rev_id = br_rev_id
 
463
        found_start = start_rev_id is None
 
464
        for revision_id in repo.iter_reverse_revision_history(end_rev_id):
 
465
            revno = branch.revision_id_to_dotted_revno(revision_id)
 
466
            revno_str = '.'.join(str(n) for n in revno)
 
467
            if not found_start and revision_id == start_rev_id:
 
468
                yield revision_id, revno_str, 0
 
469
                found_start = True
 
470
                break
 
471
            else:
 
472
                yield revision_id, revno_str, 0
 
473
        else:
 
474
            if not found_start:
 
475
                raise _StartNotLinearAncestor()
 
476
 
 
477
 
 
478
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
 
479
    rebase_initial_depths=True):
 
480
    """Calculate revisions to view including merges, newest to oldest.
 
481
 
 
482
    :param branch: the branch
 
483
    :param start_rev_id: the lower revision-id
 
484
    :param end_rev_id: the upper revision-id
 
485
    :param rebase_initial_depth: should depths be rebased until a mainline
 
486
      revision is found?
 
487
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
 
488
    """
 
489
    view_revisions = branch.iter_merge_sorted_revisions(
 
490
        start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
 
491
        stop_rule="with-merges")
 
492
    if not rebase_initial_depths:
 
493
        for (rev_id, merge_depth, revno, end_of_merge
 
494
             ) in view_revisions:
 
495
            yield rev_id, '.'.join(map(str, revno)), merge_depth
 
496
    else:
 
497
        # We're following a development line starting at a merged revision.
 
498
        # We need to adjust depths down by the initial depth until we find
 
499
        # a depth less than it. Then we use that depth as the adjustment.
 
500
        # If and when we reach the mainline, depth adjustment ends.
 
501
        depth_adjustment = None
 
502
        for (rev_id, merge_depth, revno, end_of_merge
 
503
             ) in view_revisions:
 
504
            if depth_adjustment is None:
 
505
                depth_adjustment = merge_depth
 
506
            if depth_adjustment:
 
507
                if merge_depth < depth_adjustment:
 
508
                    depth_adjustment = merge_depth
 
509
                merge_depth -= depth_adjustment
 
510
            yield rev_id, '.'.join(map(str, revno)), merge_depth
 
511
 
 
512
 
 
513
def calculate_view_revisions(branch, start_revision, end_revision, direction,
 
514
        specific_fileid, generate_merge_revisions, allow_single_merge_revision):
 
515
    """Calculate the revisions to view.
 
516
 
 
517
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
 
518
             a list of the same tuples.
 
519
    """
 
520
    # This method is no longer called by the main code path.
 
521
    # It is retained for API compatibility and may be deprecated
 
522
    # soon. IGC 20090116
 
523
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
 
524
        end_revision)
 
525
    view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
 
526
        direction, generate_merge_revisions or specific_fileid,
 
527
        allow_single_merge_revision))
 
528
    if specific_fileid:
 
529
        view_revisions = _filter_revisions_touching_file_id(branch,
 
530
            specific_fileid, view_revisions,
 
531
            include_merges=generate_merge_revisions)
 
532
    return _rebase_merge_depth(view_revisions)
 
533
 
 
534
 
 
535
def _rebase_merge_depth(view_revisions):
 
536
    """Adjust depths upwards so the top level is 0."""
 
537
    # If either the first or last revision have a merge_depth of 0, we're done
 
538
    if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
 
539
        min_depth = min([d for r,n,d in view_revisions])
 
540
        if min_depth != 0:
 
541
            view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
 
542
    return view_revisions
 
543
 
 
544
 
 
545
def make_log_rev_iterator(branch, view_revisions, generate_delta, search,
 
546
        file_ids=None, direction='reverse'):
 
547
    """Create a revision iterator for log.
 
548
 
 
549
    :param branch: The branch being logged.
 
550
    :param view_revisions: The revisions being viewed.
 
551
    :param generate_delta: Whether to generate a delta for each revision.
 
552
    :param search: A user text search string.
 
553
    :param file_ids: If non empty, only revisions matching one or more of
 
554
      the file-ids are to be kept.
 
555
    :param direction: the direction in which view_revisions is sorted
 
556
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
557
        delta).
 
558
    """
 
559
    # Convert view_revisions into (view, None, None) groups to fit with
 
560
    # the standard interface here.
 
561
    if type(view_revisions) == list:
 
562
        # A single batch conversion is faster than many incremental ones.
 
563
        # As we have all the data, do a batch conversion.
 
564
        nones = [None] * len(view_revisions)
 
565
        log_rev_iterator = iter([zip(view_revisions, nones, nones)])
 
566
    else:
 
567
        def _convert():
 
568
            for view in view_revisions:
 
569
                yield (view, None, None)
 
570
        log_rev_iterator = iter([_convert()])
 
571
    for adapter in log_adapters:
 
572
        # It would be nicer if log adapters were first class objects
 
573
        # with custom parameters. This will do for now. IGC 20090127
 
574
        if adapter == _make_delta_filter:
 
575
            log_rev_iterator = adapter(branch, generate_delta,
 
576
                search, log_rev_iterator, file_ids, direction)
 
577
        else:
 
578
            log_rev_iterator = adapter(branch, generate_delta,
 
579
                search, log_rev_iterator)
 
580
    return log_rev_iterator
 
581
 
 
582
 
 
583
def _make_search_filter(branch, generate_delta, search, log_rev_iterator):
 
584
    """Create a filtered iterator of log_rev_iterator matching on a regex.
 
585
 
 
586
    :param branch: The branch being logged.
 
587
    :param generate_delta: Whether to generate a delta for each revision.
 
588
    :param search: A user text search string.
 
589
    :param log_rev_iterator: An input iterator containing all revisions that
 
590
        could be displayed, in lists.
 
591
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
592
        delta).
 
593
    """
 
594
    if search is None:
 
595
        return log_rev_iterator
 
596
    # Compile the search now to get early errors.
 
597
    searchRE = re.compile(search, re.IGNORECASE)
 
598
    return _filter_message_re(searchRE, log_rev_iterator)
 
599
 
 
600
 
 
601
def _filter_message_re(searchRE, log_rev_iterator):
 
602
    for revs in log_rev_iterator:
 
603
        new_revs = []
 
604
        for (rev_id, revno, merge_depth), rev, delta in revs:
 
605
            if searchRE.search(rev.message):
 
606
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
 
607
        yield new_revs
 
608
 
 
609
 
 
610
def _make_delta_filter(branch, generate_delta, search, log_rev_iterator,
 
611
    fileids=None, direction='reverse'):
 
612
    """Add revision deltas to a log iterator if needed.
 
613
 
 
614
    :param branch: The branch being logged.
 
615
    :param generate_delta: Whether to generate a delta for each revision.
 
616
    :param search: A user text search string.
 
617
    :param log_rev_iterator: An input iterator containing all revisions that
 
618
        could be displayed, in lists.
 
619
    :param fileids: If non empty, only revisions matching one or more of
 
620
      the file-ids are to be kept.
 
621
    :param direction: the direction in which view_revisions is sorted
 
622
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
623
        delta).
 
624
    """
 
625
    if not generate_delta and not fileids:
 
626
        return log_rev_iterator
 
627
    return _generate_deltas(branch.repository, log_rev_iterator,
 
628
        generate_delta, fileids, direction)
 
629
 
 
630
 
 
631
def _generate_deltas(repository, log_rev_iterator, always_delta, fileids,
 
632
    direction):
 
633
    """Create deltas for each batch of revisions in log_rev_iterator.
 
634
    
 
635
    If we're only generating deltas for the sake of filtering against
 
636
    file-ids, we stop generating deltas once all file-ids reach the
 
637
    appropriate life-cycle point. If we're receiving data newest to
 
638
    oldest, then that life-cycle point is 'add', otherwise it's 'remove'.
 
639
    """
 
640
    check_fileids = fileids is not None and len(fileids) > 0
 
641
    if check_fileids:
 
642
        fileid_set = set(fileids)
 
643
        if direction == 'reverse':
 
644
            stop_on = 'add'
 
645
        else:
 
646
            stop_on = 'remove'
 
647
    else:
 
648
        fileid_set = None
 
649
    for revs in log_rev_iterator:
 
650
        # If we were matching against fileids and we've run out,
 
651
        # don't create deltas any longer
 
652
        if check_fileids and not fileid_set:
 
653
            yield revs
 
654
        revisions = [rev[1] for rev in revs]
 
655
        deltas = repository.get_deltas_for_revisions(revisions)
 
656
        new_revs = []
 
657
        for rev, delta in izip(revs, deltas):
 
658
            if check_fileids:
 
659
                if not _delta_matches_fileids(delta, fileid_set, stop_on):
 
660
                    continue
 
661
                elif not always_delta:
 
662
                    # Delta was created just for matching - ditch it
 
663
                    # Note: It would probably be a better UI to return
 
664
                    # a delta filtered by the file-ids, rather than
 
665
                    # None at all. That functional enhancement can
 
666
                    # come later ...
 
667
                    delta = None
 
668
            new_revs.append((rev[0], rev[1], delta))
 
669
        yield new_revs
 
670
 
 
671
 
 
672
def _delta_matches_fileids(delta, fileids, stop_on='add'):
 
673
    """Check is a delta matches one of more file-ids.
 
674
    
 
675
    :param fileids: a set of fileids to match against.
 
676
    :param stop_on: either 'add' or 'remove' - take file-ids out of the
 
677
      fileids set once their add or remove entry is detected respectively
 
678
    """
 
679
    if not fileids:
 
680
        return False
 
681
    result = False
 
682
    for item in delta.added:
 
683
        if item[1] in fileids:
 
684
            if stop_on == 'add':
 
685
                fileids.remove(item[1])
 
686
            result = True
 
687
    for item in delta.removed:
 
688
        if item[1] in fileids:
 
689
            if stop_on == 'delete':
 
690
                fileids.remove(item[1])
 
691
            result = True
 
692
    if result:
 
693
        return True
 
694
    for l in (delta.modified, delta.renamed, delta.kind_changed):
 
695
        for item in l:
 
696
            if item[1] in fileids:
 
697
                return True
 
698
    return False
 
699
 
 
700
 
 
701
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
 
702
    """Extract revision objects from the repository
 
703
 
 
704
    :param branch: The branch being logged.
 
705
    :param generate_delta: Whether to generate a delta for each revision.
 
706
    :param search: A user text search string.
 
707
    :param log_rev_iterator: An input iterator containing all revisions that
 
708
        could be displayed, in lists.
 
709
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
710
        delta).
 
711
    """
 
712
    repository = branch.repository
 
713
    for revs in log_rev_iterator:
 
714
        # r = revision_id, n = revno, d = merge depth
 
715
        revision_ids = [view[0] for view, _, _ in revs]
 
716
        revisions = repository.get_revisions(revision_ids)
 
717
        revs = [(rev[0], revision, rev[2]) for rev, revision in
 
718
            izip(revs, revisions)]
 
719
        yield revs
 
720
 
 
721
 
 
722
def _make_batch_filter(branch, generate_delta, search, log_rev_iterator):
 
723
    """Group up a single large batch into smaller ones.
 
724
 
 
725
    :param branch: The branch being logged.
 
726
    :param generate_delta: Whether to generate a delta for each revision.
 
727
    :param search: A user text search string.
 
728
    :param log_rev_iterator: An input iterator containing all revisions that
 
729
        could be displayed, in lists.
 
730
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
731
        delta).
 
732
    """
 
733
    repository = branch.repository
 
734
    num = 9
 
735
    for batch in log_rev_iterator:
 
736
        batch = iter(batch)
 
737
        while True:
 
738
            step = [detail for _, detail in zip(range(num), batch)]
 
739
            if len(step) == 0:
 
740
                break
 
741
            yield step
 
742
            num = min(int(num * 1.5), 200)
 
743
 
 
744
 
 
745
def _get_revision_limits(branch, start_revision, end_revision):
 
746
    """Get and check revision limits.
 
747
 
 
748
    :param  branch: The branch containing the revisions. 
 
749
 
 
750
    :param  start_revision: The first revision to be logged.
 
751
            For backwards compatibility this may be a mainline integer revno,
 
752
            but for merge revision support a RevisionInfo is expected.
 
753
 
 
754
    :param  end_revision: The last revision to be logged.
 
755
            For backwards compatibility this may be a mainline integer revno,
 
756
            but for merge revision support a RevisionInfo is expected.
 
757
 
 
758
    :return: (start_rev_id, end_rev_id) tuple.
 
759
    """
 
760
    branch_revno, branch_rev_id = branch.last_revision_info()
 
761
    start_rev_id = None
 
762
    if start_revision is None:
 
763
        start_revno = 1
 
764
    else:
 
765
        if isinstance(start_revision, revisionspec.RevisionInfo):
 
766
            start_rev_id = start_revision.rev_id
 
767
            start_revno = start_revision.revno or 1
 
768
        else:
 
769
            branch.check_real_revno(start_revision)
 
770
            start_revno = start_revision
 
771
            start_rev_id = branch.get_rev_id(start_revno)
 
772
 
 
773
    end_rev_id = None
 
774
    if end_revision is None:
 
775
        end_revno = branch_revno
 
776
    else:
 
777
        if isinstance(end_revision, revisionspec.RevisionInfo):
 
778
            end_rev_id = end_revision.rev_id
 
779
            end_revno = end_revision.revno or branch_revno
 
780
        else:
 
781
            branch.check_real_revno(end_revision)
 
782
            end_revno = end_revision
 
783
            end_rev_id = branch.get_rev_id(end_revno)
 
784
 
 
785
    if branch_revno != 0:
 
786
        if (start_rev_id == _mod_revision.NULL_REVISION
 
787
            or end_rev_id == _mod_revision.NULL_REVISION):
 
788
            raise errors.BzrCommandError('Logging revision 0 is invalid.')
 
789
        if start_revno > end_revno:
 
790
            raise errors.BzrCommandError("Start revision must be older than "
 
791
                                         "the end revision.")
 
792
    return (start_rev_id, end_rev_id)
 
793
 
 
794
 
 
795
def _get_mainline_revs(branch, start_revision, end_revision):
 
796
    """Get the mainline revisions from the branch.
 
797
    
 
798
    Generates the list of mainline revisions for the branch.
 
799
    
 
800
    :param  branch: The branch containing the revisions. 
 
801
 
 
802
    :param  start_revision: The first revision to be logged.
 
803
            For backwards compatibility this may be a mainline integer revno,
 
804
            but for merge revision support a RevisionInfo is expected.
 
805
 
 
806
    :param  end_revision: The last revision to be logged.
 
807
            For backwards compatibility this may be a mainline integer revno,
 
808
            but for merge revision support a RevisionInfo is expected.
 
809
 
 
810
    :return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
 
811
    """
 
812
    branch_revno, branch_last_revision = branch.last_revision_info()
 
813
    if branch_revno == 0:
 
814
        return None, None, None, None
 
815
 
 
816
    # For mainline generation, map start_revision and end_revision to 
 
817
    # mainline revnos. If the revision is not on the mainline choose the 
 
818
    # appropriate extreme of the mainline instead - the extra will be 
 
819
    # filtered later.
 
820
    # Also map the revisions to rev_ids, to be used in the later filtering
 
821
    # stage.
 
822
    start_rev_id = None
 
823
    if start_revision is None:
 
824
        start_revno = 1
 
825
    else:
 
826
        if isinstance(start_revision, revisionspec.RevisionInfo):
 
827
            start_rev_id = start_revision.rev_id
 
828
            start_revno = start_revision.revno or 1
 
829
        else:
 
830
            branch.check_real_revno(start_revision)
 
831
            start_revno = start_revision
 
832
 
 
833
    end_rev_id = None
 
834
    if end_revision is None:
 
835
        end_revno = branch_revno
 
836
    else:
 
837
        if isinstance(end_revision, revisionspec.RevisionInfo):
 
838
            end_rev_id = end_revision.rev_id
 
839
            end_revno = end_revision.revno or branch_revno
 
840
        else:
 
841
            branch.check_real_revno(end_revision)
 
842
            end_revno = end_revision
 
843
 
 
844
    if ((start_rev_id == _mod_revision.NULL_REVISION)
 
845
        or (end_rev_id == _mod_revision.NULL_REVISION)):
 
846
        raise errors.BzrCommandError('Logging revision 0 is invalid.')
 
847
    if start_revno > end_revno:
 
848
        raise errors.BzrCommandError("Start revision must be older than "
 
849
                                     "the end revision.")
 
850
 
 
851
    if end_revno < start_revno:
 
852
        return None, None, None, None
 
853
    cur_revno = branch_revno
 
854
    rev_nos = {}
 
855
    mainline_revs = []
 
856
    for revision_id in branch.repository.iter_reverse_revision_history(
 
857
                        branch_last_revision):
 
858
        if cur_revno < start_revno:
 
859
            # We have gone far enough, but we always add 1 more revision
 
860
            rev_nos[revision_id] = cur_revno
 
861
            mainline_revs.append(revision_id)
 
862
            break
 
863
        if cur_revno <= end_revno:
 
864
            rev_nos[revision_id] = cur_revno
 
865
            mainline_revs.append(revision_id)
 
866
        cur_revno -= 1
 
867
    else:
 
868
        # We walked off the edge of all revisions, so we add a 'None' marker
 
869
        mainline_revs.append(None)
 
870
 
 
871
    mainline_revs.reverse()
 
872
 
 
873
    # override the mainline to look like the revision history.
 
874
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
 
875
 
 
876
 
 
877
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
 
878
    """Filter view_revisions based on revision ranges.
 
879
 
 
880
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth) 
 
881
            tuples to be filtered.
 
882
 
 
883
    :param start_rev_id: If not NONE specifies the first revision to be logged.
 
884
            If NONE then all revisions up to the end_rev_id are logged.
 
885
 
 
886
    :param end_rev_id: If not NONE specifies the last revision to be logged.
 
887
            If NONE then all revisions up to the end of the log are logged.
 
888
 
 
889
    :return: The filtered view_revisions.
 
890
    """
 
891
    # This method is no longer called by the main code path.
 
892
    # It may be removed soon. IGC 20090127
 
893
    if start_rev_id or end_rev_id:
 
894
        revision_ids = [r for r, n, d in view_revisions]
 
895
        if start_rev_id:
 
896
            start_index = revision_ids.index(start_rev_id)
 
897
        else:
 
898
            start_index = 0
 
899
        if start_rev_id == end_rev_id:
 
900
            end_index = start_index
 
901
        else:
 
902
            if end_rev_id:
 
903
                end_index = revision_ids.index(end_rev_id)
 
904
            else:
 
905
                end_index = len(view_revisions) - 1
 
906
        # To include the revisions merged into the last revision, 
 
907
        # extend end_rev_id down to, but not including, the next rev
 
908
        # with the same or lesser merge_depth
 
909
        end_merge_depth = view_revisions[end_index][2]
 
910
        try:
 
911
            for index in xrange(end_index+1, len(view_revisions)+1):
 
912
                if view_revisions[index][2] <= end_merge_depth:
 
913
                    end_index = index - 1
 
914
                    break
 
915
        except IndexError:
 
916
            # if the search falls off the end then log to the end as well
 
917
            end_index = len(view_revisions) - 1
 
918
        view_revisions = view_revisions[start_index:end_index+1]
 
919
    return view_revisions
 
920
 
 
921
 
 
922
def _filter_revisions_touching_file_id(branch, file_id, view_revisions,
 
923
    include_merges=True):
 
924
    r"""Return the list of revision ids which touch a given file id.
 
925
 
 
926
    The function filters view_revisions and returns a subset.
 
927
    This includes the revisions which directly change the file id,
 
928
    and the revisions which merge these changes. So if the
 
929
    revision graph is::
 
930
        A-.
 
931
        |\ \
 
932
        B C E
 
933
        |/ /
 
934
        D |
 
935
        |\|
 
936
        | F
 
937
        |/
 
938
        G
 
939
 
 
940
    And 'C' changes a file, then both C and D will be returned. F will not be
 
941
    returned even though it brings the changes to C into the branch starting
 
942
    with E. (Note that if we were using F as the tip instead of G, then we
 
943
    would see C, D, F.)
 
944
 
 
945
    This will also be restricted based on a subset of the mainline.
 
946
 
 
947
    :param branch: The branch where we can get text revision information.
 
948
 
 
949
    :param file_id: Filter out revisions that do not touch file_id.
 
950
 
 
951
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
 
952
        tuples. This is the list of revisions which will be filtered. It is
 
953
        assumed that view_revisions is in merge_sort order (i.e. newest
 
954
        revision first ).
 
955
 
 
956
    :param include_merges: include merge revisions in the result or not
 
957
 
 
958
    :return: A list of (revision_id, dotted_revno, merge_depth) tuples.
 
959
    """
 
960
    # Lookup all possible text keys to determine which ones actually modified
 
961
    # the file.
 
962
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
 
963
    # Looking up keys in batches of 1000 can cut the time in half, as well as
 
964
    # memory consumption. GraphIndex *does* like to look for a few keys in
 
965
    # parallel, it just doesn't like looking for *lots* of keys in parallel.
 
966
    # TODO: This code needs to be re-evaluated periodically as we tune the
 
967
    #       indexing layer. We might consider passing in hints as to the known
 
968
    #       access pattern (sparse/clustered, high success rate/low success
 
969
    #       rate). This particular access is clustered with a low success rate.
 
970
    get_parent_map = branch.repository.texts.get_parent_map
 
971
    modified_text_revisions = set()
 
972
    chunk_size = 1000
 
973
    for start in xrange(0, len(text_keys), chunk_size):
 
974
        next_keys = text_keys[start:start + chunk_size]
 
975
        # Only keep the revision_id portion of the key
 
976
        modified_text_revisions.update(
 
977
            [k[1] for k in get_parent_map(next_keys)])
 
978
    del text_keys, next_keys
 
979
 
 
980
    result = []
 
981
    # Track what revisions will merge the current revision, replace entries
 
982
    # with 'None' when they have been added to result
 
983
    current_merge_stack = [None]
 
984
    for info in view_revisions:
 
985
        rev_id, revno, depth = info
 
986
        if depth == len(current_merge_stack):
 
987
            current_merge_stack.append(info)
 
988
        else:
 
989
            del current_merge_stack[depth + 1:]
 
990
            current_merge_stack[-1] = info
 
991
 
 
992
        if rev_id in modified_text_revisions:
 
993
            # This needs to be logged, along with the extra revisions
 
994
            for idx in xrange(len(current_merge_stack)):
 
995
                node = current_merge_stack[idx]
 
996
                if node is not None:
 
997
                    if include_merges or node[2] == 0:
 
998
                        result.append(node)
 
999
                        current_merge_stack[idx] = None
 
1000
    return result
 
1001
 
 
1002
 
 
1003
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
 
1004
                       include_merges=True):
 
1005
    """Produce an iterator of revisions to show
 
1006
    :return: an iterator of (revision_id, revno, merge_depth)
 
1007
    (if there is no revno for a revision, None is supplied)
 
1008
    """
 
1009
    # This method is no longer called by the main code path.
 
1010
    # It is retained for API compatibility and may be deprecated
 
1011
    # soon. IGC 20090127
 
1012
    if not include_merges:
 
1013
        revision_ids = mainline_revs[1:]
 
1014
        if direction == 'reverse':
 
1015
            revision_ids.reverse()
 
1016
        for revision_id in revision_ids:
 
1017
            yield revision_id, str(rev_nos[revision_id]), 0
 
1018
        return
 
1019
    graph = branch.repository.get_graph()
 
1020
    # This asks for all mainline revisions, which means we only have to spider
 
1021
    # sideways, rather than depth history. That said, its still size-of-history
 
1022
    # and should be addressed.
 
1023
    # mainline_revisions always includes an extra revision at the beginning, so
 
1024
    # don't request it.
 
1025
    parent_map = dict(((key, value) for key, value in
 
1026
        graph.iter_ancestry(mainline_revs[1:]) if value is not None))
 
1027
    # filter out ghosts; merge_sort errors on ghosts.
 
1028
    rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
 
1029
    merge_sorted_revisions = tsort.merge_sort(
 
1030
        rev_graph,
 
1031
        mainline_revs[-1],
 
1032
        mainline_revs,
 
1033
        generate_revno=True)
 
1034
 
 
1035
    if direction == 'forward':
 
1036
        # forward means oldest first.
 
1037
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
 
1038
    elif direction != 'reverse':
 
1039
        raise ValueError('invalid direction %r' % direction)
 
1040
 
 
1041
    for (sequence, rev_id, merge_depth, revno, end_of_merge
 
1042
         ) in merge_sorted_revisions:
 
1043
        yield rev_id, '.'.join(map(str, revno)), merge_depth
 
1044
 
 
1045
 
 
1046
def reverse_by_depth(merge_sorted_revisions, _depth=0):
 
1047
    """Reverse revisions by depth.
 
1048
 
 
1049
    Revisions with a different depth are sorted as a group with the previous
 
1050
    revision of that depth.  There may be no topological justification for this,
 
1051
    but it looks much nicer.
 
1052
    """
 
1053
    # Add a fake revision at start so that we can always attach sub revisions
 
1054
    merge_sorted_revisions = [(None, None, _depth)] + merge_sorted_revisions
 
1055
    zd_revisions = []
 
1056
    for val in merge_sorted_revisions:
 
1057
        if val[2] == _depth:
 
1058
            # Each revision at the current depth becomes a chunk grouping all
 
1059
            # higher depth revisions.
 
1060
            zd_revisions.append([val])
 
1061
        else:
 
1062
            zd_revisions[-1].append(val)
 
1063
    for revisions in zd_revisions:
 
1064
        if len(revisions) > 1:
 
1065
            # We have higher depth revisions, let reverse them locally
 
1066
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
 
1067
    zd_revisions.reverse()
 
1068
    result = []
 
1069
    for chunk in zd_revisions:
 
1070
        result.extend(chunk)
 
1071
    if _depth == 0:
 
1072
        # Top level call, get rid of the fake revisions that have been added
 
1073
        result = [r for r in result if r[0] is not None and r[1] is not None]
 
1074
    return result
 
1075
 
 
1076
 
 
1077
class LogRevision(object):
 
1078
    """A revision to be logged (by LogFormatter.log_revision).
 
1079
 
 
1080
    A simple wrapper for the attributes of a revision to be logged.
 
1081
    The attributes may or may not be populated, as determined by the 
 
1082
    logging options and the log formatter capabilities.
 
1083
    """
 
1084
 
 
1085
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
 
1086
                 tags=None, diff=None):
 
1087
        self.rev = rev
 
1088
        self.revno = str(revno)
 
1089
        self.merge_depth = merge_depth
 
1090
        self.delta = delta
 
1091
        self.tags = tags
 
1092
        self.diff = diff
 
1093
 
 
1094
 
 
1095
class LogFormatter(object):
 
1096
    """Abstract class to display log messages.
 
1097
 
 
1098
    At a minimum, a derived class must implement the log_revision method.
 
1099
 
 
1100
    If the LogFormatter needs to be informed of the beginning or end of
 
1101
    a log it should implement the begin_log and/or end_log hook methods.
 
1102
 
 
1103
    A LogFormatter should define the following supports_XXX flags 
 
1104
    to indicate which LogRevision attributes it supports:
 
1105
 
 
1106
    - supports_delta must be True if this log formatter supports delta.
 
1107
        Otherwise the delta attribute may not be populated.  The 'delta_format'
 
1108
        attribute describes whether the 'short_status' format (1) or the long
 
1109
        one (2) should be used.
 
1110
 
 
1111
    - supports_merge_revisions must be True if this log formatter supports 
 
1112
        merge revisions.  If not, and if supports_single_merge_revision is
 
1113
        also not True, then only mainline revisions will be passed to the 
 
1114
        formatter.
 
1115
 
 
1116
    - preferred_levels is the number of levels this formatter defaults to.
 
1117
        The default value is zero meaning display all levels.
 
1118
        This value is only relevant if supports_merge_revisions is True.
 
1119
 
 
1120
    - supports_single_merge_revision must be True if this log formatter
 
1121
        supports logging only a single merge revision.  This flag is
 
1122
        only relevant if supports_merge_revisions is not True.
 
1123
 
 
1124
    - supports_tags must be True if this log formatter supports tags.
 
1125
        Otherwise the tags attribute may not be populated.
 
1126
 
 
1127
    - supports_diff must be True if this log formatter supports diffs.
 
1128
        Otherwise the diff attribute may not be populated.
 
1129
 
 
1130
    Plugins can register functions to show custom revision properties using
 
1131
    the properties_handler_registry. The registered function
 
1132
    must respect the following interface description:
 
1133
        def my_show_properties(properties_dict):
 
1134
            # code that returns a dict {'name':'value'} of the properties 
 
1135
            # to be shown
 
1136
    """
 
1137
    preferred_levels = 0
 
1138
 
 
1139
    def __init__(self, to_file, show_ids=False, show_timezone='original',
 
1140
                 delta_format=None, levels=None):
 
1141
        """Create a LogFormatter.
 
1142
 
 
1143
        :param to_file: the file to output to
 
1144
        :param show_ids: if True, revision-ids are to be displayed
 
1145
        :param show_timezone: the timezone to use
 
1146
        :param delta_format: the level of delta information to display
 
1147
          or None to leave it u to the formatter to decide
 
1148
        :param levels: the number of levels to display; None or -1 to
 
1149
          let the log formatter decide.
 
1150
        """
 
1151
        self.to_file = to_file
 
1152
        self.show_ids = show_ids
 
1153
        self.show_timezone = show_timezone
 
1154
        if delta_format is None:
 
1155
            # Ensures backward compatibility
 
1156
            delta_format = 2 # long format
 
1157
        self.delta_format = delta_format
 
1158
        self.levels = levels
 
1159
 
 
1160
    def get_levels(self):
 
1161
        """Get the number of levels to display or 0 for all."""
 
1162
        if getattr(self, 'supports_merge_revisions', False):
 
1163
            if self.levels is None or self.levels == -1:
 
1164
                return self.preferred_levels
 
1165
            else:
 
1166
                return self.levels
 
1167
        return 1
 
1168
 
 
1169
    def log_revision(self, revision):
 
1170
        """Log a revision.
 
1171
 
 
1172
        :param  revision:   The LogRevision to be logged.
 
1173
        """
 
1174
        raise NotImplementedError('not implemented in abstract base')
 
1175
 
 
1176
    def short_committer(self, rev):
 
1177
        name, address = config.parse_username(rev.committer)
 
1178
        if name:
 
1179
            return name
 
1180
        return address
 
1181
 
 
1182
    def short_author(self, rev):
 
1183
        name, address = config.parse_username(rev.get_apparent_author())
 
1184
        if name:
 
1185
            return name
 
1186
        return address
 
1187
 
 
1188
    def show_properties(self, revision, indent):
 
1189
        """Displays the custom properties returned by each registered handler.
 
1190
        
 
1191
        If a registered handler raises an error it is propagated.
 
1192
        """
 
1193
        for key, handler in properties_handler_registry.iteritems():
 
1194
            for key, value in handler(revision).items():
 
1195
                self.to_file.write(indent + key + ': ' + value + '\n')
 
1196
 
 
1197
    def show_diff(self, to_file, diff, indent):
 
1198
        for l in diff.rstrip().split('\n'):
 
1199
            to_file.write(indent + '%s\n' % (l,))
 
1200
 
 
1201
 
 
1202
class LongLogFormatter(LogFormatter):
 
1203
 
 
1204
    supports_merge_revisions = True
 
1205
    supports_delta = True
 
1206
    supports_tags = True
 
1207
    supports_diff = True
 
1208
 
 
1209
    def log_revision(self, revision):
 
1210
        """Log a revision, either merged or not."""
 
1211
        indent = '    ' * revision.merge_depth
 
1212
        to_file = self.to_file
 
1213
        to_file.write(indent + '-' * 60 + '\n')
 
1214
        if revision.revno is not None:
 
1215
            to_file.write(indent + 'revno: %s\n' % (revision.revno,))
 
1216
        if revision.tags:
 
1217
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
 
1218
        if self.show_ids:
 
1219
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
 
1220
            to_file.write('\n')
 
1221
            for parent_id in revision.rev.parent_ids:
 
1222
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
 
1223
        self.show_properties(revision.rev, indent)
 
1224
 
 
1225
        author = revision.rev.properties.get('author', None)
 
1226
        if author is not None:
 
1227
            to_file.write(indent + 'author: %s\n' % (author,))
 
1228
        to_file.write(indent + 'committer: %s\n' % (revision.rev.committer,))
 
1229
 
 
1230
        branch_nick = revision.rev.properties.get('branch-nick', None)
 
1231
        if branch_nick is not None:
 
1232
            to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
 
1233
 
 
1234
        date_str = format_date(revision.rev.timestamp,
 
1235
                               revision.rev.timezone or 0,
 
1236
                               self.show_timezone)
 
1237
        to_file.write(indent + 'timestamp: %s\n' % (date_str,))
 
1238
 
 
1239
        to_file.write(indent + 'message:\n')
 
1240
        if not revision.rev.message:
 
1241
            to_file.write(indent + '  (no message)\n')
 
1242
        else:
 
1243
            message = revision.rev.message.rstrip('\r\n')
 
1244
            for l in message.split('\n'):
 
1245
                to_file.write(indent + '  %s\n' % (l,))
 
1246
        if revision.delta is not None:
 
1247
            # We don't respect delta_format for compatibility
 
1248
            revision.delta.show(to_file, self.show_ids, indent=indent,
 
1249
                                short_status=False)
 
1250
        if revision.diff is not None:
 
1251
            to_file.write(indent + 'diff:\n')
 
1252
            # Note: we explicitly don't indent the diff (relative to the
 
1253
            # revision information) so that the output can be fed to patch -p0
 
1254
            self.show_diff(to_file, revision.diff, indent)
 
1255
 
 
1256
 
 
1257
class ShortLogFormatter(LogFormatter):
 
1258
 
 
1259
    supports_merge_revisions = True
 
1260
    preferred_levels = 1
 
1261
    supports_delta = True
 
1262
    supports_tags = True
 
1263
    supports_diff = True
 
1264
 
 
1265
    def __init__(self, *args, **kwargs):
 
1266
        super(ShortLogFormatter, self).__init__(*args, **kwargs)
 
1267
        self.revno_width_by_depth = {}
 
1268
 
 
1269
    def log_revision(self, revision):
 
1270
        # We need two indents: one per depth and one for the information
 
1271
        # relative to that indent. Most mainline revnos are 5 chars or
 
1272
        # less while dotted revnos are typically 11 chars or less. Once
 
1273
        # calculated, we need to remember the offset for a given depth
 
1274
        # as we might be starting from a dotted revno in the first column
 
1275
        # and we want subsequent mainline revisions to line up.
 
1276
        depth = revision.merge_depth
 
1277
        indent = '    ' * depth
 
1278
        revno_width = self.revno_width_by_depth.get(depth)
 
1279
        if revno_width is None:
 
1280
            if revision.revno.find('.') == -1:
 
1281
                # mainline revno, e.g. 12345
 
1282
                revno_width = 5
 
1283
            else:
 
1284
                # dotted revno, e.g. 12345.10.55
 
1285
                revno_width = 11
 
1286
            self.revno_width_by_depth[depth] = revno_width
 
1287
        offset = ' ' * (revno_width + 1)
 
1288
 
 
1289
        to_file = self.to_file
 
1290
        is_merge = ''
 
1291
        if len(revision.rev.parent_ids) > 1:
 
1292
            is_merge = ' [merge]'
 
1293
        tags = ''
 
1294
        if revision.tags:
 
1295
            tags = ' {%s}' % (', '.join(revision.tags))
 
1296
        to_file.write(indent + "%*s %s\t%s%s%s\n" % (revno_width,
 
1297
                revision.revno, self.short_author(revision.rev),
 
1298
                format_date(revision.rev.timestamp,
 
1299
                            revision.rev.timezone or 0,
 
1300
                            self.show_timezone, date_fmt="%Y-%m-%d",
 
1301
                            show_offset=False),
 
1302
                tags, is_merge))
 
1303
        if self.show_ids:
 
1304
            to_file.write(indent + offset + 'revision-id:%s\n'
 
1305
                          % (revision.rev.revision_id,))
 
1306
        if not revision.rev.message:
 
1307
            to_file.write(indent + offset + '(no message)\n')
 
1308
        else:
 
1309
            message = revision.rev.message.rstrip('\r\n')
 
1310
            for l in message.split('\n'):
 
1311
                to_file.write(indent + offset + '%s\n' % (l,))
 
1312
 
 
1313
        if revision.delta is not None:
 
1314
            revision.delta.show(to_file, self.show_ids, indent=indent + offset,
 
1315
                                short_status=self.delta_format==1)
 
1316
        if revision.diff is not None:
 
1317
            self.show_diff(to_file, revision.diff, '      ')
 
1318
        to_file.write('\n')
 
1319
 
 
1320
 
 
1321
class LineLogFormatter(LogFormatter):
 
1322
 
 
1323
    supports_merge_revisions = True
 
1324
    preferred_levels = 1
 
1325
    supports_tags = True
 
1326
 
 
1327
    def __init__(self, *args, **kwargs):
 
1328
        super(LineLogFormatter, self).__init__(*args, **kwargs)
 
1329
        self._max_chars = terminal_width() - 1
 
1330
 
 
1331
    def truncate(self, str, max_len):
 
1332
        if len(str) <= max_len:
 
1333
            return str
 
1334
        return str[:max_len-3]+'...'
 
1335
 
 
1336
    def date_string(self, rev):
 
1337
        return format_date(rev.timestamp, rev.timezone or 0,
 
1338
                           self.show_timezone, date_fmt="%Y-%m-%d",
 
1339
                           show_offset=False)
 
1340
 
 
1341
    def message(self, rev):
 
1342
        if not rev.message:
 
1343
            return '(no message)'
 
1344
        else:
 
1345
            return rev.message
 
1346
 
 
1347
    def log_revision(self, revision):
 
1348
        indent = '  ' * revision.merge_depth
 
1349
        self.to_file.write(self.log_string(revision.revno, revision.rev,
 
1350
            self._max_chars, revision.tags, indent))
 
1351
        self.to_file.write('\n')
 
1352
 
 
1353
    def log_string(self, revno, rev, max_chars, tags=None, prefix=''):
 
1354
        """Format log info into one string. Truncate tail of string
 
1355
        :param  revno:      revision number or None.
 
1356
                            Revision numbers counts from 1.
 
1357
        :param  rev:        revision object
 
1358
        :param  max_chars:  maximum length of resulting string
 
1359
        :param  tags:       list of tags or None
 
1360
        :param  prefix:     string to prefix each line
 
1361
        :return:            formatted truncated string
 
1362
        """
 
1363
        out = []
 
1364
        if revno:
 
1365
            # show revno only when is not None
 
1366
            out.append("%s:" % revno)
 
1367
        out.append(self.truncate(self.short_author(rev), 20))
 
1368
        out.append(self.date_string(rev))
 
1369
        if tags:
 
1370
            tag_str = '{%s}' % (', '.join(tags))
 
1371
            out.append(tag_str)
 
1372
        out.append(rev.get_summary())
 
1373
        return self.truncate(prefix + " ".join(out).rstrip('\n'), max_chars)
 
1374
 
 
1375
 
 
1376
def line_log(rev, max_chars):
 
1377
    lf = LineLogFormatter(None)
 
1378
    return lf.log_string(None, rev, max_chars)
 
1379
 
 
1380
 
 
1381
class LogFormatterRegistry(registry.Registry):
 
1382
    """Registry for log formatters"""
 
1383
 
 
1384
    def make_formatter(self, name, *args, **kwargs):
 
1385
        """Construct a formatter from arguments.
 
1386
 
 
1387
        :param name: Name of the formatter to construct.  'short', 'long' and
 
1388
            'line' are built-in.
 
1389
        """
 
1390
        return self.get(name)(*args, **kwargs)
 
1391
 
 
1392
    def get_default(self, branch):
 
1393
        return self.get(branch.get_config().log_format())
 
1394
 
 
1395
 
 
1396
log_formatter_registry = LogFormatterRegistry()
 
1397
 
 
1398
 
 
1399
log_formatter_registry.register('short', ShortLogFormatter,
 
1400
                                'Moderately short log format')
 
1401
log_formatter_registry.register('long', LongLogFormatter,
 
1402
                                'Detailed log format')
 
1403
log_formatter_registry.register('line', LineLogFormatter,
 
1404
                                'Log format with one line per revision')
 
1405
 
 
1406
 
 
1407
def register_formatter(name, formatter):
 
1408
    log_formatter_registry.register(name, formatter)
 
1409
 
 
1410
 
 
1411
def log_formatter(name, *args, **kwargs):
 
1412
    """Construct a formatter from arguments.
 
1413
 
 
1414
    name -- Name of the formatter to construct; currently 'long', 'short' and
 
1415
        'line' are supported.
 
1416
    """
 
1417
    try:
 
1418
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
 
1419
    except KeyError:
 
1420
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
 
1421
 
 
1422
 
 
1423
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
 
1424
    # deprecated; for compatibility
 
1425
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
 
1426
    lf.show(revno, rev, delta)
 
1427
 
 
1428
 
 
1429
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
 
1430
                           log_format='long'):
 
1431
    """Show the change in revision history comparing the old revision history to the new one.
 
1432
 
 
1433
    :param branch: The branch where the revisions exist
 
1434
    :param old_rh: The old revision history
 
1435
    :param new_rh: The new revision history
 
1436
    :param to_file: A file to write the results to. If None, stdout will be used
 
1437
    """
 
1438
    if to_file is None:
 
1439
        to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
 
1440
            errors='replace')
 
1441
    lf = log_formatter(log_format,
 
1442
                       show_ids=False,
 
1443
                       to_file=to_file,
 
1444
                       show_timezone='original')
 
1445
 
 
1446
    # This is the first index which is different between
 
1447
    # old and new
 
1448
    base_idx = None
 
1449
    for i in xrange(max(len(new_rh),
 
1450
                        len(old_rh))):
 
1451
        if (len(new_rh) <= i
 
1452
            or len(old_rh) <= i
 
1453
            or new_rh[i] != old_rh[i]):
 
1454
            base_idx = i
 
1455
            break
 
1456
 
 
1457
    if base_idx is None:
 
1458
        to_file.write('Nothing seems to have changed\n')
 
1459
        return
 
1460
    ## TODO: It might be nice to do something like show_log
 
1461
    ##       and show the merged entries. But since this is the
 
1462
    ##       removed revisions, it shouldn't be as important
 
1463
    if base_idx < len(old_rh):
 
1464
        to_file.write('*'*60)
 
1465
        to_file.write('\nRemoved Revisions:\n')
 
1466
        for i in range(base_idx, len(old_rh)):
 
1467
            rev = branch.repository.get_revision(old_rh[i])
 
1468
            lr = LogRevision(rev, i+1, 0, None)
 
1469
            lf.log_revision(lr)
 
1470
        to_file.write('*'*60)
 
1471
        to_file.write('\n\n')
 
1472
    if base_idx < len(new_rh):
 
1473
        to_file.write('Added Revisions:\n')
 
1474
        show_log(branch,
 
1475
                 lf,
 
1476
                 None,
 
1477
                 verbose=False,
 
1478
                 direction='forward',
 
1479
                 start_revision=base_idx+1,
 
1480
                 end_revision=len(new_rh),
 
1481
                 search=None)
 
1482
 
 
1483
 
 
1484
def get_history_change(old_revision_id, new_revision_id, repository):
 
1485
    """Calculate the uncommon lefthand history between two revisions.
 
1486
 
 
1487
    :param old_revision_id: The original revision id.
 
1488
    :param new_revision_id: The new revision id.
 
1489
    :param repository: The repository to use for the calculation.
 
1490
 
 
1491
    return old_history, new_history
 
1492
    """
 
1493
    old_history = []
 
1494
    old_revisions = set()
 
1495
    new_history = []
 
1496
    new_revisions = set()
 
1497
    new_iter = repository.iter_reverse_revision_history(new_revision_id)
 
1498
    old_iter = repository.iter_reverse_revision_history(old_revision_id)
 
1499
    stop_revision = None
 
1500
    do_old = True
 
1501
    do_new = True
 
1502
    while do_new or do_old:
 
1503
        if do_new:
 
1504
            try:
 
1505
                new_revision = new_iter.next()
 
1506
            except StopIteration:
 
1507
                do_new = False
 
1508
            else:
 
1509
                new_history.append(new_revision)
 
1510
                new_revisions.add(new_revision)
 
1511
                if new_revision in old_revisions:
 
1512
                    stop_revision = new_revision
 
1513
                    break
 
1514
        if do_old:
 
1515
            try:
 
1516
                old_revision = old_iter.next()
 
1517
            except StopIteration:
 
1518
                do_old = False
 
1519
            else:
 
1520
                old_history.append(old_revision)
 
1521
                old_revisions.add(old_revision)
 
1522
                if old_revision in new_revisions:
 
1523
                    stop_revision = old_revision
 
1524
                    break
 
1525
    new_history.reverse()
 
1526
    old_history.reverse()
 
1527
    if stop_revision is not None:
 
1528
        new_history = new_history[new_history.index(stop_revision) + 1:]
 
1529
        old_history = old_history[old_history.index(stop_revision) + 1:]
 
1530
    return old_history, new_history
 
1531
 
 
1532
 
 
1533
def show_branch_change(branch, output, old_revno, old_revision_id):
 
1534
    """Show the changes made to a branch.
 
1535
 
 
1536
    :param branch: The branch to show changes about.
 
1537
    :param output: A file-like object to write changes to.
 
1538
    :param old_revno: The revno of the old tip.
 
1539
    :param old_revision_id: The revision_id of the old tip.
 
1540
    """
 
1541
    new_revno, new_revision_id = branch.last_revision_info()
 
1542
    old_history, new_history = get_history_change(old_revision_id,
 
1543
                                                  new_revision_id,
 
1544
                                                  branch.repository)
 
1545
    if old_history == [] and new_history == []:
 
1546
        output.write('Nothing seems to have changed\n')
 
1547
        return
 
1548
 
 
1549
    log_format = log_formatter_registry.get_default(branch)
 
1550
    lf = log_format(show_ids=False, to_file=output, show_timezone='original')
 
1551
    if old_history != []:
 
1552
        output.write('*'*60)
 
1553
        output.write('\nRemoved Revisions:\n')
 
1554
        show_flat_log(branch.repository, old_history, old_revno, lf)
 
1555
        output.write('*'*60)
 
1556
        output.write('\n\n')
 
1557
    if new_history != []:
 
1558
        output.write('Added Revisions:\n')
 
1559
        start_revno = new_revno - len(new_history) + 1
 
1560
        show_log(branch, lf, None, verbose=False, direction='forward',
 
1561
                 start_revision=start_revno,)
 
1562
 
 
1563
 
 
1564
def show_flat_log(repository, history, last_revno, lf):
 
1565
    """Show a simple log of the specified history.
 
1566
 
 
1567
    :param repository: The repository to retrieve revisions from.
 
1568
    :param history: A list of revision_ids indicating the lefthand history.
 
1569
    :param last_revno: The revno of the last revision_id in the history.
 
1570
    :param lf: The log formatter to use.
 
1571
    """
 
1572
    start_revno = last_revno - len(history) + 1
 
1573
    revisions = repository.get_revisions(history)
 
1574
    for i, rev in enumerate(revisions):
 
1575
        lr = LogRevision(rev, i + last_revno, 0, None)
 
1576
        lf.log_revision(lr)
 
1577
 
 
1578
 
 
1579
def _get_fileid_to_log(revision, tree, b, fp):
 
1580
    """Find the file-id to log for a file path in a revision range.
 
1581
 
 
1582
    :param revision: the revision range as parsed on the command line
 
1583
    :param tree: the working tree, if any
 
1584
    :param b: the branch
 
1585
    :param fp: file path
 
1586
    """
 
1587
    if revision is None:
 
1588
        if tree is None:
 
1589
            tree = b.basis_tree()
 
1590
        file_id = tree.path2id(fp)
 
1591
        if file_id is None:
 
1592
            # go back to when time began
 
1593
            try:
 
1594
                rev1 = b.get_rev_id(1)
 
1595
            except errors.NoSuchRevision:
 
1596
                # No history at all
 
1597
                file_id = None
 
1598
            else:
 
1599
                tree = b.repository.revision_tree(rev1)
 
1600
                file_id = tree.path2id(fp)
 
1601
 
 
1602
    elif len(revision) == 1:
 
1603
        # One revision given - file must exist in it
 
1604
        tree = revision[0].as_tree(b)
 
1605
        file_id = tree.path2id(fp)
 
1606
 
 
1607
    elif len(revision) == 2:
 
1608
        # Revision range given. Get the file-id from the end tree.
 
1609
        # If that fails, try the start tree.
 
1610
        rev_id = revision[1].as_revision_id(b)
 
1611
        if rev_id is None:
 
1612
            tree = b.basis_tree()
 
1613
        else:
 
1614
            tree = revision[1].as_tree(b)
 
1615
        file_id = tree.path2id(fp)
 
1616
        if file_id is None:
 
1617
            rev_id = revision[0].as_revision_id(b)
 
1618
            if rev_id is None:
 
1619
                rev1 = b.get_rev_id(1)
 
1620
                tree = b.repository.revision_tree(rev1)
 
1621
            else:
 
1622
                tree = revision[0].as_tree(b)
 
1623
            file_id = tree.path2id(fp)
 
1624
    else:
 
1625
        raise errors.BzrCommandError(
 
1626
            'bzr log --revision takes one or two values.')
 
1627
    return file_id
 
1628
 
 
1629
 
 
1630
properties_handler_registry = registry.Registry()
 
1631
properties_handler_registry.register_lazy("foreign",
 
1632
                                          "bzrlib.foreign",
 
1633
                                          "show_foreign_properties")
 
1634
 
 
1635
 
 
1636
# adapters which revision ids to log are filtered. When log is called, the
 
1637
# log_rev_iterator is adapted through each of these factory methods.
 
1638
# Plugins are welcome to mutate this list in any way they like - as long
 
1639
# as the overall behaviour is preserved. At this point there is no extensible
 
1640
# mechanism for getting parameters to each factory method, and until there is
 
1641
# this won't be considered a stable api.
 
1642
log_adapters = [
 
1643
    # core log logic
 
1644
    _make_batch_filter,
 
1645
    # read revision objects
 
1646
    _make_revision_objects,
 
1647
    # filter on log messages
 
1648
    _make_search_filter,
 
1649
    # generate deltas for things we will show
 
1650
    _make_delta_filter
 
1651
    ]