1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
19
"""Code to show logs of changes.
 
 
21
Various flavors of log can be produced:
 
 
23
* for one file, or the whole tree, and (not done yet) for
 
 
24
  files in a given directory
 
 
26
* in "verbose" mode with a description of what changed from one
 
 
29
* with file-ids and revision-ids shown
 
 
31
Logs are actually written out through an abstract LogFormatter
 
 
32
interface, which allows for different preferred formats.  Plugins can
 
 
35
Logs can be produced in either forward (oldest->newest) or reverse
 
 
36
(newest->oldest) order.
 
 
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
 
 
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.
 
 
53
from itertools import (
 
 
58
from warnings import (
 
 
62
from bzrlib.lazy_import import lazy_import
 
 
63
lazy_import(globals(), """
 
 
68
    repository as _mod_repository,
 
 
69
    revision as _mod_revision,
 
 
79
from bzrlib.osutils import (
 
 
81
    get_terminal_encoding,
 
 
86
def find_touching_revisions(branch, file_id):
 
 
87
    """Yield a description of revisions which affect the file_id.
 
 
89
    Each returned element is (revno, revision_id, description)
 
 
91
    This is the list of revisions where the file is either added,
 
 
92
    modified, renamed or deleted.
 
 
94
    TODO: Perhaps some way to limit this to only particular revisions,
 
 
95
    or to traverse a non-mainline set of revisions?
 
 
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)
 
 
106
            this_ie = this_path = None
 
 
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?
 
 
111
        if not this_ie and not last_ie:
 
 
112
            # not present in either
 
 
114
        elif this_ie and not last_ie:
 
 
115
            yield revno, revision_id, "added " + this_path
 
 
116
        elif not this_ie and last_ie:
 
 
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
 
 
126
        last_path = this_path
 
 
130
def _enumerate_history(branch):
 
 
133
    for rev_id in branch.revision_history():
 
 
134
        rh.append((revno, rev_id))
 
 
141
             specific_fileid=None,
 
 
148
    """Write out human-readable log of commits to this branch.
 
 
151
        LogFormatter object to show the output.
 
 
154
        If true, list only the commits affecting the specified
 
 
155
        file, rather than all commits.
 
 
158
        If true show added/changed/deleted/renamed files.
 
 
161
        'reverse' (default) is latest to earliest;
 
 
162
        'forward' is earliest to latest.
 
 
165
        If not None, only show revisions >= start_revision
 
 
168
        If not None, only show revisions <= end_revision
 
 
171
        If not None, only show revisions with matching commit messages
 
 
174
        If not None or 0, only show limit revisions
 
 
178
        if getattr(lf, 'begin_log', None):
 
 
181
        _show_log(branch, lf, specific_fileid, verbose, direction,
 
 
182
                  start_revision, end_revision, search, limit)
 
 
184
        if getattr(lf, 'end_log', None):
 
 
190
def _show_log(branch,
 
 
192
             specific_fileid=None,
 
 
199
    """Worker function for show_log - see show_log."""
 
 
200
    if not isinstance(lf, LogFormatter):
 
 
201
        warn("not a LogFormatter instance: %r" % lf)
 
 
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,
 
 
211
                                              generate_merge_revisions,
 
 
212
                                              allow_single_merge_revision)
 
 
214
    generate_tags = getattr(lf, 'supports_tags', False)
 
 
216
        if branch.supports_tags():
 
 
217
            rev_tag_dict = branch.tags.get_reverse_tag_dict()
 
 
219
    generate_delta = verbose and getattr(lf, 'supports_delta', False)
 
 
221
    # now we just print all the revisions
 
 
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))
 
 
232
                if log_count >= limit:
 
 
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)
 
 
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:
 
 
248
    if direction == 'reverse':
 
 
249
        start_rev_id, end_rev_id = end_rev_id, start_rev_id
 
 
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),
 
 
266
    if view_revisions and generate_single_revision:
 
 
