~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/log.py

  • Committer: John Ferlito
  • Date: 2009-09-02 04:31:45 UTC
  • mto: (4665.7.1 serve-init)
  • mto: This revision was merged to the branch mainline in revision 4913.
  • Revision ID: johnf@inodes.org-20090902043145-gxdsfw03ilcwbyn5
Add a debian init script for bzr --serve

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
73
73
    repository as _mod_repository,
74
74
    revision as _mod_revision,
75
75
    revisionspec,
 
76
    trace,
76
77
    tsort,
77
78
    )
78
79
""")
82
83
    )
83
84
from bzrlib.osutils import (
84
85
    format_date,
85
 
    format_date_with_offset_in_original_timezone,
86
 
    get_diff_header_encoding,
87
86
    get_terminal_encoding,
 
87
    re_compile_checked,
88
88
    terminal_width,
89
89
    )
90
 
from bzrlib.symbol_versioning import (
91
 
    deprecated_function,
92
 
    deprecated_in,
93
 
    )
94
90
 
95
91
 
96
92
def find_touching_revisions(branch, file_id):
108
104
    last_path = None
109
105
    revno = 1
110
106
    for revision_id in branch.revision_history():
111
 
        this_inv = branch.repository.get_inventory(revision_id)
 
107
        this_inv = branch.repository.get_revision_inventory(revision_id)
112
108
        if file_id in this_inv:
113
109
            this_ie = this_inv[file_id]
114
110
            this_path = this_inv.id2path(file_id)
219
215
    'direction': 'reverse',
220
216
    'levels': 1,
221
217
    'generate_tags': True,
222
 
    'exclude_common_ancestry': False,
223
218
    '_match_using_deltas': True,
224
219
    }
225
220
 
226
221
 
227
222
def make_log_request_dict(direction='reverse', specific_fileids=None,
228
 
                          start_revision=None, end_revision=None, limit=None,
229
 
                          message_search=None, levels=1, generate_tags=True,
230
 
                          delta_type=None,
231
 
                          diff_type=None, _match_using_deltas=True,
232
 
                          exclude_common_ancestry=False,
233
 
                          ):
 
223
    start_revision=None, end_revision=None, limit=None,
 
224
    message_search=None, levels=1, generate_tags=True, delta_type=None,
 
225
    diff_type=None, _match_using_deltas=True):
234
226
    """Convenience function for making a logging request dictionary.
235
227
 
236
228
    Using this function may make code slightly safer by ensuring
274
266
      algorithm used for matching specific_fileids. This parameter
275
267
      may be removed in the future so bzrlib client code should NOT
276
268
      use it.
277
 
 
278
 
    :param exclude_common_ancestry: Whether -rX..Y should be interpreted as a
279
 
      range operator or as a graph difference.
280
269
    """
281
270
    return {
282
271
        'direction': direction,
289
278
        'generate_tags': generate_tags,
290
279
        'delta_type': delta_type,
291
280
        'diff_type': diff_type,
292
 
        'exclude_common_ancestry': exclude_common_ancestry,
293
281
        # Add 'private' attributes for features that may be deprecated
294
282
        '_match_using_deltas': _match_using_deltas,
295
283
    }
297
285
 
298
286
def _apply_log_request_defaults(rqst):
299
287
    """Apply default values to a request dictionary."""
300
 
    result = _DEFAULT_REQUEST_PARAMS.copy()
 
288
    result = _DEFAULT_REQUEST_PARAMS
301
289
    if rqst:
302
290
        result.update(rqst)
303
291
    return result
315
303
 
316
304
 
317
305
class Logger(object):
318
 
    """An object that generates, formats and displays a log."""
 
306
    """An object the generates, formats and displays a log."""
319
307
 
320
308
    def __init__(self, branch, rqst):
321
309
        """Create a Logger.
396
384
        :return: An iterator yielding LogRevision objects.
