~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/log.py

  • Committer: Robert Collins
  • Date: 2010-05-06 07:48:22 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506074822-0bsgf2j4h8jx0xkk
Added ``bzrlib.tests.matchers`` as a place to put matchers, along with
our first in-tree matcher. See the module docstring for details.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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
69
69
    config,
70
70
    diff,
71
71
    errors,
 
72
    foreign,
72
73
    repository as _mod_repository,
73
74
    revision as _mod_revision,
74
75
    revisionspec,
82
83
    )
83
84
from bzrlib.osutils import (
84
85
    format_date,
 
86
    format_date_with_offset_in_original_timezone,
85
87
    get_terminal_encoding,
86
88
    re_compile_checked,
87
89
    terminal_width,
88
90
    )
 
91
from bzrlib.symbol_versioning import (
 
92
    deprecated_function,
 
93
    deprecated_in,
 
94
    )
89
95
 
90
96
 
91
97
def find_touching_revisions(branch, file_id):
103
109
    last_path = None
104
110
    revno = 1
105
111
    for revision_id in branch.revision_history():
106
 
        this_inv = branch.repository.get_revision_inventory(revision_id)
 
112
        this_inv = branch.repository.get_inventory(revision_id)
107
113
        if file_id in this_inv:
108
114
            this_ie = this_inv[file_id]
109
115
            this_path = this_inv.id2path(file_id)
214
220
    'direction': 'reverse',
215
221
    'levels': 1,
216
222
    'generate_tags': True,
 
223
    'exclude_common_ancestry': False,
217
224
    '_match_using_deltas': True,
218
225
    }
219
226
 
220
227
 
221
228
def make_log_request_dict(direction='reverse', specific_fileids=None,
222
 
    start_revision=None, end_revision=None, limit=None,
223
 
    message_search=None, levels=1, generate_tags=True, delta_type=None,
224
 
    diff_type=None, _match_using_deltas=True):
 
229
                          start_revision=None, end_revision=None, limit=None,
 
230
                          message_search=None, levels=1, generate_tags=True,
 
231
                          delta_type=None,
 
232
                          diff_type=None, _match_using_deltas=True,
 
233
                          exclude_common_ancestry=False,
 
234
                          ):
225
235
    """Convenience function for making a logging request dictionary.
226
236
 
227
237
    Using this function may make code slightly safer by ensuring
265
275
      algorithm used for matching specific_fileids. This parameter
266
276
      may be removed in the future so bzrlib client code should NOT
267
277
      use it.
 
278
 
 
279
    :param exclude_common_ancestry: Whether -rX..Y should be interpreted as a
 
280
      range operator or as a graph difference.
268
281
    """
269
282
    return {
270
283
        'direction': direction,
277
290
        'generate_tags': generate_tags,
278
291
        'delta_type': delta_type,
279
292
        'diff_type': diff_type,
 
293
        'exclude_common_ancestry': exclude_common_ancestry,
280
294
        # Add 'private' attributes for features that may be deprecated
281
295
        '_match_using_deltas': _match_using_deltas,
282
296
    }
302
316
 
303
317
 
304
318
class Logger(object):
305
 
    """An object the generates, formats and displays a log."""
 
319
    """An object that generates, formats and displays a log."""
306
320
 
307
321
    def __init__(self, branch, rqst):
308
322
        """Create a Logger.
383
397
        :return: An iterator yielding LogRevision objects.
384
398
        """
385
399
        rqst = self.rqst
 
400
        levels = rqst.get('levels')
 
401
        limit = rqst.get('limit')
 
402
        diff_type = rqst.get('diff_type')
386
403
        log_count = 0
387
404
        revision_iterator = self._create_log_revision_iterator()
388
405
        for revs in revision_iterator:
389
406
            for (rev_id, revno, merge_depth), rev, delta in revs:
390
407
                # 0 levels means show everything; merge_depth counts from 0
391
 
                levels = rqst.get('levels')
392
408
                if levels != 0 and merge_depth >= levels:
393
409
                    continue
394
 
                diff = self._format_diff(rev, rev_id)
 
410
                if diff_type is None:
 
411
                    diff = None
 
412
                else:
 
413
                    diff = self._format_diff(rev, rev_id, diff_type)
395
414
                yield LogRevision(rev, revno, merge_depth, delta,
396
415
                    self.rev_tag_dict.get(rev_id), diff)
