/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

fix tests relying on trailing whitespace by replacing it with \x20.

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 itertools import (
 
54
    izip,
 
55
    )
 
56
import re
 
57
import sys
 
58
from warnings import (
 
59
    warn,
 
60
    )
 
61
 
 
62
from bzrlib.lazy_import import lazy_import
 
63
lazy_import(globals(), """
 
64
 
 
65
from bzrlib import (
 
66
    config,
 
67
    errors,
 
68
    repository as _mod_repository,
 
69
    revision as _mod_revision,
 
70
    revisionspec,
 
71
    trace,
 
72
    tsort,
 
73
    )
 
74
""")
 
75
 
 
76
from bzrlib import (
 
77
    registry,
 
78
    )
 
79
from bzrlib.osutils import (
 
80
    format_date,
 
81
    get_terminal_encoding,
 
82
    terminal_width,
 
83
    )
 
84
 
 
85
 
 
86
def find_touching_revisions(branch, file_id):
 
87
    """Yield a description of revisions which affect the file_id.
 
88
 
 
89
    Each returned element is (revno, revision_id, description)
 
90
 
 
91
    This is the list of revisions where the file is either added,
 
92
    modified, renamed or deleted.
 
93
 
 
94
    TODO: Perhaps some way to limit this to only particular revisions,
 
95
    or to traverse a non-mainline set of revisions?
 
96
    """
 
97
    last_ie = None
 
98
    last_path = None
 
99
    revno = 1
 
100
    for revision_id in branch.revision_history():
 
101
        this_inv = branch.repository.get_revision_inventory(revision_id)
 
102
        if file_id in this_inv:
 
103
            this_ie = this_inv[file_id]
 
104
            this_path = this_inv.id2path(file_id)
 
105
        else:
 
106
            this_ie = this_path = None
 
107
 
 
108
        # now we know how it was last time, and how it is in this revision.
 
109
        # are those two states effectively the same or not?
 
110
 
 
111
        if not this_ie and not last_ie:
 
112
            # not present in either
 
113
            pass
 
114
        elif this_ie and not last_ie:
 
115
            yield revno, revision_id, "added " + this_path
 
116
        elif not this_ie and last_ie:
 
117
            # deleted here
 
118
            yield revno, revision_id, "deleted " + last_path
 
119
        elif this_path != last_path:
 
120
            yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
 
121
        elif (this_ie.text_size != last_ie.text_size
 
122
              or this_ie.text_sha1 != last_ie.text_sha1):
 
123
            yield revno, revision_id, "modified " + this_path
 
124
 
 
125
        last_ie = this_ie
 
126
        last_path = this_path
 
127
        revno += 1
 
128
 
 
129
 
 
130
def _enumerate_history(branch):
 
131
    rh = []
 
132
    revno = 1
 
133
    for rev_id in branch.revision_history():
 
134
        rh.append((revno, rev_id))
 
135
        revno += 1
 
136
    return rh
 
137
 
 
138
 
 
139
def show_log(branch,
 
140
             lf,
 
141
             specific_fileid=None,
 
142
             verbose=False,
 
143
             direction='reverse',
 
144
             start_revision=None,
 
145
             end_revision=None,
 
146
             search=None,
 
147
             limit=None):
 
148
    """Write out human-readable log of commits to this branch.
 
149
 
 
150
    :param lf: The LogFormatter object showing the output.
 
151
 
 
152
    :param specific_fileid: If not None, list only the commits affecting the
 
153
        specified file, rather than all commits.
 
154
 
 
155
    :param verbose: If True show added/changed/deleted/renamed files.
 
156
 
 
157
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
 
158
        earliest to latest.
 
159
 
 
160
    :param start_revision: If not None, only show revisions >= start_revision
 
161
 
 
162
    :param end_revision: If not None, only show revisions <= end_revision
 
163
 
 
164
    :param search: If not None, only show revisions with matching commit
 
165
        messages
 
166
 
 
167
    :param limit: If set, shows only 'limit' revisions, all revisions are shown
 
168
        if None or 0.
 
169
    """
 
170
    branch.lock_read()
 
171
    try:
 
172
        if getattr(lf, 'begin_log', None):
 
173
            lf.begin_log()
 
174
 
 
175
        _show_log(branch, lf, specific_fileid, verbose, direction,
 
176
                  start_revision, end_revision, search, limit)
 
177
 
 
178
        if getattr(lf, 'end_log', None):
 
179
            lf.end_log()
 
180
    finally:
 
181
        branch.unlock()
 
182
 
 
183
 
 
184
def _show_log(branch,
 
185
             lf,
 
186
             specific_fileid=None,
 
187
             verbose=False,
 
188
             direction='reverse',
 
189
             start_revision=None,
 
190
             end_revision=None,
 
191
             search=None,
 
192
             limit=None):
 
193
    """Worker function for show_log - see show_log."""
 
194
    if not isinstance(lf, LogFormatter):
 
195
        warn("not a LogFormatter instance: %r" % lf)
 
196
 
 
197
    if specific_fileid:
 
198
        trace.mutter('get log for file_id %r', specific_fileid)
 
199
    generate_merge_revisions = getattr(lf, 'supports_merge_revisions', False)
 
200
    allow_single_merge_revision = getattr(lf,
 
201
        'supports_single_merge_revision', False)
 
202
    view_revisions = calculate_view_revisions(branch, start_revision,
 
203
                                              end_revision, direction,
 
204
                                              specific_fileid,
 
205
                                              generate_merge_revisions,
 
206
                                              allow_single_merge_revision)
 
207
    rev_tag_dict = {}
 
208
    generate_tags = getattr(lf, 'supports_tags', False)
 