397
385
        """
398
386
        rqst = self.rqst
399
 
        levels = rqst.get('levels')
400
 
        limit = rqst.get('limit')
401
 
        diff_type = rqst.get('diff_type')
402
387
        log_count = 0
403
388
        revision_iterator = self._create_log_revision_iterator()
404
389
        for revs in revision_iterator:
405
390
            for (rev_id, revno, merge_depth), rev, delta in revs:
406
391
                # 0 levels means show everything; merge_depth counts from 0
 
392
                levels = rqst.get('levels')
407
393
                if levels != 0 and merge_depth >= levels:
408
394
                    continue
409
 
                if diff_type is None:
410
 
                    diff = None
411
 
                else:
412
 
                    diff = self._format_diff(rev, rev_id, diff_type)
 
395
                diff = self._format_diff(rev, rev_id)
413
396
                yield LogRevision(rev, revno, merge_depth, delta,
414
397
                    self.rev_tag_dict.get(rev_id), diff)
 
398
                limit = rqst.get('limit')
415
399
                if limit:
416
400
                    log_count += 1
417
401
                    if log_count >= limit:
418
402
                        return
419
403
 
420
 
    def _format_diff(self, rev, rev_id, diff_type):
 
404
    def _format_diff(self, rev, rev_id):
 
405
        diff_type = self.rqst.get('diff_type')
 
406
        if diff_type is None:
 
407
            return None
421
408
        repo = self.branch.repository
422
409
        if len(rev.parent_ids) == 0:
423
410
            ancestor_id = _mod_revision.NULL_REVISION
431
418
        else:
432
419
            specific_files = None
433
420
        s = StringIO()
434
 
        path_encoding = get_diff_header_encoding()
435
421
        diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
436
 
            new_label='', path_encoding=path_encoding)
 
422
            new_label='')
437
423
        return s.getvalue()
438
424
 
439
425
    def _create_log_revision_iterator(self):
463
449
        generate_merge_revisions = rqst.get('levels') != 1
464
450
        delayed_graph_generation = not rqst.get('specific_fileids') and (
465
451
                rqst.get('limit') or self.start_rev_id or self.end_rev_id)
466
 
        view_revisions = _calc_view_revisions(
467
 
            self.branch, self.start_rev_id, self.end_rev_id,
468
 
            rqst.get('direction'),
469
 
            generate_merge_revisions=generate_merge_revisions,
470
 
            delayed_graph_generation=delayed_graph_generation,
471
 
            exclude_common_ancestry=rqst.get('exclude_common_ancestry'))
 
452
        view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
 
453
            self.end_rev_id, rqst.get('direction'), generate_merge_revisions,
 
454
            delayed_graph_generation=delayed_graph_generation)
472
455
 
473
456
        # Apply the other filters
474
457
        return make_log_rev_iterator(self.branch, view_revisions,
481
464
        # Note that we always generate the merge revisions because
482
465
        # filter_revisions_touching_file_id() requires them ...
483
466
        rqst = self.rqst
484
 
        view_revisions = _calc_view_revisions(
485
 
            self.branch, self.start_rev_id, self.end_rev_id,
486
 
            rqst.get('direction'), generate_merge_revisions=True,
487
 
            exclude_common_ancestry=rqst.get('exclude_common_ancestry'))
 
467
        view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
 
468
            self.end_rev_id, rqst.get('direction'), True)
488
469
        if not isinstance(view_revisions, list):
489
470
            view_revisions = list(view_revisions)
490
471
        view_revisions = _filter_revisions_touching_file_id(self.branch,
495
476
 
496
477
 
497
478
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
498
 
                         generate_merge_revisions,
499
 
                         delayed_graph_generation=False,
500
 
                         exclude_common_ancestry=False,
501
 
                         ):
 
479
    generate_merge_revisions, delayed_graph_generation=False):
502
480
    """Calculate the revisions to view.
503
481
 
504
482
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
505
483
             a list of the same tuples.