267
        view_revisions = view_revisions[0:1]
 
 
269
        view_revisions = _filter_revisions_touching_file_id(branch,
 
 
274
    # rebase merge_depth - unless there are no revisions or 
 
 
275
    # either the first or last revision have merge_depth = 0.
 
 
276
    if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
 
 
277
        min_depth = min([d for r,n,d in view_revisions])
 
 
279
            view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
 
 
280
    return view_revisions
 
 
283
def _linear_view_revisions(branch):
 
 
284
    start_revno, start_revision_id = branch.last_revision_info()
 
 
285
    repo = branch.repository
 
 
286
    revision_ids = repo.iter_reverse_revision_history(start_revision_id)
 
 
287
    for num, revision_id in enumerate(revision_ids):
 
 
288
        yield revision_id, str(start_revno - num), 0
 
 
291
def make_log_rev_iterator(branch, view_revisions, generate_delta, search):
 
 
292
    """Create a revision iterator for log.
 
 
294
    :param branch: The branch being logged.
 
 
295
    :param view_revisions: The revisions being viewed.
 
 
296
    :param generate_delta: Whether to generate a delta for each revision.
 
 
297
    :param search: A user text search string.
 
 
298
    :return: An iterator over iterators of ((rev_id, revno, merge_depth), rev,
 
 
301
    # Convert view_revisions into (view, None, None) groups to fit with
 
 
302
    # the standard interface here.
 
 
303
    if type(view_revisions) == list:
 
 
304
        nones = [None] * len(view_revisions)
 
 
305
        log_rev_iterator = iter([zip(view_revisions, nones, nones)])
 
 
308
            for view in view_revisions:
 
 
309
                yield (view, None, None)
 
 
310
        log_rev_iterator = iter([_convert()])
 
 
312
    log_rev_iterator = make_batch_filter(branch, generate_delta, search,
 
 
314
    # read revision objects
 
 
315
    log_rev_iterator = make_revision_objects(branch, generate_delta, search,
 
 
317
    # filter on log messages
 
 
318
    log_rev_iterator = make_search_filter(branch, generate_delta, search,
 
 
320
    # generate deltas for things we will show
 
 
321
    log_rev_iterator = make_delta_filter(branch, generate_delta, search,
 
 
323
    return log_rev_iterator
 
 
326
def make_search_filter(branch, generate_delta, search, log_rev_iterator):
 
 
327
    """Create a filtered iterator of log_rev_iterator matching on a regex.
 
 
329
    :param branch: The branch being logged.
 
 
330
    :param generate_delta: Whether to generate a delta for each revision.
 
 
331
    :param search: A user text search string.
 
 
332
    :param log_rev_iterator: An input iterator containing all revisions that
 
 
333
        could be displayed, in lists.
 
 
334
    :return: An iterator over iterators of ((rev_id, revno, merge_depth), rev,
 
 
338
        return log_rev_iterator
 
 
339
    # Compile the search now to get early errors.
 
 
340
    searchRE = re.compile(search, re.IGNORECASE)
 
 
341
    return _filter_message_re(searchRE, log_rev_iterator)
 
 
344
def _filter_message_re(searchRE, log_rev_iterator):
 
 
345
    for revs in log_rev_iterator:
 
 
347
        for (rev_id, revno, merge_depth), rev, delta in revs:
 
 
348
            if searchRE.search(rev.message):
 
 
349
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
 
 
353
def make_delta_filter(branch, generate_delta, search, log_rev_iterator):
 
 
354
    """Add revision deltas to a log iterator if needed.
 
 
356
    :param branch: The branch being logged.
 
 
357
    :param generate_delta: Whether to generate a delta for each revision.
 
 
358
    :param search: A user text search string.
 
 
359
    :param log_rev_iterator: An input iterator containing all revisions that
 
 
360
        could be displayed, in lists.
 
 
361
    :return: An iterator over iterators of ((rev_id, revno, merge_depth), rev,
 
 
364
    if not generate_delta:
 
 
365
        return log_rev_iterator
 
 
366
    return _generate_deltas(branch.repository, log_rev_iterator)
 
 
369
def _generate_deltas(repository, log_rev_iterator):
 
 
370
    for revs in log_rev_iterator:
 
 
371
        revisions = [rev[1] for rev in revs]
 
 
372
        deltas = repository.get_deltas_for_revisions(revisions)
 
 
373
        revs = [(rev[0], rev[1], delta) for rev, delta in izip(revs, deltas)]
 
 
377
def make_revision_objects(branch, generate_delta, search, log_rev_iterator):
 
 
378
    """Extract revision objects from the repository
 
 
380
    :param branch: The branch being logged.
 
 
381
    :param generate_delta: Whether to generate a delta for each revision.
 
 
382
    :param search: A user text search string.
 
 
383
    :param log_rev_iterator: An input iterator containing all revisions that
 
 
384
        could be displayed, in lists.
 
 
385
    :return: An iterator over iterators of ((rev_id, revno, merge_depth), rev,
 
 
388
    repository = branch.repository
 
 
389
    for revs in log_rev_iterator:
 
 
390
        # r = revision_id, n = revno, d = merge depth
 
 
391
        revision_ids = [view[0] for view, _, _ in revs]
 
 
392
        revisions = repository.get_revisions(revision_ids)
 
 
393
        revs = [(rev[0], revision, rev[2]) for rev, revision in
 
 
394
            izip(revs, revisions)]
 
 
398
def make_batch_filter(branch, generate_delta, search, log_rev_iterator):
 
 
399
    """Group up a single large batch into smaller ones.
 
 
401
    :param branch: The branch being logged.
 
 
402
    :param generate_delta: Whether to generate a delta for each revision.
 
 
403
    :param search: A user text search string.
 
 
404
    :param log_rev_iterator: An input iterator containing all revisions that
 
 
405
        could be displayed, in lists.
 
 
406
    :return: An iterator over ((rev_id, revno, merge_depth), rev, delta).
 
 
408
    repository = branch.repository
 
 
410
    for batch in log_rev_iterator:
 
 
413
            step = [detail for _, detail in zip(range(num), batch)]
 
 
417
            num = min(int(num * 1.5), 200)
 
 
420
def _get_mainline_revs(branch, start_revision, end_revision):
 
 
421
    """Get the mainline revisions from the branch.
 
 
423
    Generates the list of mainline revisions for the branch.
 
 
425
    :param  branch: The branch containing the revisions. 
 
 
427
    :param  start_revision: The first revision to be logged.
 
 
428
            For backwards compatibility this may be a mainline integer revno,
 
 
429
            but for merge revision support a RevisionInfo is expected.
 
 
431
    :param  end_revision: The last revision to be logged.
 
 
432
            For backwards compatibility this may be a mainline integer revno,
 
 
433
            but for merge revision support a RevisionInfo is expected.
 
 
435
    :return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
 
 
437
    branch_revno, branch_last_revision = branch.last_revision_info()
 
 
438
    if branch_revno == 0:
 
 
439
        return None, None, None, None
 
 
441
    # For mainline generation, map start_revision and end_revision to 
 
 
442
    # mainline revnos. If the revision is not on the mainline choose the 
 
 
443
    # appropriate extreme of the mainline instead - the extra will be 
 
 
445
    # Also map the revisions to rev_ids, to be used in the later filtering
 
 
448
    if start_revision is None:
 
 
451
        if isinstance(start_revision, revisionspec.RevisionInfo):
 
 
452
            start_rev_id = start_revision.rev_id
 
 
453
            start_revno = start_revision.revno or 1
 
 
455
            branch.check_real_revno(start_revision)
 
 
456
            start_revno = start_revision
 
 
459
    if end_revision is None:
 
 
460
        end_revno = branch_revno
 
 
462
        if isinstance(end_revision, revisionspec.RevisionInfo):
 
 
463
            end_rev_id = end_revision.rev_id
 
 
464
            end_revno = end_revision.revno or branch_revno
 
 
466
            branch.check_real_revno(end_revision)
 
 
467
            end_revno = end_revision
 
 
469
    if ((start_rev_id == _mod_revision.NULL_REVISION)
 
 
470
        or (end_rev_id == _mod_revision.NULL_REVISION)):
 
 
471
        raise errors.BzrCommandError('Logging revision 0 is invalid.')
 
 
472
    if start_revno > end_revno:
 
 
473
        raise errors.BzrCommandError("Start revision must be older than "
 
 
476
    if end_revno < start_revno:
 
 
477
        return None, None, None, None
 
 
478
    cur_revno = branch_revno
 
 
481
    for revision_id in branch.repository.iter_reverse_revision_history(
 
 
482
                        branch_last_revision):
 
 
483
        if cur_revno < start_revno:
 
 
484
            # We have gone far enough, but we always add 1 more revision
 
 
485
            rev_nos[revision_id] = cur_revno
 
 
486
            mainline_revs.append(revision_id)
 
 
488
        if cur_revno <= end_revno:
 
 
489
            rev_nos[revision_id] = cur_revno
 
 
490
            mainline_revs.append(revision_id)
 
 
493
        # We walked off the edge of all revisions, so we add a 'None' marker
 
 
494
        mainline_revs.append(None)
 
 
496
    mainline_revs.reverse()
 
 
498
    # override the mainline to look like the revision history.
 
 
499
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
 
 
502
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
 
 
503
    """Filter view_revisions based on revision ranges.
 
 
505
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth) 
 
 
506
            tuples to be filtered.
 
 
508
    :param start_rev_id: If not NONE specifies the first revision to be logged.
 
 
509
            If NONE then all revisions up to the end_rev_id are logged.
 
 
511
    :param end_rev_id: If not NONE specifies the last revision to be logged.
 
 
512
            If NONE then all revisions up to the end of the log are logged.
 
 
514
    :return: The filtered view_revisions.
 
 
516
    if start_rev_id or end_rev_id: 
 
 
517
        revision_ids = [r for r, n, d in view_revisions]
 
 
519
            start_index = revision_ids.index(start_rev_id)
 
 
522
        if start_rev_id == end_rev_id:
 
 
523
            end_index = start_index
 
 
526
                end_index = revision_ids.index(end_rev_id)
 
 
528
                end_index = len(view_revisions) - 1
 
 
529
        # To include the revisions merged into the last revision, 
 
 
530
        # extend end_rev_id down to, but not including, the next rev
 
 
531
        # with the same or lesser merge_depth
 
 
532
        end_merge_depth = view_revisions[end_index][2]
 
 
534
            for index in xrange(end_index+1, len(view_revisions)+1):
 
 
535
                if view_revisions[index][2] <= end_merge_depth:
 
 
536
                    end_index = index - 1
 
 
539
            # if the search falls off the end then log to the end as well
 
 
540
            end_index = len(view_revisions) - 1
 
 
541
        view_revisions = view_revisions[start_index:end_index+1]
 
 
542
    return view_revisions
 
 
545
def _filter_revisions_touching_file_id(branch, file_id, mainline_revisions,
 
 
547
    """Return the list of revision ids which touch a given file id.
 
 
549
    The function filters view_revisions and returns a subset.
 
 
550
    This includes the revisions which directly change the file id,
 
 
551
    and the revisions which merge these changes. So if the
 
 
559
    And 'C' changes a file, then both C and D will be returned.
 
 
561
    This will also can be restricted based on a subset of the mainline.
 
 
563
    :return: A list of (revision_id, dotted_revno, merge_depth) tuples.
 
 
565
    # find all the revisions that change the specific file
 
 
566
    # build the ancestry of each revision in the graph
 
 
567
    # - only listing the ancestors that change the specific file.
 
 
568
    graph = branch.repository.get_graph()
 
 
569
    # This asks for all mainline revisions, which means we only have to spider
 
 
570
    # sideways, rather than depth history. That said, its still size-of-history
 
 
571
    # and should be addressed.
 
 
572
    # mainline_revisions always includes an extra revision at the beginning, so
 
 
574
    parent_map = dict(((key, value) for key, value in
 
 
575
        graph.iter_ancestry(mainline_revisions[1:]) if value is not None))
 
 
576
    sorted_rev_list = tsort.topo_sort(parent_map.items())
 
 
577
    text_keys = [(file_id, rev_id) for rev_id in sorted_rev_list]
 
 
578
    modified_text_versions = branch.repository.texts.get_parent_map(text_keys)
 
 
580
    for rev in sorted_rev_list:
 
 
581
        text_key = (file_id, rev)
 
 
582
        parents = parent_map[rev]
 
 
583
        if text_key not in modified_text_versions and len(parents) == 1:
 
 
584
            # We will not be adding anything new, so just use a reference to
 
 
585
            # the parent ancestry.
 
 
586
            rev_ancestry = ancestry[parents[0]]
 
 
589
            if text_key in modified_text_versions:
 
 
590
                rev_ancestry.add(rev)
 
 
591
            for parent in parents:
 
 
592
                if parent not in ancestry:
 
 
593
                    # parent is a Ghost, which won't be present in
 
 
594
                    # sorted_rev_list, but we may access it later, so create an
 
 
596
                    ancestry[parent] = set()
 
 
597
                rev_ancestry = rev_ancestry.union(ancestry[parent])
 
 
598
        ancestry[rev] = rev_ancestry
 
 
600
    def is_merging_rev(r):
 
 
601
        parents = parent_map[r]
 
 
603
            leftparent = parents[0]
 
 
604
            for rightparent in parents[1:]:
 
 
605
                if not ancestry[leftparent].issuperset(
 
 
606
                        ancestry[rightparent]):
 
 
610
    # filter from the view the revisions that did not change or merge 
 
 
612
    return [(r, n, d) for r, n, d in view_revs_iter
 
 
613
            if (file_id, r) in modified_text_versions or is_merging_rev(r)]
 
 
616
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
 
 
617
                       include_merges=True):
 
 
618
    """Produce an iterator of revisions to show
 
 
619
    :return: an iterator of (revision_id, revno, merge_depth)
 
 
620
    (if there is no revno for a revision, None is supplied)
 
 
622
    if include_merges is False:
 
 
623
        revision_ids = mainline_revs[1:]
 
 
624
        if direction == 'reverse':
 
 
625
            revision_ids.reverse()
 
 
626
        for revision_id in revision_ids:
 
 
627
            yield revision_id, str(rev_nos[revision_id]), 0
 
 
629
    graph = branch.repository.get_graph()
 
 
630
    # This asks for all mainline revisions, which means we only have to spider
 
 
631
    # sideways, rather than depth history. That said, its still size-of-history
 
 
632
    # and should be addressed.
 
 
633
    # mainline_revisions always includes an extra revision at the beginning, so
 
 
635
    parent_map = dict(((key, value) for key, value in
 
 
636
        graph.iter_ancestry(mainline_revs[1:]) if value is not None))
 
 
637
    # filter out ghosts; merge_sort errors on ghosts.
 
 
638
    rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
 
 
639
    merge_sorted_revisions = tsort.merge_sort(
 
 
645
    if direction == 'forward':
 
 
646
        # forward means oldest first.
 
 
647
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
 
 
648
    elif direction != 'reverse':
 
 
649
        raise ValueError('invalid direction %r' % direction)
 
 
651
    for sequence, rev_id, merge_depth, revno, end_of_merge in merge_sorted_revisions:
 
 
652
        yield rev_id, '.'.join(map(str, revno)), merge_depth
 
 
655
def reverse_by_depth(merge_sorted_revisions, _depth=0):
 
 
656
    """Reverse revisions by depth.
 
 
658
    Revisions with a different depth are sorted as a group with the previous
 
 
659
    revision of that depth.  There may be no topological justification for this,
 
 
660
    but it looks much nicer.
 
 
663
    for val in merge_sorted_revisions:
 
 
665
            zd_revisions.append([val])
 
 
667
            zd_revisions[-1].append(val)
 
 
668
    for revisions in zd_revisions:
 
 
669
        if len(revisions) > 1:
 
 
670
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
 
 
671
    zd_revisions.reverse()
 
 
673
    for chunk in zd_revisions:
 
 
678
class LogRevision(object):
 
 
679
    """A revision to be logged (by LogFormatter.log_revision).
 
 
681
    A simple wrapper for the attributes of a revision to be logged.
 
 
682
    The attributes may or may not be populated, as determined by the 
 
 
683
    logging options and the log formatter capabilities.
 
 
686
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
 
 
690
        self.merge_depth = merge_depth
 
 
695
class LogFormatter(object):
 
 
696
    """Abstract class to display log messages.
 
 
698
    At a minimum, a derived class must implement the log_revision method.
 
 
700
    If the LogFormatter needs to be informed of the beginning or end of
 
 
701
    a log it should implement the begin_log and/or end_log hook methods.
 
 
703
    A LogFormatter should define the following supports_XXX flags 
 
 
704
    to indicate which LogRevision attributes it supports:
 
 
706
    - supports_delta must be True if this log formatter supports delta.
 
 
707
        Otherwise the delta attribute may not be populated.
 
 
708
    - supports_merge_revisions must be True if this log formatter supports 
 
 
709
        merge revisions.  If not, and if supports_single_merge_revisions is
 
 
710
        also not True, then only mainline revisions will be passed to the 
 
 
712
    - supports_single_merge_revision must be True if this log formatter
 
 
713
        supports logging only a single merge revision.  This flag is
 
 
714
        only relevant if supports_merge_revisions is not True.
 
 
715
    - supports_tags must be True if this log formatter supports tags.
 
 
716
        Otherwise the tags attribute may not be populated.
 
 
718
    Plugins can register functions to show custom revision properties using
 
 
719
    the properties_handler_registry. The registered function
 
 
720
    must respect the following interface description:
 
 
721
        def my_show_properties(properties_dict):
 
 
722
            # code that returns a dict {'name':'value'} of the properties 
 
 
726
    def __init__(self, to_file, show_ids=False, show_timezone='original'):
 
 
727
        self.to_file = to_file
 
 
728
        self.show_ids = show_ids
 
 
729
        self.show_timezone = show_timezone
 
 
731
# TODO: uncomment this block after show() has been removed.
 
 
732
# Until then defining log_revision would prevent _show_log calling show() 
 
 
733
# in legacy formatters.
 
 
734
#    def log_revision(self, revision):
 
 
737
#        :param  revision:   The LogRevision to be logged.
 
 
739
#        raise NotImplementedError('not implemented in abstract base')
 
 
741
    def short_committer(self, rev):
 
 
742
        name, address = config.parse_username(rev.committer)
 
 
747
    def short_author(self, rev):
 
 
748
        name, address = config.parse_username(rev.get_apparent_author())
 
 
753
    def show_properties(self, revision, indent):
 
 
754
        """Displays the custom properties returned by each registered handler.
 
 
756
        If a registered handler raises an error it is propagated.
 
 
758
        for key, handler in properties_handler_registry.iteritems():
 
 
759
            for key, value in handler(revision).items():
 
 
760
                self.to_file.write(indent + key + ': ' + value + '\n')
 
 
763
class LongLogFormatter(LogFormatter):
 
 
765
    supports_merge_revisions = True
 
 
766
    supports_delta = True
 
 
769
    def log_revision(self, revision):
 
 
770
        """Log a revision, either merged or not."""
 
 
771
        indent = '    ' * revision.merge_depth
 
 
772
        to_file = self.to_file
 
 
773
        to_file.write(indent + '-' * 60 + '\n')
 
 
774
        if revision.revno is not None:
 
 
775
            to_file.write(indent + 'revno: %s\n' % (revision.revno,))
 
 
777
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
 
 
779
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
 
 
781
            for parent_id in revision.rev.parent_ids:
 
 
782
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
 
 
783
        self.show_properties(revision.rev, indent)
 
 
785
        author = revision.rev.properties.get('author', None)
 
 
786
        if author is not None:
 
 
787
            to_file.write(indent + 'author: %s\n' % (author,))
 
 
788
        to_file.write(indent + 'committer: %s\n' % (revision.rev.committer,))
 
 
790
        branch_nick = revision.rev.properties.get('branch-nick', None)
 
 
791
        if branch_nick is not None:
 
 
792
            to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
 
 
794
        date_str = format_date(revision.rev.timestamp,
 
 
795
                               revision.rev.timezone or 0,
 
 
797
        to_file.write(indent + 'timestamp: %s\n' % (date_str,))
 
 
799
        to_file.write(indent + 'message:\n')
 
 
800
        if not revision.rev.message:
 
 
801
            to_file.write(indent + '  (no message)\n')
 
 
803
            message = revision.rev.message.rstrip('\r\n')
 
 
804
            for l in message.split('\n'):
 
 
805
                to_file.write(indent + '  %s\n' % (l,))
 
 
806
        if revision.delta is not None:
 
 
807
            revision.delta.show(to_file, self.show_ids, indent=indent)
 
 
810
class ShortLogFormatter(LogFormatter):
 
 
812
    supports_delta = True
 
 
813
    supports_single_merge_revision = True
 
 
815
    def log_revision(self, revision):
 
 
816
        to_file = self.to_file
 
 
818
        if len(revision.rev.parent_ids) > 1:
 
 
819
            is_merge = ' [merge]'
 
 
820
        to_file.write("%5s %s\t%s%s\n" % (revision.revno,
 
 
821
                self.short_author(revision.rev),
 
 
822
                format_date(revision.rev.timestamp,
 
 
823
                            revision.rev.timezone or 0,
 
 
824
                            self.show_timezone, date_fmt="%Y-%m-%d",
 
 
828
            to_file.write('      revision-id:%s\n' % (revision.rev.revision_id,))
 
 
829
        if not revision.rev.message:
 
 
830
            to_file.write('      (no message)\n')
 
 
832
            message = revision.rev.message.rstrip('\r\n')
 
 
833
            for l in message.split('\n'):
 
 
834
                to_file.write('      %s\n' % (l,))
 
 
836
        # TODO: Why not show the modified files in a shorter form as
 
 
837
        # well? rewrap them single lines of appropriate length
 
 
838
        if revision.delta is not None:
 
 
839
            revision.delta.show(to_file, self.show_ids)
 
 
843
class LineLogFormatter(LogFormatter):
 
 
845
    supports_single_merge_revision = True
 
 
847
    def __init__(self, *args, **kwargs):
 
 
848
        super(LineLogFormatter, self).__init__(*args, **kwargs)
 
 
849
        self._max_chars = terminal_width() - 1
 
 
851
    def truncate(self, str, max_len):
 
 
852
        if len(str) <= max_len:
 
 
854
        return str[:max_len-3]+'...'
 
 
856
    def date_string(self, rev):
 
 
857
        return format_date(rev.timestamp, rev.timezone or 0, 
 
 
858
                           self.show_timezone, date_fmt="%Y-%m-%d",
 
 
861
    def message(self, rev):
 
 
863
            return '(no message)'
 
 
867
    def log_revision(self, revision):
 
 
868
        self.to_file.write(self.log_string(revision.revno, revision.rev,
 
 
870
        self.to_file.write('\n')
 
 
872
    def log_string(self, revno, rev, max_chars):
 
 
873
        """Format log info into one string. Truncate tail of string
 
 
874
        :param  revno:      revision number (int) or None.
 
 
875
                            Revision numbers counts from 1.
 
 
876
        :param  rev:        revision info object
 
 
877
        :param  max_chars:  maximum length of resulting string
 
 
878
        :return:            formatted truncated string
 
 
882
            # show revno only when is not None
 
 
883
            out.append("%s:" % revno)
 
 
884
        out.append(self.truncate(self.short_author(rev), 20))
 
 
885
        out.append(self.date_string(rev))
 
 
886
        out.append(rev.get_summary())
 
 
887
        return self.truncate(" ".join(out).rstrip('\n'), max_chars)
 
 
890
def line_log(rev, max_chars):
 
 
891
    lf = LineLogFormatter(None)
 
 
892
    return lf.log_string(None, rev, max_chars)
 
 
895
class LogFormatterRegistry(registry.Registry):
 
 
896
    """Registry for log formatters"""
 
 
898
    def make_formatter(self, name, *args, **kwargs):
 
 
899
        """Construct a formatter from arguments.
 
 
901
        :param name: Name of the formatter to construct.  'short', 'long' and
 
 
904
        return self.get(name)(*args, **kwargs)
 
 
906
    def get_default(self, branch):
 
 
907
        return self.get(branch.get_config().log_format())
 
 
910
log_formatter_registry = LogFormatterRegistry()
 
 
913
log_formatter_registry.register('short', ShortLogFormatter,
 
 
914
                                'Moderately short log format')
 
 
915
log_formatter_registry.register('long', LongLogFormatter,
 
 
916
                                'Detailed log format')
 
 
917
log_formatter_registry.register('line', LineLogFormatter,
 
 
918
                                'Log format with one line per revision')
 
 
921
def register_formatter(name, formatter):
 
 
922
    log_formatter_registry.register(name, formatter)
 
 
925
def log_formatter(name, *args, **kwargs):
 
 
926
    """Construct a formatter from arguments.
 
 
928
    name -- Name of the formatter to construct; currently 'long', 'short' and
 
 
929
        'line' are supported.
 
 
932
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
 
 
934
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
 
 
937
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
 
 
938
    # deprecated; for compatibility
 
 
939
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
 
 
940
    lf.show(revno, rev, delta)
 
 
943
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
 
 
945
    """Show the change in revision history comparing the old revision history to the new one.
 
 
947
    :param branch: The branch where the revisions exist
 
 
948
    :param old_rh: The old revision history
 
 
949
    :param new_rh: The new revision history
 
 
950
    :param to_file: A file to write the results to. If None, stdout will be used
 
 
953
        to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
 
 
955
    lf = log_formatter(log_format,
 
 
958
                       show_timezone='original')
 
 
960
    # This is the first index which is different between
 
 
963
    for i in xrange(max(len(new_rh),
 
 
967
            or new_rh[i] != old_rh[i]):
 
 
972
        to_file.write('Nothing seems to have changed\n')
 
 
974
    ## TODO: It might be nice to do something like show_log
 
 
975
    ##       and show the merged entries. But since this is the
 
 
976
    ##       removed revisions, it shouldn't be as important
 
 
977
    if base_idx < len(old_rh):
 
 
978
        to_file.write('*'*60)
 
 
979
        to_file.write('\nRemoved Revisions:\n')
 
 
980
        for i in range(base_idx, len(old_rh)):
 
 
981
            rev = branch.repository.get_revision(old_rh[i])
 
 
982
            lr = LogRevision(rev, i+1, 0, None)
 
 
984
        to_file.write('*'*60)
 
 
985
        to_file.write('\n\n')
 
 
986
    if base_idx < len(new_rh):
 
 
987
        to_file.write('Added Revisions:\n')
 
 
993
                 start_revision=base_idx+1,
 
 
994
                 end_revision=len(new_rh),
 
 
998
properties_handler_registry = registry.Registry()