209
    if generate_tags:
 
210
        if branch.supports_tags():
 
211
            rev_tag_dict = branch.tags.get_reverse_tag_dict()
 
212
 
 
213
    generate_delta = verbose and getattr(lf, 'supports_delta', False)
 
214
 
 
215
    # now we just print all the revisions
 
216
    log_count = 0
 
217
    revision_iterator = make_log_rev_iterator(branch, view_revisions,
 
218
        generate_delta, search)
 
219
    for revs in revision_iterator:
 
220
        for (rev_id, revno, merge_depth), rev, delta in revs:
 
221
            lr = LogRevision(rev, revno, merge_depth, delta,
 
222
                             rev_tag_dict.get(rev_id))
 
223
            lf.log_revision(lr)
 
224
            if limit:
 
225
                log_count += 1
 
226
                if log_count >= limit:
 
227
                    return
 
228
 
 
229
 
 
230
def calculate_view_revisions(branch, start_revision, end_revision, direction,
 
231
                             specific_fileid, generate_merge_revisions,
 
232
                             allow_single_merge_revision):
 
233
    if (    not generate_merge_revisions
 
234
        and start_revision is end_revision is None
 
235
        and direction == 'reverse'
 
236
        and specific_fileid is None):
 
237
        return _linear_view_revisions(branch)
 
238
 
 
239
    mainline_revs, rev_nos, start_rev_id, end_rev_id = _get_mainline_revs(
 
240
        branch, start_revision, end_revision)
 
241
    if not mainline_revs:
 
242
        return []
 
243
 
 
244
    generate_single_revision = False
 
245
    if ((not generate_merge_revisions)
 
246
        and ((start_rev_id and (start_rev_id not in rev_nos))
 
247
            or (end_rev_id and (end_rev_id not in rev_nos)))):
 
248
        generate_single_revision = ((start_rev_id == end_rev_id)
 
249
            and allow_single_merge_revision)
 
250
        if not generate_single_revision:
 
251
            raise errors.BzrCommandError('Selected log formatter only supports'
 
252
                ' mainline revisions.')
 
253
        generate_merge_revisions = generate_single_revision
 
254
    include_merges = generate_merge_revisions or specific_fileid
 
255
    view_revs_iter = get_view_revisions(mainline_revs, rev_nos, branch,
 
256
                          direction, include_merges=include_merges)
 
257
 
 
258
    if direction == 'reverse':
 
259
        start_rev_id, end_rev_id = end_rev_id, start_rev_id
 
260
    view_revisions = _filter_revision_range(list(view_revs_iter),
 
261
                                            start_rev_id,
 
262
                                            end_rev_id)
 
263
    if view_revisions and generate_single_revision:
 
264
        view_revisions = view_revisions[0:1]
 
265
    if specific_fileid:
 
266
        view_revisions = _filter_revisions_touching_file_id(branch,
 
267
            specific_fileid, view_revisions,
 
268
            include_merges=generate_merge_revisions)
 
269
 
 
270
    # rebase merge_depth - unless there are no revisions or
 
271
    # either the first or last revision have merge_depth = 0.
 
272
    if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
 
273
        min_depth = min([d for r,n,d in view_revisions])
 
274
        if min_depth != 0:
 
275
            view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
 
276
    return view_revisions
 
277
 
 
278
 
 
279
def _linear_view_revisions(branch):
 
280
    start_revno, start_revision_id = branch.last_revision_info()
 
281
    repo = branch.repository
 
282
    revision_ids = repo.iter_reverse_revision_history(start_revision_id)
 
283
    for num, revision_id in enumerate(revision_ids):
 
284
        yield revision_id, str(start_revno - num), 0
 
285
 
 
286
 
 
287
def make_log_rev_iterator(branch, view_revisions, generate_delta, search):
 
288
    """Create a revision iterator for log.
 
289
 
 
290
    :param branch: The branch being logged.
 
291
    :param view_revisions: The revisions being viewed.
 
292
    :param generate_delta: Whether to generate a delta for each revision.
 
293
    :param search: A user text search string.
 
294
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
295
        delta).
 
296
    """
 
297
    # Convert view_revisions into (view, None, None) groups to fit with
 
298
    # the standard interface here.
 
299
    if type(view_revisions) == list:
 
300
        # A single batch conversion is faster than many incremental ones.
 
301
        # As we have all the data, do a batch conversion.
 
302
        nones = [None] * len(view_revisions)
 
303
        log_rev_iterator = iter([zip(view_revisions, nones, nones)])
 
304
    else:
 
305
        def _convert():
 
306
            for view in view_revisions:
 
307
                yield (view, None, None)
 
308
        log_rev_iterator = iter([_convert()])
 
309
    for adapter in log_adapters:
 
310
        log_rev_iterator = adapter(branch, generate_delta, search,
 
311
            log_rev_iterator)
 
312
    return log_rev_iterator
 
313
 
 
314
 
 
315
def _make_search_filter(branch, generate_delta, search, log_rev_iterator):
 
316
    """Create a filtered iterator of log_rev_iterator matching on a regex.
 
317
 
 
318
    :param branch: The branch being logged.
 
319
    :param generate_delta: Whether to generate a delta for each revision.
 
320
    :param search: A user text search string.
 
321
    :param log_rev_iterator: An input iterator containing all revisions that
 
322
        could be displayed, in lists.
 
323
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
324
        delta).
 
325
    """
 
326
    if search is None:
 
327
        return log_rev_iterator
 
328
    # Compile the search now to get early errors.
 
329
    searchRE = re.compile(search, re.IGNORECASE)
 
330
    return _filter_message_re(searchRE, log_rev_iterator)
 