506
484
    """
507
 
    if (exclude_common_ancestry and start_rev_id == end_rev_id):
508
 
        raise errors.BzrCommandError(
509
 
            '--exclude-common-ancestry requires two different revisions')
510
 
    if direction not in ('reverse', 'forward'):
511
 
        raise ValueError('invalid direction %r' % direction)
512
485
    br_revno, br_rev_id = branch.last_revision_info()
513
486
    if br_revno == 0:
514
487
        return []
515
488
 
516
 
    if (end_rev_id and start_rev_id == end_rev_id
517
 
        and (not generate_merge_revisions
518
 
             or not _has_merges(branch, end_rev_id))):
519
 
        # If a single revision is requested, check we can handle it
520
 
        iter_revs = _generate_one_revision(branch, end_rev_id, br_rev_id,
521
 
                                           br_revno)
522
 
    elif not generate_merge_revisions:
523
 
        # If we only want to see linear revisions, we can iterate ...
524
 
        iter_revs = _generate_flat_revisions(branch, start_rev_id, end_rev_id,
525
 
                                             direction, exclude_common_ancestry)
526
 
        if direction == 'forward':
527
 
            iter_revs = reversed(iter_revs)
 
489
    # If a single revision is requested, check we can handle it
 
490
    generate_single_revision = (end_rev_id and start_rev_id == end_rev_id and
 
491
        (not generate_merge_revisions or not _has_merges(branch, end_rev_id)))
 
492
    if generate_single_revision:
 
493
        return _generate_one_revision(branch, end_rev_id, br_rev_id, br_revno)
 
494
 
 
495
    # If we only want to see linear revisions, we can iterate ...
 
496
    if not generate_merge_revisions:
 
497
        return _generate_flat_revisions(branch, start_rev_id, end_rev_id,
 
498
            direction)
528
499
    else:
529
 
        iter_revs = _generate_all_revisions(branch, start_rev_id, end_rev_id,
530
 
                                            direction, delayed_graph_generation,
531
 
                                            exclude_common_ancestry)
532
 
        if direction == 'forward':
533
 
            iter_revs = _rebase_merge_depth(reverse_by_depth(list(iter_revs)))
534
 
    return iter_revs
 
500
        return _generate_all_revisions(branch, start_rev_id, end_rev_id,
 
501
            direction, delayed_graph_generation)
535
502
 
536
503
 
537
504
def _generate_one_revision(branch, rev_id, br_rev_id, br_revno):
539
506
        # It's the tip
540
507
        return [(br_rev_id, br_revno, 0)]
541
508
    else:
542
 
        revno_str = _compute_revno_str(branch, rev_id)
 
509
        revno = branch.revision_id_to_dotted_revno(rev_id)
 
510
        revno_str = '.'.join(str(n) for n in revno)
543
511
        return [(rev_id, revno_str, 0)]
544
512
 
545
513
 
546
 
def _generate_flat_revisions(branch, start_rev_id, end_rev_id, direction,
547
 
                             exclude_common_ancestry=False):
548
 
    result = _linear_view_revisions(
549
 
        branch, start_rev_id, end_rev_id,
550
 
        exclude_common_ancestry=exclude_common_ancestry)
 
514
def _generate_flat_revisions(branch, start_rev_id, end_rev_id, direction):
 
515
    result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
551
516
    # If a start limit was given and it's not obviously an
552
517
    # ancestor of the end limit, check it before outputting anything
553
518
    if direction == 'forward' or (start_rev_id
557
522
        except _StartNotLinearAncestor:
558
523
            raise errors.BzrCommandError('Start revision not found in'
559
524
                ' left-hand history of end revision.')
 
525
    if direction == 'forward':
 
526
        result = reversed(result)
560
527
    return result
561
528
 
562
529
 
563
530
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
564
 
                            delayed_graph_generation,
565
 
                            exclude_common_ancestry=False):
 
531
    delayed_graph_generation):
566
532
    # On large trees, generating the merge graph can take 30-60 seconds
567
533
    # so we delay doing it until a merge is detected, incrementally
568
534
    # returning initial (non-merge) revisions while we can.
569
 
 
570
 
    # The above is only true for old formats (<= 0.92), for newer formats, a
571
 
    # couple of seconds only should be needed to load the whole graph and the
572
 
    # other graph operations needed are even faster than that -- vila 100201
573
535
    initial_revisions = []
574
536
    if delayed_graph_generation:
575
537
        try:
576
 
            for rev_id, revno, depth in  _linear_view_revisions(
577
 
                branch, start_rev_id, end_rev_id, exclude_common_ancestry):
 
538
            for rev_id, revno, depth in \
 
539
                _linear_view_revisions(branch, start_rev_id, end_rev_id):
578
540
                if _has_merges(branch, rev_id):
579
 
                    # The end_rev_id can be nested down somewhere. We need an
580
 
                    # explicit ancestry check. There is an ambiguity here as we
581
 
                    # may not raise _StartNotLinearAncestor for a revision that
582
 
                    # is an ancestor but not a *linear* one. But since we have
583
 
                    # loaded the graph to do the check (or calculate a dotted
584
 
                    # revno), we may as well accept to show the log...  We need
585
 
                    # the check only if start_rev_id is not None as all
586
 
                    # revisions have _mod_revision.NULL_REVISION as an ancestor
587
 
                    # -- vila 20100319
588
 
                    graph = branch.repository.get_graph()
589
 
                    if (start_rev_id is not None
590
 
                        and not graph.is_ancestor(start_rev_id, end_rev_id)):
591
 
                        raise _StartNotLinearAncestor()
592
 
                    # Since we collected the revisions so far, we need to
593
 
                    # adjust end_rev_id.
594
541
                    end_rev_id = rev_id
595
542
                    break
596
543
                else:
597
544
                    initial_revisions.append((rev_id, revno, depth))
598
545
            else:
599
546
                # No merged revisions found
600
 
                return initial_revisions
 
547
                if direction == 'reverse':
 
548
                    return initial_revisions
 
549
                elif direction == 'forward':
 
550
                    return reversed(initial_revisions)
 
551
                else:
 
552
                    raise ValueError('invalid direction %r' % direction)
601
553
        except _StartNotLinearAncestor:
602
554
            # A merge was never detected so the lower revision limit can't
603
555
            # be nested down somewhere
604
556
            raise errors.BzrCommandError('Start revision not found in'
605
557
                ' history of end revision.')
606
558
 
607
 
    # We exit the loop above because we encounter a revision with merges, from
608
 
    # this revision, we need to switch to _graph_view_revisions.
609
 
 
610
559
    # A log including nested merges is required. If the direction is reverse,
611
560
    # we rebase the initial merge depths so that the development line is
612
561
    # shown naturally, i.e. just like it is for linear logging. We can easily
614
563
    # indented at the end seems slightly nicer in that case.
615
564
    view_revisions = chain(iter(initial_revisions),
616
565
        _graph_view_revisions(branch, start_rev_id, end_rev_id,
617
 
                              rebase_initial_depths=(direction == 'reverse'),
618
 
                              exclude_common_ancestry=exclude_common_ancestry))
619
 
    return view_revisions
 
566
        rebase_initial_depths=direction == 'reverse'))
 
567
    if direction == 'reverse':
 
568
        return view_revisions
 
569
    elif direction == 'forward':
 
570
        # Forward means oldest first, adjusting for depth.
 
571
        view_revisions = reverse_by_depth(list(view_revisions))
 
572
        return _rebase_merge_depth(view_revisions)
 
573
    else:
 
574
        raise ValueError('invalid direction %r' % direction)
620
575
 
621
576
 
622
577
def _has_merges(branch, rev_id):
625
580
    return len(parents) > 1
626
581
 
627
582
 
628
 
def _compute_revno_str(branch, rev_id):
629
 
    """Compute the revno string from a rev_id.
630
 
 
631
 
    :return: The revno string, or None if the revision is not in the supplied
632
 
        branch.