397
 
                limit = rqst.get('limit')
398
416
                if limit:
399
417
                    log_count += 1
400
418
                    if log_count >= limit:
401
419
                        return
402
420
 
403
 
    def _format_diff(self, rev, rev_id):
404
 
        diff_type = self.rqst.get('diff_type')
405
 
        if diff_type is None:
406
 
            return None
 
421
    def _format_diff(self, rev, rev_id, diff_type):
407
422
        repo = self.branch.repository
408
423
        if len(rev.parent_ids) == 0:
409
424
            ancestor_id = _mod_revision.NULL_REVISION
448
463
        generate_merge_revisions = rqst.get('levels') != 1
449
464
        delayed_graph_generation = not rqst.get('specific_fileids') and (
450
465
                rqst.get('limit') or self.start_rev_id or self.end_rev_id)
451
 
        view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
452
 
            self.end_rev_id, rqst.get('direction'), generate_merge_revisions,
453
 
            delayed_graph_generation=delayed_graph_generation)
 
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'))
454
472
 
455
473
        # Apply the other filters
456
474
        return make_log_rev_iterator(self.branch, view_revisions,
463
481
        # Note that we always generate the merge revisions because
464
482
        # filter_revisions_touching_file_id() requires them ...
465
483
        rqst = self.rqst
466
 
        view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
467
 
            self.end_rev_id, rqst.get('direction'), True)
 
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'))
468
488
        if not isinstance(view_revisions, list):
469
489
            view_revisions = list(view_revisions)
470
490
        view_revisions = _filter_revisions_touching_file_id(self.branch,
475
495
 
476
496
 
477
497
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
478
 
    generate_merge_revisions, delayed_graph_generation=False):
 
498
                         generate_merge_revisions,
 
499
                         delayed_graph_generation=False,
 
500
                         exclude_common_ancestry=False,
 
501
                         ):
479
502
    """Calculate the revisions to view.
480
503
 
481
504
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
482
505
             a list of the same tuples.
483
506
    """
 
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)
484
512
    br_revno, br_rev_id = branch.last_revision_info()
485
513
    if br_revno == 0:
486
514
        return []
487
515
 
488
 
    # If a single revision is requested, check we can handle it
489
 
    generate_single_revision = (end_rev_id and start_rev_id == end_rev_id and
490
 
        (not generate_merge_revisions or not _has_merges(branch, end_rev_id)))
491
 
    if generate_single_revision:
492
 
        return _generate_one_revision(branch, end_rev_id, br_rev_id, br_revno)
493
 
 
494
 
    # If we only want to see linear revisions, we can iterate ...
495
 
    if not generate_merge_revisions:
496
 
        return _generate_flat_revisions(branch, start_rev_id, end_rev_id,
497
 
            direction)
 
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)
 
526
        if direction == 'forward':
 
527
            iter_revs = reversed(iter_revs)
498
528
    else:
499
 
        return _generate_all_revisions(branch, start_rev_id, end_rev_id,
500
 
            direction, delayed_graph_generation)
 
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
501
535
 
502
536
 
503
537
def _generate_one_revision(branch, rev_id, br_rev_id, br_revno):
521
555
        except _StartNotLinearAncestor:
522
556
            raise errors.BzrCommandError('Start revision not found in'
523
557
                ' left-hand history of end revision.')
524
 
    if direction == 'forward':
525
 
        result = reversed(result)
526
558
    return result
527
559
 
528
560
 
529
561
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
530
 
    delayed_graph_generation):
 
562
                            delayed_graph_generation,
 
563
                            exclude_common_ancestry=False):
531
564
    # On large trees, generating the merge graph can take 30-60 seconds
532
565
    # so we delay doing it until a merge is detected, incrementally
533
566
    # returning initial (non-merge) revisions while we can.
 
567
 
 
568
    # The above is only true for old formats (<= 0.92), for newer formats, a
 
569
    # couple of seconds only should be needed to load the whole graph and the
 
570
    # other graph operations needed are even faster than that -- vila 100201
534
571
    initial_revisions = []
535
572
    if delayed_graph_generation:
536
573
        try:
537
 
            for rev_id, revno, depth in \
538
 
                _linear_view_revisions(branch, start_rev_id, end_rev_id):
 