331
 
 
332
 
 
333
def _filter_message_re(searchRE, log_rev_iterator):
 
334
    for revs in log_rev_iterator:
 
335
        new_revs = []
 
336
        for (rev_id, revno, merge_depth), rev, delta in revs:
 
337
            if searchRE.search(rev.message):
 
338
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
 
339
        yield new_revs
 
340
 
 
341
 
 
342
def _make_delta_filter(branch, generate_delta, search, log_rev_iterator):
 
343
    """Add revision deltas to a log iterator if needed.
 
344
 
 
345
    :param branch: The branch being logged.
 
346
    :param generate_delta: Whether to generate a delta for each revision.
 
347
    :param search: A user text search string.
 
348
    :param log_rev_iterator: An input iterator containing all revisions that
 
349
        could be displayed, in lists.
 
350
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
351
        delta).
 
352
    """
 
353
    if not generate_delta:
 
354
        return log_rev_iterator
 
355
    return _generate_deltas(branch.repository, log_rev_iterator)
 
356
 
 
357
 
 
358
def _generate_deltas(repository, log_rev_iterator):
 
359
    """Create deltas for each batch of revisions in log_rev_iterator."""
 
360
    for revs in log_rev_iterator:
 
361
        revisions = [rev[1] for rev in revs]
 
362
        deltas = repository.get_deltas_for_revisions(revisions)
 
363
        revs = [(rev[0], rev[1], delta) for rev, delta in izip(revs, deltas)]
 
364
        yield revs
 
365
 
 
366
 
 
367
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
 
368
    """Extract revision objects from the repository
 
369
 
 
370
    :param branch: The branch being logged.
 
371
    :param generate_delta: Whether to generate a delta for each revision.
 
372
    :param search: A user text search string.
 
373
    :param log_rev_iterator: An input iterator containing all revisions that
 
374
        could be displayed, in lists.
 
375
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
376
        delta).
 
377
    """
 
378
    repository = branch.repository
 
379
    for revs in log_rev_iterator:
 
380
        # r = revision_id, n = revno, d = merge depth
 
381
        revision_ids = [view[0] for view, _, _ in revs]
 
382
        revisions = repository.get_revisions(revision_ids)
 
383
        revs = [(rev[0], revision, rev[2]) for rev, revision in
 
384
            izip(revs, revisions)]
 
385
        yield revs
 
386
 
 
387
 
 
388
def _make_batch_filter(branch, generate_delta, search, log_rev_iterator):
 
389
    """Group up a single large batch into smaller ones.
 
390
 
 
391
    :param branch: The branch being logged.
 
392
    :param generate_delta: Whether to generate a delta for each revision.
 
393
    :param search: A user text search string.
 
394
    :param log_rev_iterator: An input iterator containing all revisions that
 
395
        could be displayed, in lists.
 
396
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
397
        delta).
 
398
    """
 
399
    repository = branch.repository
 
400
    num = 9
 
401
    for batch in log_rev_iterator:
 
402
        batch = iter(batch)
 
403
        while True:
 
404
            step = [detail for _, detail in zip(range(num), batch)]
 
405
            if len(step) == 0:
 
406
                break
 
407
            yield step
 
408
            num = min(int(num * 1.5), 200)
 
409
 
 
410
 
 
411
def _get_mainline_revs(branch, start_revision, end_revision):
 
412
    """Get the mainline revisions from the branch.
 
413
 
 
414
    Generates the list of mainline revisions for the branch.
 
415
 
 
416
    :param  branch: The branch containing the revisions.
 
417
 
 
418
    :param  start_revision: The first revision to be logged.
 
419
            For backwards compatibility this may be a mainline integer revno,
 
420
            but for merge revision support a RevisionInfo is expected.
 
421
 
 
422
    :param  end_revision: The last revision to be logged.
 
423
            For backwards compatibility this may be a mainline integer revno,
 
424
            but for merge revision support a RevisionInfo is expected.
 
425
 
 
426
    :return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
 
427
    """
 
428
    branch_revno, branch_last_revision = branch.last_revision_info()
 
429
    if branch_revno == 0:
 
430
        return None, None, None, None
 
431
 
 
432
    # For mainline generation, map start_revision and end_revision to
 
433
    # mainline revnos. If the revision is not on the mainline choose the
 
434
    # appropriate extreme of the mainline instead - the extra will be
 
435
    # filtered later.
 
436
    # Also map the revisions to rev_ids, to be used in the later filtering
 
437
    # stage.
 
438
    start_rev_id = None
 
439
    if start_revision is None:
 
440
        start_revno = 1
 
441
    else:
 
442
        if isinstance(start_revision, revisionspec.RevisionInfo):
 
443
            start_rev_id = start_revision.rev_id
 
444
            start_revno = start_revision.revno or 1
 
445
        else:
 
446
            branch.check_real_revno(start_revision)
 
447
            start_revno = start_revision
 
448
 
 
449
    end_rev_id = None
 
450
    if end_revision is None:
 
451
        end_revno = branch_revno
 
452
    else:
 
453
        if isinstance(end_revision, revisionspec.RevisionInfo):
 
454
            end_rev_id = end_revision.rev_id
 
455
            end_revno = end_revision.revno or branch_revno
 
456
        else:
 
457
            branch.check_real_revno(end_revision)
 
458
            end_revno = end_revision
 
459
 
 
460
    if ((start_rev_id == _mod_revision.NULL_REVISION)
 
461
        or (end_rev_id == _mod_revision.NULL_REVISION)):
 
462
        raise errors.BzrCommandError('Logging revision 0 is invalid.')
 
463
    if start_revno > end_revno:
 