633
 
    """
634
 
    try:
635
 
        revno = branch.revision_id_to_dotted_revno(rev_id)
636
 
    except errors.NoSuchRevision:
637
 
        # The revision must be outside of this branch
638
 
        return None
639
 
    else:
640
 
        return '.'.join(str(n) for n in revno)
641
 
 
642
 
 
643
583
def _is_obvious_ancestor(branch, start_rev_id, end_rev_id):
644
584
    """Is start_rev_id an obvious ancestor of end_rev_id?"""
645
585
    if start_rev_id and end_rev_id:
646
 
        try:
647
 
            start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
648
 
            end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
649
 
        except errors.NoSuchRevision:
650
 
            # one or both is not in the branch; not obvious
651
 
            return False
 
586
        start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
 
587
        end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
652
588
        if len(start_dotted) == 1 and len(end_dotted) == 1:
653
589
            # both on mainline
654
590
            return start_dotted[0] <= end_dotted[0]
659
595
        else:
660
596
            # not obvious
661
597
            return False
662
 
    # if either start or end is not specified then we use either the first or
663
 
    # the last revision and *they* are obvious ancestors.
664
598
    return True
665
599
 
666
600
 
667
 
def _linear_view_revisions(branch, start_rev_id, end_rev_id,
668
 
                           exclude_common_ancestry=False):
 
601
def _linear_view_revisions(branch, start_rev_id, end_rev_id):
669
602
    """Calculate a sequence of revisions to view, newest to oldest.
670
603
 
671
604
    :param start_rev_id: the lower revision-id
672
605
    :param end_rev_id: the upper revision-id
673
 
    :param exclude_common_ancestry: Whether the start_rev_id should be part of
674
 
        the iterated revisions.
675
606
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
676
607
    :raises _StartNotLinearAncestor: if a start_rev_id is specified but
677
 
        is not found walking the left-hand history
 
608
      is not found walking the left-hand history
678
609
    """
679
610
    br_revno, br_rev_id = branch.last_revision_info()
680
611
    repo = branch.repository
688
619
            end_rev_id = br_rev_id
689
620
        found_start = start_rev_id is None
690
621
        for revision_id in repo.iter_reverse_revision_history(end_rev_id):
691
 
            revno_str = _compute_revno_str(branch, revision_id)
 
622
            revno = branch.revision_id_to_dotted_revno(revision_id)
 
623
            revno_str = '.'.join(str(n) for n in revno)
692
624
            if not found_start and revision_id == start_rev_id:
693
 
                if not exclude_common_ancestry:
694
 
                    yield revision_id, revno_str, 0
 
625
                yield revision_id, revno_str, 0
695
626
                found_start = True
696
627
                break
697
628
            else:
702
633
 
703
634
 
704
635
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
705
 
                          rebase_initial_depths=True,
706
 
                          exclude_common_ancestry=False):
 
636
    rebase_initial_depths=True):
707
637
    """Calculate revisions to view including merges, newest to oldest.
708
638
 
709
639
    :param branch: the branch
713
643
      revision is found?
714
644
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
715
645
    """
716
 
    if exclude_common_ancestry:
717
 
        stop_rule = 'with-merges-without-common-ancestry'
718
 
    else:
719
 
        stop_rule = 'with-merges'
720
646
    view_revisions = branch.iter_merge_sorted_revisions(
721
647
        start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
722
 
        stop_rule=stop_rule)
 
648
        stop_rule="with-merges")
723
649
    if not rebase_initial_depths:
724
650
        for (rev_id, merge_depth, revno, end_of_merge
725
651
             ) in view_revisions:
736
662
                depth_adjustment = merge_depth
737
663
            if depth_adjustment:
738
664
                if merge_depth < depth_adjustment:
739
 
                    # From now on we reduce the depth adjustement, this can be
740
 
                    # surprising for users. The alternative requires two passes
741
 
                    # which breaks the fast display of the first revision
742
 
                    # though.
743
665
                    depth_adjustment = merge_depth
744
666
                merge_depth -= depth_adjustment
745
667
            yield rev_id, '.'.join(map(str, revno)), merge_depth
746
668
 
747
669
 
748
 
@deprecated_function(deprecated_in((2, 2, 0)))
749
670
def calculate_view_revisions(branch, start_revision, end_revision, direction,
750
671
        specific_fileid, generate_merge_revisions):
751
672
    """Calculate the revisions to view.
753
674
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
754
675
             a list of the same tuples.
755
676
    """
 
677
    # This method is no longer called by the main code path.
 
678
    # It is retained for API compatibility and may be deprecated
 
679
    # soon. IGC 20090116
756
680
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
757
681
        end_revision)
758
682
    view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
826
750
    """
827
751
    if search is None:
828
752
        return log_rev_iterator
829
 
    searchRE = re.compile(search, re.IGNORECASE)
 
753
    searchRE = re_compile_checked(search, re.IGNORECASE,
 
754
            'log message filter')
830
755
    return _filter_message_re(searchRE, log_rev_iterator)
831
756
 
832
757
 
1107
1032
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
1108
1033
 
1109
1034
 
1110
 
@deprecated_function(deprecated_in((2, 2, 0)))
1111
1035
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
1112
1036
    """Filter view_revisions based on revision ranges.
1113
1037
 
1122
1046
 
1123
1047
    :return: The filtered view_revisions.
1124
1048
    """
 
1049
    # This method is no longer called by the main code path.
 
1050
    # It may be removed soon. IGC 20090127
1125
1051
    if start_rev_id or end_rev_id:
1126
1052
        revision_ids = [r for r, n, d in view_revisions]
1127
1053
        if start_rev_id:
1233
1159
    return result