574
            for rev_id, revno, depth in  _linear_view_revisions(
 
575
                branch, start_rev_id, end_rev_id):
539
576
                if _has_merges(branch, rev_id):
 
577
                    # The end_rev_id can be nested down somewhere. We need an
 
578
                    # explicit ancestry check. There is an ambiguity here as we
 
579
                    # may not raise _StartNotLinearAncestor for a revision that
 
580
                    # is an ancestor but not a *linear* one. But since we have
 
581
                    # loaded the graph to do the check (or calculate a dotted
 
582
                    # revno), we may as well accept to show the log...  We need
 
583
                    # the check only if start_rev_id is not None as all
 
584
                    # revisions have _mod_revision.NULL_REVISION as an ancestor
 
585
                    # -- vila 20100319
 
586
                    graph = branch.repository.get_graph()
 
587
                    if (start_rev_id is not None
 
588
                        and not graph.is_ancestor(start_rev_id, end_rev_id)):
 
589
                        raise _StartNotLinearAncestor()
 
590
                    # Since we collected the revisions so far, we need to
 
591
                    # adjust end_rev_id.
540
592
                    end_rev_id = rev_id
541
593
                    break
542
594
                else:
543
595
                    initial_revisions.append((rev_id, revno, depth))
544
596
            else:
545
597
                # No merged revisions found
546
 
                if direction == 'reverse':
547
 
                    return initial_revisions
548
 
                elif direction == 'forward':
549
 
                    return reversed(initial_revisions)
550
 
                else:
551
 
                    raise ValueError('invalid direction %r' % direction)
 
598
                return initial_revisions
552
599
        except _StartNotLinearAncestor:
553
600
            # A merge was never detected so the lower revision limit can't
554
601
            # be nested down somewhere
555
602
            raise errors.BzrCommandError('Start revision not found in'
556
603
                ' history of end revision.')
557
604
 
 
605
    # We exit the loop above because we encounter a revision with merges, from
 
606
    # this revision, we need to switch to _graph_view_revisions.
 
607
 
558
608
    # A log including nested merges is required. If the direction is reverse,
559
609
    # we rebase the initial merge depths so that the development line is
560
610
    # shown naturally, i.e. just like it is for linear logging. We can easily
562
612
    # indented at the end seems slightly nicer in that case.
563
613
    view_revisions = chain(iter(initial_revisions),
564
614
        _graph_view_revisions(branch, start_rev_id, end_rev_id,
565
 
        rebase_initial_depths=direction == 'reverse'))
566
 
    if direction == 'reverse':
567
 
        return view_revisions
568
 
    elif direction == 'forward':
569
 
        # Forward means oldest first, adjusting for depth.
570
 
        view_revisions = reverse_by_depth(list(view_revisions))
571
 
        return _rebase_merge_depth(view_revisions)
572
 
    else:
573
 
        raise ValueError('invalid direction %r' % direction)
 
615
                              rebase_initial_depths=(direction == 'reverse'),
 
616
                              exclude_common_ancestry=exclude_common_ancestry))
 
617
    return view_revisions
574
618
 
575
619
 
576
620
def _has_merges(branch, rev_id):
594
638
        else:
595
639
            # not obvious
596
640
            return False
 
641
    # if either start or end is not specified then we use either the first or
 
642
    # the last revision and *they* are obvious ancestors.
597
643
    return True
598
644
 
599
645
 
632
678
 
633
679
 
634
680
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
635
 
    rebase_initial_depths=True):
 
681
                          rebase_initial_depths=True,
 
682
                          exclude_common_ancestry=False):
636
683
    """Calculate revisions to view including merges, newest to oldest.
637
684
 
638
685
    :param branch: the branch
642
689
      revision is found?
643
690
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
644
691
    """
 
692
    if exclude_common_ancestry:
 
693
        stop_rule = 'with-merges-without-common-ancestry'
 
694
    else:
 
695
        stop_rule = 'with-merges'
645
696
    view_revisions = branch.iter_merge_sorted_revisions(
646
697
        start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
647
 
        stop_rule="with-merges")
 
698
        stop_rule=stop_rule)
648
699
    if not rebase_initial_depths:
649
700
        for (rev_id, merge_depth, revno, end_of_merge
650
701
             ) in view_revisions:
661
712
                depth_adjustment = merge_depth