464
        raise errors.BzrCommandError("Start revision must be older than "
 
465
                                     "the end revision.")
 
466
 
 
467
    if end_revno < start_revno:
 
468
        return None, None, None, None
 
469
    cur_revno = branch_revno
 
470
    rev_nos = {}
 
471
    mainline_revs = []
 
472
    for revision_id in branch.repository.iter_reverse_revision_history(
 
473
                        branch_last_revision):
 
474
        if cur_revno < start_revno:
 
475
            # We have gone far enough, but we always add 1 more revision
 
476
            rev_nos[revision_id] = cur_revno
 
477
            mainline_revs.append(revision_id)
 
478
            break
 
479
        if cur_revno <= end_revno:
 
480
            rev_nos[revision_id] = cur_revno
 
481
            mainline_revs.append(revision_id)
 
482
        cur_revno -= 1
 
483
    else:
 
484
        # We walked off the edge of all revisions, so we add a 'None' marker
 
485
        mainline_revs.append(None)
 
486
 
 
487
    mainline_revs.reverse()
 
488
 
 
489
    # override the mainline to look like the revision history.
 
490
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
 
491
 
 
492
 
 
493
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
 
494
    """Filter view_revisions based on revision ranges.
 
495
 
 
496
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
 
497
            tuples to be filtered.
 
498
 
 
499
    :param start_rev_id: If not NONE specifies the first revision to be logged.
 
500
            If NONE then all revisions up to the end_rev_id are logged.
 
501
 
 
502
    :param end_rev_id: If not NONE specifies the last revision to be logged.
 
503
            If NONE then all revisions up to the end of the log are logged.
 
504
 
 
505
    :return: The filtered view_revisions.
 
506
    """
 
507
    if start_rev_id or end_rev_id:
 
508
        revision_ids = [r for r, n, d in view_revisions]
 
509
        if start_rev_id:
 
510
            start_index = revision_ids.index(start_rev_id)
 
511
        else:
 
512
            start_index = 0
 
513
        if start_rev_id == end_rev_id:
 
514
            end_index = start_index
 
515
        else:
 
516
            if end_rev_id:
 
517
                end_index = revision_ids.index(end_rev_id)
 
518
            else:
 
519
                end_index = len(view_revisions) - 1
 
520
        # To include the revisions merged into the last revision,
 
521
        # extend end_rev_id down to, but not including, the next rev
 
522
        # with the same or lesser merge_depth
 
523
        end_merge_depth = view_revisions[end_index][2]
 
524
        try:
 
525
            for index in xrange(end_index+1, len(view_revisions)+1):
 
526
                if view_revisions[index][2] <= end_merge_depth:
 
527
                    end_index = index - 1
 
528
                    break
 
529
        except IndexError:
 
530
            # if the search falls off the end then log to the end as well
 
531
            end_index = len(view_revisions) - 1
 
532
        view_revisions = view_revisions[start_index:end_index+1]
 
533
    return view_revisions
 
534
 
 
535
 
 
536
def _filter_revisions_touching_file_id(branch, file_id, view_revisions,
 
537
    include_merges=True):
 
538
    r"""Return the list of revision ids which touch a given file id.
 
539
 
 
540
    The function filters view_revisions and returns a subset.
 
541
    This includes the revisions which directly change the file id,
 
542
    and the revisions which merge these changes. So if the
 
543
    revision graph is::
 
544
        A-.
 
545
        |\ \
 
546
        B C E
 
547
        |/ /
 
548
        D |
 
549
        |\|
 
550
        | F
 
551
        |/
 
552
        G
 
553
 
 
554
    And 'C' changes a file, then both C and D will be returned. F will not be
 
555
    returned even though it brings the changes to C into the branch starting
 
556
    with E. (Note that if we were using F as the tip instead of G, then we
 
557
    would see C, D, F.)
 
558
 
 
559
    This will also be restricted based on a subset of the mainline.
 
560
 
 
561
    :param branch: The branch where we can get text revision information.
 
562
 
 
563
    :param file_id: Filter out revisions that do not touch file_id.
 
564
 
 
565
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
 
566
        tuples. This is the list of revisions which will be filtered. It is
 
567
        assumed that view_revisions is in merge_sort order (i.e. newest
 
568
        revision first ).
 
569
 
 
570
    :param include_merges: include merge revisions in the result or not
 
571
 
 
572
    :return: A list of (revision_id, dotted_revno, merge_depth) tuples.
 
573
    """
 
574
    # Lookup all possible text keys to determine which ones actually modified
 
575
    # the file.
 
576
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
 
577
    # Looking up keys in batches of 1000 can cut the time in half, as well as
 
578
    # memory consumption. GraphIndex *does* like to look for a few keys in
 
579
    # parallel, it just doesn't like looking for *lots* of keys in parallel.
 
580
    # TODO: This code needs to be re-evaluated periodically as we tune the
 
581
    #       indexing layer. We might consider passing in hints as to the known
 
582
    #       access pattern (sparse/clustered, high success rate/low success
 
583
    #       rate). This particular access is clustered with a low success rate.
 
584
    get_parent_map = branch.repository.texts.get_parent_map
 
585
    modified_text_revisions = set()
 
586
    chunk_size = 1000
 
587
    for start in xrange(0, len(text_keys), chunk_size):
 
588
        next_keys = text_keys[start:start + chunk_size]
 
589
        # Only keep the revision_id portion of the key
 
590
        modified_text_revisions.update(
 
591
            [k[1] for k in get_parent_map(next_keys)])
 
592
    del text_keys, next_keys
 
593
 
 
594
    result = []
 
595
    # Track what revisions will merge the current revision, replace entries
 
