/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

  • Committer: John Arbash Meinel
  • Date: 2008-09-21 14:48:37 UTC
  • mto: This revision was merged to the branch mainline in revision 3735.
  • Revision ID: john@arbash-meinel.com-20080921144837-wi61tf7gr4jfwl5d
Fix GraphIndex to properly generate _nodes_by_keys on demand.

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