662
713
            if depth_adjustment:
663
714
                if merge_depth < depth_adjustment:
 
715
                    # From now on we reduce the depth adjustement, this can be
 
716
                    # surprising for users. The alternative requires two passes
 
717
                    # which breaks the fast display of the first revision
 
718
                    # though.
664
719
                    depth_adjustment = merge_depth
665
720
                merge_depth -= depth_adjustment
666
721
            yield rev_id, '.'.join(map(str, revno)), merge_depth
667
722
 
668
723
 
 
724
@deprecated_function(deprecated_in((2, 2, 0)))
669
725
def calculate_view_revisions(branch, start_revision, end_revision, direction,
670
726
        specific_fileid, generate_merge_revisions):
671
727
    """Calculate the revisions to view.
673
729
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
674
730
             a list of the same tuples.
675
731
    """
676
 
    # This method is no longer called by the main code path.
677
 
    # It is retained for API compatibility and may be deprecated
678
 
    # soon. IGC 20090116
679
732
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
680
733
        end_revision)
681
734
    view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
1031
1084
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
1032
1085
 
1033
1086
 
 
1087
@deprecated_function(deprecated_in((2, 2, 0)))
1034
1088
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
1035
1089
    """Filter view_revisions based on revision ranges.
1036
1090
 
1045
1099
 
1046
1100
    :return: The filtered view_revisions.
1047
1101
    """
1048
 
    # This method is no longer called by the main code path.
1049
 
    # It may be removed soon. IGC 20090127
1050
1102
    if start_rev_id or end_rev_id:
1051
1103
        revision_ids = [r for r, n, d in view_revisions]
1052
1104
        if start_rev_id:
1158
1210
    return result
1159
1211
 
1160
1212
 
 
1213
@deprecated_function(deprecated_in((2, 2, 0)))
1161
1214
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
1162
1215
                       include_merges=True):
1163
1216
    """Produce an iterator of revisions to show
1164
1217
    :return: an iterator of (revision_id, revno, merge_depth)
1165
1218
    (if there is no revno for a revision, None is supplied)
1166
1219
    """
1167
 
    # This method is no longer called by the main code path.
1168
 
    # It is retained for API compatibility and may be deprecated
1169
 
    # soon. IGC 20090127
1170
1220
    if not include_merges:
1171
1221
        revision_ids = mainline_revs[1:]
1172
1222
        if direction == 'reverse':
1290
1340
    preferred_levels = 0
1291
1341
 
1292
1342
    def __init__(self, to_file, show_ids=False, show_timezone='original',
1293
 
                 delta_format=None, levels=None):
 
1343
                 delta_format=None, levels=None, show_advice=False,
 
1344
                 to_exact_file=None):
1294
1345
        """Create a LogFormatter.
1295
1346
 
1296
1347
        :param to_file: the file to output to
 
1348
        :param to_exact_file: if set, gives an output stream to which 
 
1349
             non-Unicode diffs are written.
1297
1350
        :param show_ids: if True, revision-ids are to be displayed
1298
1351
        :param show_timezone: the timezone to use
1299
1352
        :param delta_format: the level of delta information to display
1300
 
          or None to leave it u to the formatter to decide
 
1353
          or None to leave it to the formatter to decide
1301
1354
        :param levels: the number of levels to display; None or -1 to
1302
1355
          let the log formatter decide.
 
1356
        :param show_advice: whether to show advice at the end of the
 
1357
          log or not
1303
1358
        """
1304
1359
        self.to_file = to_file
1305
1360
        # 'exact' stream used to show diff, it should print content 'as is'
1306
1361
        # and should not try to decode/encode it to unicode to avoid bug #328007
1307
 
        self.to_exact_file = getattr(to_file, 'stream', to_file)
 
1362
        if to_exact_file is not None:
 
1363
            self.to_exact_file = to_exact_file
 
1364
        else:
 
1365
            # XXX: somewhat hacky; this assumes it's a codec writer; it's better
 
1366
            # for code that expects to get diffs to pass in the exact file
 
1367
            # stream
 
1368
            self.to_exact_file = getattr(to_file, 'stream', to_file)
1308
1369
        self.show_ids = show_ids
1309
1370
        self.show_timezone = show_timezone
1310
1371
        if delta_format is None:
1312
1373
            delta_format = 2 # long format