596
    # with 'None' when they have been added to result
 
597
    current_merge_stack = [None]
 
598
    for info in view_revisions:
 
599
        rev_id, revno, depth = info
 
600
        if depth == len(current_merge_stack):
 
601
            current_merge_stack.append(info)
 
602
        else:
 
603
            del current_merge_stack[depth + 1:]
 
604
            current_merge_stack[-1] = info
 
605
 
 
606
        if rev_id in modified_text_revisions:
 
607
            # This needs to be logged, along with the extra revisions
 
608
            for idx in xrange(len(current_merge_stack)):
 
609
                node = current_merge_stack[idx]
 
610
                if node is not None:
 
611
                    if include_merges or node[2] == 0:
 
612
                        result.append(node)
 
613
                        current_merge_stack[idx] = None
 
614
    return result
 
615
 
 
616
 
 
617
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
 
618
                       include_merges=True):
 
619
    """Produce an iterator of revisions to show
 
620
    :return: an iterator of (revision_id, revno, merge_depth)
 
621
    (if there is no revno for a revision, None is supplied)
 
622
    """
 
623
    if include_merges is False:
 
624
        revision_ids = mainline_revs[1:]
 
625
        if direction == 'reverse':
 
626
            revision_ids.reverse()
 
627
        for revision_id in revision_ids:
 
628
            yield revision_id, str(rev_nos[revision_id]), 0
 
629
        return
 
630
    graph = branch.repository.get_graph()
 
631
    # This asks for all mainline revisions, which means we only have to spider
 
632
    # sideways, rather than depth history. That said, its still size-of-history
 
633
    # and should be addressed.
 
634
    # mainline_revisions always includes an extra revision at the beginning, so
 
635
    # don't request it.
 
636
    parent_map = dict(((key, value) for key, value in
 
637
        graph.iter_ancestry(mainline_revs[1:]) if value is not None))
 
638
    # filter out ghosts; merge_sort errors on ghosts.
 
639
    rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
 
640
    merge_sorted_revisions = tsort.merge_sort(
 
641
        rev_graph,
 
642
        mainline_revs[-1],
 
643
        mainline_revs,
 
644
        generate_revno=True)
 
645
 
 
646
    if direction == 'forward':
 
647
        # forward means oldest first.
 
648
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
 
649
    elif direction != 'reverse':
 
650
        raise ValueError('invalid direction %r' % direction)
 
651
 
 
652
    for (sequence, rev_id, merge_depth, revno, end_of_merge
 
653
         ) in merge_sorted_revisions:
 
654
        yield rev_id, '.'.join(map(str, revno)), merge_depth
 
655
 
 
656
 
 
657
def reverse_by_depth(merge_sorted_revisions, _depth=0):
 
658
    """Reverse revisions by depth.
 
659
 
 
660
    Revisions with a different depth are sorted as a group with the previous
 
661
    revision of that depth.  There may be no topological justification for this,
 
662
    but it looks much nicer.
 
663
    """
 
664
    # Add a fake revision at start so that we can always attach sub revisions
 
665
    merge_sorted_revisions = [(None, None, _depth)] + merge_sorted_revisions
 
666
    zd_revisions = []
 
667
    for val in merge_sorted_revisions:
 
668
        if val[2] == _depth:
 
669
            # Each revision at the current depth becomes a chunk grouping all
 
670
            # higher depth revisions.
 
671
            zd_revisions.append([val])
 
672
        else:
 
673
            zd_revisions[-1].append(val)
 
674
    for revisions in zd_revisions:
 
675
        if len(revisions) > 1:
 
676
            # We have higher depth revisions, let reverse them locally
 
677
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
 
678
    zd_revisions.reverse()
 
679
    result = []
 
680
    for chunk in zd_revisions:
 
681
        result.extend(chunk)
 
682
    if _depth == 0:
 
683
        # Top level call, get rid of the fake revisions that have been added
 
684
        result = [r for r in result if r[0] is not None and r[1] is not None]
 
685
    return result
 
686
 
 
687
 
 
688
class LogRevision(object):
 
689
    """A revision to be logged (by LogFormatter.log_revision).
 
690
 
 
691
    A simple wrapper for the attributes of a revision to be logged.
 
692
    The attributes may or may not be populated, as determined by the
 
693
    logging options and the log formatter capabilities.
 
694
    """
 
695
 
 
696
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
 
697
                 tags=None):
 
698
        self.rev = rev
 
699
        self.revno = revno
 
700
        self.merge_depth = merge_depth
 
701
        self.delta = delta
 
702
        self.tags = tags
 
703
 
 
704
 
 
705
class LogFormatter(object):
 
706
    """Abstract class to display log messages.
 
707
 
 
708
    At a minimum, a derived class must implement the log_revision method.
 
709
 
 
710
    If the LogFormatter needs to be informed of the beginning or end of
 
711
    a log it should implement the begin_log and/or end_log hook methods.
 
712
 
 
713
    A LogFormatter should define the following supports_XXX flags
 
714
    to indicate which LogRevision attributes it supports:
 
715
 
 
716
    - supports_delta must be True if this log formatter supports delta.
 
717
        Otherwise the delta attribute may not be populated.  The 'delta_format'
 
718
        attribute describes whether the 'short_status' format (1) or the long
 
719
        one (2) sould be used.
 
720
 
 
721
    - supports_merge_revisions must be True if this log formatter supports
 
722
        merge revisions.  If not, and if supports_single_merge_revisions is
 
723
        also not True, then only mainline revisions will be passed to the
 
724
        formatter.
 
725
    - supports_single_merge_revision must be True if this log formatter
 
726
        supports logging only a single merge revision.  This flag is
 
727
        only relevant if supports_merge_revisions is not True.
 
728
    - supports_tags must be True if this log formatter supports tags.
 
729
        Otherwise the tags attribute may not be populated.
 
730
 
 
731
    Plugins can register functions to show custom revision properties using
 
732
    the properties_handler_registry. The registered function
 
733
    must respect the following interface description:
 
734
        def my_show_properties(properties_dict):
 
735
            # code that returns a dict {'name':'value'} of the properties
 
736
            # to be shown
 
737
    """
 