1234
1160
 
1235
1161
 
1236
 
@deprecated_function(deprecated_in((2, 2, 0)))
1237
1162
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
1238
1163
                       include_merges=True):
1239
1164
    """Produce an iterator of revisions to show
1240
1165
    :return: an iterator of (revision_id, revno, merge_depth)
1241
1166
    (if there is no revno for a revision, None is supplied)
1242
1167
    """
 
1168
    # This method is no longer called by the main code path.
 
1169
    # It is retained for API compatibility and may be deprecated
 
1170
    # soon. IGC 20090127
1243
1171
    if not include_merges:
1244
1172
        revision_ids = mainline_revs[1:]
1245
1173
        if direction == 'reverse':
1316
1244
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
1317
1245
                 tags=None, diff=None):
1318
1246
        self.rev = rev
1319
 
        if revno is None:
1320
 
            self.revno = None
1321
 
        else:
1322
 
            self.revno = str(revno)
 
1247
        self.revno = str(revno)
1323
1248
        self.merge_depth = merge_depth
1324
1249
        self.delta = delta
1325
1250
        self.tags = tags
1366
1291
    preferred_levels = 0
1367
1292
 
1368
1293
    def __init__(self, to_file, show_ids=False, show_timezone='original',
1369
 
                 delta_format=None, levels=None, show_advice=False,
1370
 
                 to_exact_file=None, author_list_handler=None):
 
1294
                 delta_format=None, levels=None, show_advice=False):
1371
1295
        """Create a LogFormatter.
1372
1296
 
1373
1297
        :param to_file: the file to output to
1374
 
        :param to_exact_file: if set, gives an output stream to which 
1375
 
             non-Unicode diffs are written.
1376
1298
        :param show_ids: if True, revision-ids are to be displayed
1377
1299
        :param show_timezone: the timezone to use
1378
1300
        :param delta_format: the level of delta information to display
1381
1303
          let the log formatter decide.
1382
1304
        :param show_advice: whether to show advice at the end of the
1383
1305
          log or not
1384
 
        :param author_list_handler: callable generating a list of
1385
 
          authors to display for a given revision
1386
1306
        """
1387
1307
        self.to_file = to_file
1388
1308
        # 'exact' stream used to show diff, it should print content 'as is'
1389
1309
        # and should not try to decode/encode it to unicode to avoid bug #328007
1390
 
        if to_exact_file is not None:
1391
 
            self.to_exact_file = to_exact_file
1392
 
        else:
1393
 
            # XXX: somewhat hacky; this assumes it's a codec writer; it's better
1394
 
            # for code that expects to get diffs to pass in the exact file
1395
 
            # stream
1396
 
            self.to_exact_file = getattr(to_file, 'stream', to_file)
 
1310
        self.to_exact_file = getattr(to_file, 'stream', to_file)
1397
1311
        self.show_ids = show_ids
1398
1312
        self.show_timezone = show_timezone
1399
1313
        if delta_format is None:
1403
1317
        self.levels = levels
1404
1318
        self._show_advice = show_advice
1405
1319
        self._merge_count = 0
1406
 
        self._author_list_handler = author_list_handler
1407
1320
 
1408
1321
    def get_levels(self):
1409
1322
        """Get the number of levels to display or 0 for all."""
1441
1354
        return address
1442
1355
 
1443
1356
    def short_author(self, rev):
1444
 
        return self.authors(rev, 'first', short=True, sep=', ')
1445
 
 
1446
 
    def authors(self, rev, who, short=False, sep=None):
1447
 
        """Generate list of authors, taking --authors option into account.
1448
 
 
1449
 
        The caller has to specify the name of a author list handler,
1450
 
        as provided by the author list registry, using the ``who``
1451
 
        argument.  That name only sets a default, though: when the
1452
 
        user selected a different author list generation using the
1453
 
        ``--authors`` command line switch, as represented by the
1454
 
        ``author_list_handler`` constructor argument, that value takes
1455
 
        precedence.
1456
 
 
1457
 
        :param rev: The revision for which to generate the list of authors.
1458
 
        :param who: Name of the default handler.
1459
 
        :param short: Whether to shorten names to either name or address.
1460
 
        :param sep: What separator to use for automatic concatenation.
1461
 
        """
1462
 
        if self._author_list_handler is not None:
1463
 
            # The user did specify --authors, which overrides the default
1464
 
            author_list_handler = self._author_list_handler
1465
 
        else:
1466
 
            # The user didn't specify --authors, so we use the caller's default
1467
 
            author_list_handler = author_list_registry.get(who)
1468
 
        names = author_list_handler(rev)
1469
 
        if short:
1470
 
            for i in range(len(names)):
1471
 
                name, address = config.parse_username(names[i])
1472
 
                if name:
1473
 
                    names[i] = name
1474
 
                else:
1475
 
                    names[i] = address
1476
 
        if sep is not None:
1477
 
            names = sep.join(names)
1478
 
        return names
 
1357
        name, address = config.parse_username(rev.get_apparent_authors()[0])
 
1358
        if name:
 
1359
            return name
 
1360
        return address
1479
1361
 
1480
1362
    def merge_marker(self, revision):
1481
1363
        """Get the merge marker to include in the output or '' if none."""
1485
1367
        else:
1486
1368
            return ''
1487
1369
 
1488
 
    def show_properties(self, revision, indent):