1313
1374
        self.delta_format = delta_format
1314
1375
        self.levels = levels
 
1376
        self._show_advice = show_advice
1315
1377
        self._merge_count = 0
1316
1378
 
1317
1379
    def get_levels(self):
1332
1394
 
1333
1395
    def show_advice(self):
1334
1396
        """Output user advice, if any, when the log is completed."""
1335
 
        if self.levels == 1 and self._merge_count > 0:
 
1397
        if self._show_advice and self.levels == 1 and self._merge_count > 0:
1336
1398
            advice_sep = self.get_advice_separator()
1337
1399
            if advice_sep:
1338
1400
                self.to_file.write(advice_sep)
1339
1401
            self.to_file.write(
1340
 
                "Use --levels 0 (or -n0) to see merged revisions.\n")
 
1402
                "Use --include-merges or -n0 to see merged revisions.\n")
1341
1403
 
1342
1404
    def get_advice_separator(self):
1343
1405
        """Get the text separating the log from the closing advice."""
1368
1430
 
1369
1431
        If a registered handler raises an error it is propagated.
1370
1432
        """
 
1433
        for line in self.custom_properties(revision):
 
1434
            self.to_file.write("%s%s\n" % (indent, line))
 
1435
 
 
1436
    def custom_properties(self, revision):
 
1437
        """Format the custom properties returned by each registered handler.
 
1438
 
 
1439
        If a registered handler raises an error it is propagated.
 
1440
 
 
1441
        :return: a list of formatted lines (excluding trailing newlines)
 
1442
        """
 
1443
        lines = self._foreign_info_properties(revision)
1371
1444
        for key, handler in properties_handler_registry.iteritems():
1372
 
            for key, value in handler(revision).items():
1373
 
                self.to_file.write(indent + key + ': ' + value + '\n')
 
1445
            lines.extend(self._format_properties(handler(revision)))
 
1446
        return lines
 
1447
 
 
1448
    def _foreign_info_properties(self, rev):
 
1449
        """Custom log displayer for foreign revision identifiers.
 
1450
 
 
1451
        :param rev: Revision object.
 