738
 
 
739
    def __init__(self, to_file, show_ids=False, show_timezone='original',
 
740
                 delta_format=None):
 
741
        self.to_file = to_file
 
742
        self.show_ids = show_ids
 
743
        self.show_timezone = show_timezone
 
744
        if delta_format is None:
 
745
            # Ensures backward compatibility
 
746
            delta_format = 2 # long format
 
747
        self.delta_format = delta_format
 
748
 
 
749
# TODO: uncomment this block after show() has been removed.
 
750
# Until then defining log_revision would prevent _show_log calling show()
 
751
# in legacy formatters.
 
752
#    def log_revision(self, revision):
 
753
#        """Log a revision.
 
754
#
 
755
#        :param  revision:   The LogRevision to be logged.
 
756
#        """
 
757
#        raise NotImplementedError('not implemented in abstract base')
 
758
 
 
759
    def short_committer(self, rev):
 
760
        name, address = config.parse_username(rev.committer)
 
761
        if name:
 
762
            return name
 
763
        return address
 
764
 
 
765
    def short_author(self, rev):
 
766
        name, address = config.parse_username(rev.get_apparent_author())
 
767
        if name:
 
768
            return name
 
769
        return address
 
770
 
 
771
    def show_properties(self, revision, indent):
 
772
        """Displays the custom properties returned by each registered handler.
 
773
 
 
774
        If a registered handler raises an error it is propagated.
 
775
        """
 
776
        for key, handler in properties_handler_registry.iteritems():
 
777
            for key, value in handler(revision).items():
 
778
                self.to_file.write(indent + key + ': ' + value + '\n')
 
779
 
 
780
 
 
781
class LongLogFormatter(LogFormatter):
 
782
 
 
783
    supports_merge_revisions = True
 
784
    supports_delta = True
 
785
    supports_tags = True
 
786
 
 
787
    def log_revision(self, revision):
 
788
        """Log a revision, either merged or not."""
 
789
        indent = '    ' * revision.merge_depth
 
790
        to_file = self.to_file
 
791
        to_file.write(indent + '-' * 60 + '\n')
 
792
        if revision.revno is not None:
 
793
            to_file.write(indent + 'revno: %s\n' % (revision.revno,))
 
794
        if revision.tags:
 
795
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
 
796
        if self.show_ids:
 
797
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
 
798
            to_file.write('\n')
 
799
            for parent_id in revision.rev.parent_ids:
 
800
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
 
801
        self.show_properties(revision.rev, indent)
 
802
 
 
803
        author = revision.rev.properties.get('author', None)
 
804
        if author is not None:
 
805
            to_file.write(indent + 'author: %s\n' % (author,))
 
806
        to_file.write(indent + 'committer: %s\n' % (revision.rev.committer,))
 
807
 
 
808
        branch_nick = revision.rev.properties.get('branch-nick', None)
 
809
        if branch_nick is not None:
 
810
            to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
 
811
 
 
812
        date_str = format_date(revision.rev.timestamp,
 
813
                               revision.rev.timezone or 0,
 
814
                               self.show_timezone)
 
815
        to_file.write(indent + 'timestamp: %s\n' % (date_str,))
 
816
 
 
817
        to_file.write(indent + 'message:\n')
 
818
        if not revision.rev.message:
 
819
            to_file.write(indent + '  (no message)\n')
 
820
        else:
 
821
            message = revision.rev.message.rstrip('\r\n')
 
822
            for l in message.split('\n'):
 
823
                to_file.write(indent + '  %s\n' % (l,))
 
824
        if revision.delta is not None:
 
825
            # We don't respect delta_format for compatibility
 
826
            revision.delta.show(to_file, self.show_ids, indent=indent,
 
827
                                short_status=False)
 
828
 
 
829
 
 
830
class ShortLogFormatter(LogFormatter):
 
831
 
 
832
    supports_delta = True
 
833
    supports_single_merge_revision = True
 
834
 
 
835
    def log_revision(self, revision):
 
836
        to_file = self.to_file
 
837
        is_merge = ''
 
838
        if len(revision.rev.parent_ids) > 1:
 
839
            is_merge = ' [merge]'
 
840
        to_file.write("%5s %s\t%s%s\n" % (revision.revno,
 
841
                self.short_author(revision.rev),
 
842
                format_date(revision.rev.timestamp,
 
843
                            revision.rev.timezone or 0,
 
844
                            self.show_timezone, date_fmt="%Y-%m-%d",
 
845
                            show_offset=False),
 
846
                is_merge))
 
847
        if self.show_ids:
 
848
            to_file.write('      revision-id:%s\n'
 
849
                          % (revision.rev.revision_id,))
 
850
        if not revision.rev.message:
 
851
            to_file.write('      (no message)\n')
 
852
        else:
 
853
            message = revision.rev.message.rstrip('\r\n')
 
854
            for l in message.split('\n'):
 
855
                to_file.write('      %s\n' % (l,))
 
856
 
 
857
        if revision.delta is not None:
 
858
            revision.delta.show(to_file, self.show_ids,
 
859
                                short_status=self.delta_format==1)
 
860
        to_file.write('\n')
 
