/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: Martin Pool
  • Date: 2009-01-23 22:39:31 UTC
  • mto: This revision was merged to the branch mainline in revision 3959.
  • Revision ID: mbp@sourcefrog.net-20090123223931-kb1la553lxibnbpd
Rephrase api docs

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