1452
        """
 
1453
        # Revision comes directly from a foreign repository
 
1454
        if isinstance(rev, foreign.ForeignRevision):
 
1455
            return self._format_properties(
 
1456
                rev.mapping.vcs.show_foreign_revid(rev.foreign_revid))
 
1457
 
 
1458
        # Imported foreign revision revision ids always contain :
 
1459
        if not ":" in rev.revision_id:
 
1460
            return []
 
1461
 
 
1462
        # Revision was once imported from a foreign repository
 
1463
        try:
 
1464
            foreign_revid, mapping = \
 
1465
                foreign.foreign_vcs_registry.parse_revision_id(rev.revision_id)
 
1466
        except errors.InvalidRevisionId:
 
1467
            return []
 
1468
 
 
1469
        return self._format_properties(
 
1470
            mapping.vcs.show_foreign_revid(foreign_revid))
 
1471
 
 
1472
    def _format_properties(self, properties):
 
1473
        lines = []
 
1474
        for key, value in properties.items():
 
1475
            lines.append(key + ': ' + value)
 
1476
        return lines
1374
1477
 
1375
1478
    def show_diff(self, to_file, diff, indent):
1376
1479
        for l in diff.rstrip().split('\n'):
1377
1480
            to_file.write(indent + '%s\n' % (l,))
1378
1481
 
1379
1482
 
 
1483
# Separator between revisions in long format
 
1484
_LONG_SEP = '-' * 60
 
1485
 
 
1486
 
1380
1487
class LongLogFormatter(LogFormatter):
1381
1488
 
1382
1489
    supports_merge_revisions = True
1385
1492
    supports_tags = True
1386
1493
    supports_diff = True
1387
1494
 
 
1495
    def __init__(self, *args, **kwargs):
 
1496
        super(LongLogFormatter, self).__init__(*args, **kwargs)
 
1497
        if self.show_timezone == 'original':
 
1498
            self.date_string = self._date_string_original_timezone
 
1499
        else:
 
1500
            self.date_string = self._date_string_with_timezone
 
1501
 
 
1502
    def _date_string_with_timezone(self, rev):
 
1503
        return format_date(rev.timestamp, rev.timezone or 0,
 
1504
                           self.show_timezone)
 
1505
 
 
1506
    def _date_string_original_timezone(self, rev):
 
1507
        return format_date_with_offset_in_original_timezone(rev.timestamp,
 
1508
            rev.timezone or 0)
 
1509
 
1388
1510
    def log_revision(self, revision):
1389
1511
        """Log a revision, either merged or not."""
1390
1512
        indent = '    ' * revision.merge_depth
1391
 
        to_file = self.to_file
1392
 
        to_file.write(indent + '-' * 60 + '\n')
 
1513
        lines = [_LONG_SEP]
1393
1514
        if revision.revno is not None:
1394
 
            to_file.write(indent + 'revno: %s%s\n' % (revision.revno,
 
1515
            lines.append('revno: %s%s' % (revision.revno,
1395
1516
                self.merge_marker(revision)))
1396
1517
        if revision.tags:
1397
 
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
 
1518
            lines.append('tags: %s' % (', '.join(revision.tags)))
1398
1519
        if self.show_ids:
1399
 
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
1400
 
            to_file.write('\n')
 
1520
            lines.append('revision-id: %s' % (revision.rev.revision_id,))
1401
1521
            for parent_id in revision.rev.parent_ids:
1402
 
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
1403
 
        self.show_properties(revision.rev, indent)
 
1522
                lines.append('parent: %s' % (parent_id,))
 
1523
        lines.extend(self.custom_properties(revision.rev))
1404
1524
 
1405
1525
        committer = revision.rev.committer
1406
1526
        authors = revision.rev.get_apparent_authors()
1407
1527
        if authors != [committer]:
1408
 
            to_file.write(indent + 'author: %s\n' % (", ".join(authors),))
1409
 
        to_file.write(indent + 'committer: %s\n' % (committer,))
 
1528
            lines.append('author: %s' % (", ".join(authors),))
 
1529
        lines.append('committer: %s' % (committer,))
1410
1530
 
1411
1531
        branch_nick = revision.rev.properties.get('branch-nick', None)
1412
1532
        if branch_nick is not None:
1413
 
            to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
1414
 
 
1415
 
        date_str = format_date(revision.rev.timestamp,
1416
 
                               revision.rev.timezone or 0,
1417
 
                               self.show_timezone)
1418
 
        to_file.write(indent + 'timestamp: %s\n' % (date_str,))
1419
 
 
1420
 
        to_file.write(indent + 'message:\n')
 
1533
            lines.append('branch nick: %s' % (branch_nick,))
 
1534
 
 
1535
        lines.append('timestamp: %s' % (self.date_string(revision.rev),))
 
1536
 
 
1537
        lines.append('message:')
1421
1538
        if not revision.rev.message:
1422
 
            to_file.write(indent + '  (no message)\n')
 
1539
            lines.append('  (no message)')
1423
1540
        else:
1424
1541
            message = revision.rev.message.rstrip('\r\n')
1425
1542
            for l in message.split('\n'):
1426
 
                to_file.write(indent + '  %s\n' % (l,))
 
1543
                lines.append('  %s' % (l,))
 
1544
 
 
1545
        # Dump the output, appending the delta and diff if requested
 
1546
        to_file = self.to_file
 
1547
        to_file.write("%s%s\n" % (indent, ('\n' + indent).join(lines)))
1427
1548
        if revision.delta is not None:
1428
 
            # We don't respect delta_format for compatibility
1429
 
            revision.delta.show(to_file, self.show_ids, indent=indent,
1430
 
                                short_status=False)
 
1549
            # Use the standard status output to display changes
 
1550
            from bzrlib.delta import report_delta
 
1551
            report_delta(to_file, revision.delta, short_status=False, 
 
1552
                         show_ids=self.show_ids, indent=indent)
1431
1553
        if revision.diff is not None:
1432
1554
            to_file.write(indent + 'diff:\n')
 
1555
            to_file.flush()
1433
1556
            # Note: we explicitly don't indent the diff (relative to the
1434
1557
            # revision information) so that the output can be fed to patch -p0
1435
1558
            self.show_diff(self.to_exact_file, revision.diff, indent)
 
1559
            self.to_exact_file.flush()
1436
1560
 
1437
1561
    def get_advice_separator(self):
1438
1562
        """Get the text separating the log from the closing advice."""
1494
1618
                to_file.write(indent + offset + '%s\n' % (l,))
1495
1619
 
1496
1620
        if revision.delta is not None:
1497
 
            revision.delta.show(to_file, self.show_ids, indent=indent + offset,
1498
 
                                short_status=self.delta_format==1)
 
1621
            # Use the standard status output to display changes
 
1622
            from bzrlib.delta import report_delta
 
1623
            report_delta(to_file, revision.delta, 
 
1624
                         short_status=self.delta_format==1, 
 
1625
                         show_ids=self.show_ids, indent=indent + offset)
1499
1626
        if revision.diff is not None:
1500
1627
            self.show_diff(self.to_exact_file, revision.diff, '      ')
1501
1628
        to_file.write('\n')
1509
1636
 
1510
1637
    def __init__(self, *args, **kwargs):
1511
1638
        super(LineLogFormatter, self).__init__(*args, **kwargs)
1512
 
        self._max_chars = terminal_width() - 1
 
1639
        width = terminal_width()
 
1640
        if width is not None:
 
1641
            # we need one extra space for terminals that wrap on last char
 
1642
            width = width - 1
 
1643
        self._max_chars = width
1513
1644
 
1514
1645
    def truncate(self, str, max_len):
1515
 
        if len(str) <= max_len:
 
1646
        if max_len is None or len(str) <= max_len:
1516
1647
            return str
1517
 
        return str[:max_len-3]+'...'
 
1648
        return str[:max_len-3] + '...'
1518
1649
 
1519
1650
    def date_string(self, rev):
1520
1651
        return format_date(rev.timestamp, rev.timezone or 0,
1572
1703
                               self.show_timezone,
1573
1704
                               date_fmt='%Y-%m-%d',
1574
1705
                               show_offset=False)
1575
 
        committer_str = revision.rev.committer.replace (' <', '  <')
 
1706
        committer_str = revision.rev.get_apparent_authors()[0].replace (' <', '  <')
1576
1707
        to_file.write('%s  %s\n\n' % (date_str,committer_str))
1577
1708
 
1578
1709
        if revision.delta is not None and revision.delta.has_changed():
1812
1943
    :return: (branch, info_list, start_rev_info, end_rev_info) where
1813
1944
      info_list is a list of (relative_path, file_id, kind) tuples where
1814
1945
      kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
 
1946
      branch will be read-locked.
1815
1947
    """