861
 
 
862
 
 
863
class LineLogFormatter(LogFormatter):
 
864
 
 
865
    supports_single_merge_revision = True
 
866
 
 
867
    def __init__(self, *args, **kwargs):
 
868
        super(LineLogFormatter, self).__init__(*args, **kwargs)
 
869
        self._max_chars = terminal_width() - 1
 
870
 
 
871
    def truncate(self, str, max_len):
 
872
        if len(str) <= max_len:
 
873
            return str
 
874
        return str[:max_len-3]+'...'
 
875
 
 
876
    def date_string(self, rev):
 
877
        return format_date(rev.timestamp, rev.timezone or 0,
 
878
                           self.show_timezone, date_fmt="%Y-%m-%d",
 
879
                           show_offset=False)
 
880
 
 
881
    def message(self, rev):
 
882
        if not rev.message:
 
883
            return '(no message)'
 
884
        else:
 
885
            return rev.message
 
886
 
 
887
    def log_revision(self, revision):
 
888
        self.to_file.write(self.log_string(revision.revno, revision.rev,
 
889
                                              self._max_chars))
 
890
        self.to_file.write('\n')
 
891
 
 
892
    def log_string(self, revno, rev, max_chars):
 
893
        """Format log info into one string. Truncate tail of string
 
894
        :param  revno:      revision number or None.
 
895
                            Revision numbers counts from 1.
 
896
        :param  rev:        revision info object
 
897
        :param  max_chars:  maximum length of resulting string
 
898
        :return:            formatted truncated string
 
899
        """
 
900
        out = []
 
901
        if revno:
 
902
            # show revno only when is not None
 
903
            out.append("%s:" % revno)
 
904
        out.append(self.truncate(self.short_author(rev), 20))
 
905
        out.append(self.date_string(rev))
 
906
        out.append(rev.get_summary())
 
907
        return self.truncate(" ".join(out).rstrip('\n'), max_chars)
 
908
 
 
909
 
 
910
def line_log(rev, max_chars):
 
911
    lf = LineLogFormatter(None)
 
912
    return lf.log_string(None, rev, max_chars)
 
913
 
 
914
 
 
915
class LogFormatterRegistry(registry.Registry):
 
916
    """Registry for log formatters"""
 
917
 
 
918
    def make_formatter(self, name, *args, **kwargs):
 
919
        """Construct a formatter from arguments.
 
920
 
 
921
        :param name: Name of the formatter to construct.  'short', 'long' and
 
922
            'line' are built-in.
 
923
        """
 
924
        return self.get(name)(*args, **kwargs)
 
925
 
 
926
    def get_default(self, branch):
 
927
        return self.get(branch.get_config().log_format())
 
928
 
 
929
 
 
930
log_formatter_registry = LogFormatterRegistry()
 
931
 
 
932
 
 
933
log_formatter_registry.register('short', ShortLogFormatter,
 
934
                                'Moderately short log format')
 
935
log_formatter_registry.register('long', LongLogFormatter,
 
936
                                'Detailed log format')
 
937
log_formatter_registry.register('line', LineLogFormatter,
 
938
                                'Log format with one line per revision')
 
939
 
 
940
 
 
941
def register_formatter(name, formatter):
 
942
    log_formatter_registry.register(name, formatter)
 
943
 
 
944
 
 
945
def log_formatter(name, *args, **kwargs):
 
946
    """Construct a formatter from arguments.
 
947
 
 
948
    name -- Name of the formatter to construct; currently 'long', 'short' and
 
949
        'line' are supported.
 
950
    """
 
951
    try:
 
952
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
 
953
    except KeyError:
 
954
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
 
955
 
 
956
 
 
957
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
 
958
    # deprecated; for compatibility
 
959
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
 
960
    lf.show(revno, rev, delta)
 
961
 
 
962
 
 
963
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
 
964
                           log_format='long'):
 
965
    """Show the change in revision history comparing the old revision history to the new one.
 
966
 
 
967
    :param branch: The branch where the revisions exist
 
968
    :param old_rh: The old revision history
 
969
    :param new_rh: The new revision history
 
970
    :param to_file: A file to write the results to. If None, stdout will be used
 
971
    """
 
972
    if to_file is None:
 
973
        to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
 
974
            errors='replace')
 
975
    lf = log_formatter(log_format,
 
976
                       show_ids=False,
 
977
                       to_file=to_file,
 
978
                       show_timezone='original')
 
979
 
 
980
    # This is the first index which is different between
 
981
    # old and new
 
982
    base_idx = None
 
983
    for i in xrange(max(len(new_rh),
 
984
                        len(old_rh))):
 
985
        if (len(new_rh) <= i
 
986
            or len(old_rh) <= i
 
987
            or new_rh[i] != old_rh[i]):
 
988
            base_idx = i
 
989
            break
 
990
 
 
991
    if base_idx is None:
 
992
        to_file.write('Nothing seems to have changed\n')
 
993
        return
 
994
    ## TODO: It might be nice to do something like show_log
 
995
    ##       and show the merged entries. But since this is the
 
996
    ##       removed revisions, it shouldn't be as important
 
997
    if base_idx < len(old_rh):
 
998
        to_file.write('*'*60)
 
999
        to_file.write('\nRemoved Revisions:\n')
 
1000
        for i in range(base_idx, len(old_rh)):
 
1001
            rev = branch.repository.get_revision(old_rh[i])
 
1002
            lr = LogRevision(rev, i+1, 0, None)
 
1003
            lf.log_revision(lr)
 
1004
        to_file.write('*'*60)
 
1005
        to_file.write('\n\n')
 
1006
    if base_idx < len(new_rh):
 