1489
 
        """Displays the custom properties returned by each registered handler.
1490
 
 
1491
 
        If a registered handler raises an error it is propagated.
1492
 
        """
1493
 
        for line in self.custom_properties(revision):
1494
 
            self.to_file.write("%s%s\n" % (indent, line))
1495
 
 
1496
 
    def custom_properties(self, revision):
1497
 
        """Format the custom properties returned by each registered handler.
1498
 
 
1499
 
        If a registered handler raises an error it is propagated.
1500
 
 
1501
 
        :return: a list of formatted lines (excluding trailing newlines)
1502
 
        """
1503
 
        lines = self._foreign_info_properties(revision)
1504
 
        for key, handler in properties_handler_registry.iteritems():
1505
 
            lines.extend(self._format_properties(handler(revision)))
1506
 
        return lines
1507
 
 
1508
 
    def _foreign_info_properties(self, rev):
 
1370
    def show_foreign_info(self, rev, indent):
1509
1371
        """Custom log displayer for foreign revision identifiers.
1510
1372
 
1511
1373
        :param rev: Revision object.
1512
1374
        """
1513
1375
        # Revision comes directly from a foreign repository
1514
1376
        if isinstance(rev, foreign.ForeignRevision):
1515
 
            return self._format_properties(
1516
 
                rev.mapping.vcs.show_foreign_revid(rev.foreign_revid))
 
1377
            self._write_properties(indent, rev.mapping.vcs.show_foreign_revid(
 
1378
                rev.foreign_revid))
 
1379
            return
1517
1380
 
1518
1381
        # Imported foreign revision revision ids always contain :
1519
1382
        if not ":" in rev.revision_id:
1520
 
            return []
 
1383
            return
1521
1384
 
1522
1385
        # Revision was once imported from a foreign repository
1523
1386
        try:
1524
1387
            foreign_revid, mapping = \
1525
1388
                foreign.foreign_vcs_registry.parse_revision_id(rev.revision_id)
1526
1389
        except errors.InvalidRevisionId:
1527
 
            return []
 
1390
            return
1528
1391
 