1816
1948
    from builtins import _get_revision_range, safe_relpath_files
1817
1949
    tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
 
1950
    b.lock_read()
1818
1951
    # XXX: It's damn messy converting a list of paths to relative paths when
1819
1952
    # those paths might be deleted ones, they might be on a case-insensitive
1820
1953
    # filesystem and/or they might be in silly locations (like another branch).
1830
1963
    info_list = []
1831
1964
    start_rev_info, end_rev_info = _get_revision_range(revisionspec_list, b,
1832
1965
        "log")
 
1966
    if relpaths in ([], [u'']):
 
1967
        return b, [], start_rev_info, end_rev_info
1833
1968
    if start_rev_info is None and end_rev_info is None:
1834
1969
        if tree is None:
1835
1970
            tree = b.basis_tree()
1896
2031
 
1897
2032
 
1898
2033
properties_handler_registry = registry.Registry()
1899
 
properties_handler_registry.register_lazy("foreign",
1900
 
                                          "bzrlib.foreign",
1901
 
                                          "show_foreign_properties")
 
2034
 
 
2035
# Use the properties handlers to print out bug information if available
 
2036
def _bugs_properties_handler(revision):
 
2037
    if revision.properties.has_key('bugs'):
 
2038
        bug_lines = revision.properties['bugs'].split('\n')
 
2039
        bug_rows = [line.split(' ', 1) for line in bug_lines]
 
2040
        fixed_bug_urls = [row[0] for row in bug_rows if
 
2041
                          len(row) > 1 and row[1] == 'fixed']
 
2042
 
 
2043
        if fixed_bug_urls:
 
2044
            return {'fixes bug(s)': ' '.join(fixed_bug_urls)}
 
2045
    return {}
 
2046
 
 
2047
properties_handler_registry.register('bugs_properties_handler',
 
2048
                                     _bugs_properties_handler)
1902
2049
 
1903
2050
 
1904
2051
# adapters which revision ids to log are filtered. When log is called, the