1007
        to_file.write('Added Revisions:\n')
 
1008
        show_log(branch,
 
1009
                 lf,
 
1010
                 None,
 
1011
                 verbose=False,
 
1012
                 direction='forward',
 
1013
                 start_revision=base_idx+1,
 
1014
                 end_revision=len(new_rh),
 
1015
                 search=None)
 
1016
 
 
1017
 
 
1018
def get_history_change(old_revision_id, new_revision_id, repository):
 
1019
    """Calculate the uncommon lefthand history between two revisions.
 
1020
 
 
1021
    :param old_revision_id: The original revision id.
 
1022
    :param new_revision_id: The new revision id.
 
1023
    :param repository: The repository to use for the calculation.
 
1024
 
 
1025
    return old_history, new_history
 
1026
    """
 
1027
    old_history = []
 
1028
    old_revisions = set()
 
1029
    new_history = []
 
1030
    new_revisions = set()
 
1031
    new_iter = repository.iter_reverse_revision_history(new_revision_id)
 
1032
    old_iter = repository.iter_reverse_revision_history(old_revision_id)
 
1033
    stop_revision = None
 
1034
    do_old = True
 
1035
    do_new = True
 
1036
    while do_new or do_old:
 
1037
        if do_new:
 
1038
            try:
 
1039
                new_revision = new_iter.next()
 
1040
            except StopIteration:
 
1041
                do_new = False
 
1042
            else:
 
1043
                new_history.append(new_revision)
 
1044
                new_revisions.add(new_revision)
 
1045
                if new_revision in old_revisions:
 
1046
                    stop_revision = new_revision
 
1047
                    break
 
1048
        if do_old:
 
1049
            try:
 
1050
                old_revision = old_iter.next()
 
1051
            except StopIteration:
 
1052
                do_old = False
 
1053
            else:
 
1054
                old_history.append(old_revision)
 
1055
                old_revisions.add(old_revision)
 
1056
                if old_revision in new_revisions:
 
1057
                    stop_revision = old_revision
 
1058
                    break
 
1059
    new_history.reverse()
 
1060
    old_history.reverse()
 
1061
    if stop_revision is not None:
 
1062
        new_history = new_history[new_history.index(stop_revision) + 1:]
 
1063
        old_history = old_history[old_history.index(stop_revision) + 1:]
 
1064
    return old_history, new_history
 
1065
 
 
1066
 
 
1067
def show_branch_change(branch, output, old_revno, old_revision_id):
 
1068
    """Show the changes made to a branch.
 
1069
 
 
1070
    :param branch: The branch to show changes about.
 
1071
    :param output: A file-like object to write changes to.
 
1072
    :param old_revno: The revno of the old tip.
 
1073
    :param old_revision_id: The revision_id of the old tip.
 
1074
    """
 
1075
    new_revno, new_revision_id = branch.last_revision_info()
 
1076
    old_history, new_history = get_history_change(old_revision_id,
 
1077
                                                  new_revision_id,
 
1078
                                                  branch.repository)
 
1079
    if old_history == [] and new_history == []:
 
1080
        output.write('Nothing seems to have changed\n')
 
1081
        return
 
1082
 
 
1083
    log_format = log_formatter_registry.get_default(branch)
 
1084
    lf = log_format(show_ids=False, to_file=output, show_timezone='original')
 
1085
    if old_history != []:
 
1086
        output.write('*'*60)
 
1087
        output.write('\nRemoved Revisions:\n')
 
1088
        show_flat_log(branch.repository, old_history, old_revno, lf)
 
1089
        output.write('*'*60)
 
1090
        output.write('\n\n')
 
1091
    if new_history != []:
 
1092
        output.write('Added Revisions:\n')
 
1093
        start_revno = new_revno - len(new_history) + 1
 
1094
        show_log(branch, lf, None, verbose=False, direction='forward',
 
1095
                 start_revision=start_revno,)
 
1096
 
 
1097
 
 
1098
def show_flat_log(repository, history, last_revno, lf):
 
1099
    """Show a simple log of the specified history.
 
1100
 
 
1101
    :param repository: The repository to retrieve revisions from.
 
1102
    :param history: A list of revision_ids indicating the lefthand history.
 
1103
    :param last_revno: The revno of the last revision_id in the history.
 
1104
    :param lf: The log formatter to use.
 
1105
    """
 
1106
    start_revno = last_revno - len(history) + 1
 
1107
    revisions = repository.get_revisions(history)
 
1108
    for i, rev in enumerate(revisions):
 
1109
        lr = LogRevision(rev, i + last_revno, 0, None)
 
1110
        lf.log_revision(lr)
 
1111
 
 
1112
 
 
1113
properties_handler_registry = registry.Registry()
 
1114
properties_handler_registry.register_lazy("foreign",
 
1115
                                          "bzrlib.foreign",
 
1116
                                          "show_foreign_properties")
 
1117
 
 
1118
 
 
1119
# adapters which revision ids to log are filtered. When log is called, the
 
1120
# log_rev_iterator is adapted through each of these factory methods.
 
1121
# Plugins are welcome to mutate this list in any way they like - as long
 
1122
# as the overall behaviour is preserved. At this point there is no extensible
 
1123
# mechanism for getting parameters to each factory method, and until there is
 
1124
# this won't be considered a stable api.
 
1125
log_adapters = [
 
1126
    # core log logic
 
1127
    _make_batch_filter,
 
1128
    # read revision objects
 
1129
    _make_revision_objects,
 
1130
    # filter on log messages
 
1131
    _make_search_filter,
 
1132
    # generate deltas for things we will show
 
1133
    _make_delta_filter
 
1134
    ]