1529
 
        return self._format_properties(
 
1392
        self._write_properties(indent, 
1530
1393
            mapping.vcs.show_foreign_revid(foreign_revid))
1531
1394
 
1532
 
    def _format_properties(self, properties):
1533
 
        lines = []
 
1395
    def show_properties(self, revision, indent):
 
1396
        """Displays the custom properties returned by each registered handler.
 
1397
 
 
1398
        If a registered handler raises an error it is propagated.
 
1399
        """
 
1400
        for key, handler in properties_handler_registry.iteritems():
 
1401
            self._write_properties(indent, handler(revision))
 
1402
 
 
1403
    def _write_properties(self, indent, properties):
1534
1404
        for key, value in properties.items():
1535
 
            lines.append(key + ': ' + value)
1536
 
        return lines
 
1405
            self.to_file.write(indent + key + ': ' + value + '\n')
1537
1406
 
1538
1407
    def show_diff(self, to_file, diff, indent):
1539
1408
        for l in diff.rstrip().split('\n'):
1540
1409
            to_file.write(indent + '%s\n' % (l,))
1541
1410
 
1542
1411
 
1543
 
# Separator between revisions in long format
1544
 
_LONG_SEP = '-' * 60
1545
 
 
1546
 
 
1547
1412
class LongLogFormatter(LogFormatter):
1548
1413
 
1549
1414
    supports_merge_revisions = True
1552
1417
    supports_tags = True
1553
1418
    supports_diff = True
1554
1419
 
1555
 
    def __init__(self, *args, **kwargs):
1556
 
        super(LongLogFormatter, self).__init__(*args, **kwargs)
1557
 
        if self.show_timezone == 'original':
1558
 
            self.date_string = self._date_string_original_timezone
1559
 
        else:
1560
 
            self.date_string = self._date_string_with_timezone
1561
 
 
1562
 
    def _date_string_with_timezone(self, rev):
1563
 
        return format_date(rev.timestamp, rev.timezone or 0,
1564
 
                           self.show_timezone)
1565
 
 
1566
 
    def _date_string_original_timezone(self, rev):
1567
 
        return format_date_with_offset_in_original_timezone(rev.timestamp,
1568
 
            rev.timezone or 0)
1569
 
 
1570
1420
    def log_revision(self, revision):
1571
1421
        """Log a revision, either merged or not."""
1572
1422
        indent = '    ' * revision.merge_depth
1573
 
        lines = [_LONG_SEP]
 
1423
        to_file = self.to_file
 
1424
        to_file.write(indent + '-' * 60 + '\n')
1574
1425
        if revision.revno is not None:
1575
 
            lines.append('revno: %s%s' % (revision.revno,
 
1426
            to_file.write(indent + 'revno: %s%s\n' % (revision.revno,
1576
1427
                self.merge_marker(revision)))
1577
1428
        if revision.tags:
1578
 
            lines.append('tags: %s' % (', '.join(revision.tags)))
1579
 
        if self.show_ids or revision.revno is None:
1580
 
            lines.append('revision-id: %s' % (revision.rev.revision_id,))
 
1429
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
1581
1430
        if self.show_ids:
 
1431
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
 
1432
            to_file.write('\n')
1582
1433
            for parent_id in revision.rev.parent_ids:
1583
 
                lines.append('parent: %s' % (parent_id,))
1584
 
        lines.extend(self.custom_properties(revision.rev))
 
1434
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
 
1435
        self.show_foreign_info(revision.rev, indent)
 
1436
        self.show_properties(revision.rev, indent)
1585
1437
 
1586
1438
        committer = revision.rev.committer
1587
 
        authors = self.authors(revision.rev, 'all')
 
1439
        authors = revision.rev.get_apparent_authors()
1588
1440
        if authors != [committer]:
1589
 
            lines.append('author: %s' % (", ".join(authors),))
1590
 
        lines.append('committer: %s' % (committer,))
 
1441
            to_file.write(indent + 'author: %s\n' % (", ".join(authors),))
 
1442
        to_file.write(indent + 'committer: %s\n' % (committer,))
1591
1443
 
1592
1444
        branch_nick = revision.rev.properties.get('branch-nick', None)
1593
1445
        if branch_nick is not None:
1594
 
            lines.append('branch nick: %s' % (branch_nick,))
1595
 
 
1596
 
        lines.append('timestamp: %s' % (self.date_string(revision.rev),))
1597
 
 
1598
 
        lines.append('message:')
 
1446
            to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
 
1447
 
 
1448
        date_str = format_date(revision.rev.timestamp,
 
1449
                               revision.rev.timezone or 0,
 
1450
                               self.show_timezone)
 
1451
        to_file.write(indent + 'timestamp: %s\n' % (date_str,))
 
1452
 
 
1453
        to_file.write(indent + 'message:\n')
1599
1454
        if not revision.rev.message:
1600
 
            lines.append('  (no message)')
 
1455
            to_file.write(indent + '  (no message)\n')
1601
1456
        else:
1602
1457
            message = revision.rev.message.rstrip('\r\n')
1603
1458
            for l in message.split('\n'):
1604
 
                lines.append('  %s' % (l,))
1605
 
 
1606
 
        # Dump the output, appending the delta and diff if requested
1607
 
        to_file = self.to_file
1608
 
        to_file.write("%s%s\n" % (indent, ('\n' + indent).join(lines)))
 
1459
                to_file.write(indent + '  %s\n' % (l,))
1609
1460
        if revision.delta is not None:
1610
 
            # Use the standard status output to display changes
1611
 
            from bzrlib.delta import report_delta
1612
 
            report_delta(to_file, revision.delta, short_status=False, 
1613
 
                         show_ids=self.show_ids, indent=indent)
 
1461
            # We don't respect delta_format for compatibility
 
1462
            revision.delta.show(to_file, self.show_ids, indent=indent,
 
1463
                                short_status=False)
1614
1464
        if revision.diff is not None:
1615
1465
            to_file.write(indent + 'diff:\n')
1616
 
            to_file.flush()
1617
1466
            # Note: we explicitly don't indent the diff (relative to the
1618
1467
            # revision information) so that the output can be fed to patch -p0
1619
1468
            self.show_diff(self.to_exact_file, revision.diff, indent)
1620
 
            self.to_exact_file.flush()
1621
1469
 
1622
1470
    def get_advice_separator(self):
1623
1471
        """Get the text separating the log from the closing advice."""
1647
1495
        indent = '    ' * depth
1648
1496
        revno_width = self.revno_width_by_depth.get(depth)
1649
1497
        if revno_width is None:
1650
 
            if revision.revno is None or revision.revno.find('.') == -1:
 
1498
            if revision.revno.find('.') == -1:
1651
1499
                # mainline revno, e.g. 12345
1652
1500
                revno_width = 5
1653
1501
            else:
1661
1509
        if revision.tags:
1662
1510
            tags = ' {%s}' % (', '.join(revision.tags))
1663
1511
        to_file.write(indent + "%*s %s\t%s%s%s\n" % (revno_width,
1664
 
                revision.revno or "", self.short_author(revision.rev),
 
1512
                revision.revno, self.short_author(revision.rev),
1665
1513
                format_date(revision.rev.timestamp,
1666
1514
                            revision.rev.timezone or 0,
1667
1515
                            self.show_timezone, date_fmt="%Y-%m-%d",
1668
1516
                            show_offset=False),
1669
1517
                tags, self.merge_marker(revision)))
 
1518
        self.show_foreign_info(revision.rev, indent+offset)
1670
1519
        self.show_properties(revision.rev, indent+offset)
1671
 
        if self.show_ids or revision.revno is None:
 
1520
        if self.show_ids:
1672
1521
            to_file.write(indent + offset + 'revision-id:%s\n'
1673
1522
                          % (revision.rev.revision_id,))
1674
1523
        if not revision.rev.message:
1679
1528
                to_file.write(indent + offset + '%s\n' % (l,))
1680
1529
 
1681
1530
        if revision.delta is not None:
1682
 
            # Use the standard status output to display changes
1683
 
            from bzrlib.delta import report_delta
1684
 
            report_delta(to_file, revision.delta, 
1685
 
                         short_status=self.delta_format==1, 
1686
 
                         show_ids=self.show_ids, indent=indent + offset)
 
1531
            revision.delta.show(to_file, self.show_ids, indent=indent + offset,
 
1532
                                short_status=self.delta_format==1)
1687
1533
        if revision.diff is not None:
1688
1534
            self.show_diff(self.to_exact_file, revision.diff, '      ')
1689
1535
        to_file.write('\n')
1697
1543
 
1698
1544
    def __init__(self, *args, **kwargs):
1699
1545
        super(LineLogFormatter, self).__init__(*args, **kwargs)
1700
 
        width = terminal_width()
1701
 
        if width is not None:
1702
 
            # we need one extra space for terminals that wrap on last char
1703
 
            width = width - 1
1704
 
        self._max_chars = width
 
1546
        self._max_chars = terminal_width() - 1
1705
1547
 
1706
1548
    def truncate(self, str, max_len):
1707
 
        if max_len is None or len(str) <= max_len:
 
1549
        if len(str) <= max_len:
1708
1550
            return str
1709
 
        return str[:max_len-3] + '...'
 
1551
        return str[:max_len-3]+'...'
1710
1552
 
1711
1553
    def date_string(self, rev):
1712
1554
        return format_date(rev.timestamp, rev.timezone or 0,
1764
1606
                               self.show_timezone,
1765
1607
                               date_fmt='%Y-%m-%d',
1766
1608
                               show_offset=False)
1767
 
        committer_str = self.authors(revision.rev, 'first', sep=', ')
1768
 
        committer_str = committer_str.replace(' <', '  <')
 
1609
        committer_str = revision.rev.committer.replace (' <', '  <')
1769
1610
        to_file.write('%s  %s\n\n' % (date_str,committer_str))
1770
1611
 
1771
1612
        if revision.delta is not None and revision.delta.has_changed():
1836
1677
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
1837
1678
 
1838
1679
 
1839
 
def author_list_all(rev):
1840
 
    return rev.get_apparent_authors()[:]
1841
 
 
1842
 
 
1843
 
def author_list_first(rev):
1844
 
    lst = rev.get_apparent_authors()
1845
 
    try:
1846
 
        return [lst[0]]
1847
 
    except IndexError:
1848
 
        return []
1849
 
 
1850
 
 
1851
 
def author_list_committer(rev):
1852
 
    return [rev.committer]
1853
 
 
1854
 
 
1855
 
author_list_registry = registry.Registry()
1856
 
 
1857
 
author_list_registry.register('all', author_list_all,
1858
 
                              'All authors')
1859
 
 
1860
 
author_list_registry.register('first', author_list_first,
1861
 
                              'The first author')
1862
 
 
1863
 
author_list_registry.register('committer', author_list_committer,
1864
 
                              'The committer')
1865
 
 
1866
 
 
1867
1680
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
1868
1681
    # deprecated; for compatibility
1869
1682
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
2020
1833
        lf.log_revision(lr)
2021
1834
 
2022
1835
 
2023
 
def _get_info_for_log_files(revisionspec_list, file_list, add_cleanup):
 
1836
def _get_info_for_log_files(revisionspec_list, file_list):
2024
1837
    """Find file-ids and kinds given a list of files and a revision range.
2025
1838
 
2026
1839
    We search for files at the end of the range. If not found there,
2030
1843
    :param file_list: the list of paths given on the command line;
2031
1844
      the first of these can be a branch location or a file path,
2032
1845
      the remainder must be file paths
2033
 
    :param add_cleanup: When the branch returned is read locked,
2034
 
      an unlock call will be queued to the cleanup.
2035
1846
    :return: (branch, info_list, start_rev_info, end_rev_info) where
2036
1847
      info_list is a list of (relative_path, file_id, kind) tuples where
2037
1848
      kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
2038
 
      branch will be read-locked.
2039
1849
    """
2040
 
    from builtins import _get_revision_range
 
1850
    from builtins import _get_revision_range, safe_relpath_files
2041
1851
    tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
2042
 
    add_cleanup(b.lock_read().unlock)
2043
1852
    # XXX: It's damn messy converting a list of paths to relative paths when
2044
1853
    # those paths might be deleted ones, they might be on a case-insensitive
2045
1854
    # filesystem and/or they might be in silly locations (like another branch).
2049
1858
    # case of running log in a nested directory, assuming paths beyond the
2050
1859
    # first one haven't been deleted ...
2051
1860
    if tree:
2052
 
        relpaths = [path] + tree.safe_relpath_files(file_list[1:])
 
1861
        relpaths = [path] + safe_relpath_files(tree, file_list[1:])
2053
1862
    else:
2054
1863
        relpaths = [path] + file_list[1:]
2055
1864
    info_list = []
2124
1933
 
2125
1934
properties_handler_registry = registry.Registry()
2126
1935
 
2127
 
# Use the properties handlers to print out bug information if available
2128
 
def _bugs_properties_handler(revision):
2129
 
    if revision.properties.has_key('bugs'):
2130
 
        bug_lines = revision.properties['bugs'].split('\n')
2131
 
        bug_rows = [line.split(' ', 1) for line in bug_lines]
2132
 
        fixed_bug_urls = [row[0] for row in bug_rows if
2133
 
                          len(row) > 1 and row[1] == 'fixed']
2134
 
 
2135
 
        if fixed_bug_urls:
2136
 
            return {'fixes bug(s)': ' '.join(fixed_bug_urls)}
2137
 
    return {}
2138
 
 
2139
 
properties_handler_registry.register('bugs_properties_handler',
2140
 
                                     _bugs_properties_handler)
2141
 
 
2142
1936
 
2143
1937
# adapters which revision ids to log are filtered. When log is called, the
2144
1938
# log_rev_iterator is adapted through each of these factory methods.