~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/log.py

  • Committer: Martin Pool
  • Date: 2010-04-01 04:41:18 UTC
  • mto: This revision was merged to the branch mainline in revision 5128.
  • Revision ID: mbp@sourcefrog.net-20100401044118-shyctqc02ob08ngz
ignore .testrepository

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
83
83
    )
84
84
from bzrlib.osutils import (
85
85
    format_date,
 
86
    format_date_with_offset_in_original_timezone,
86
87
    get_terminal_encoding,
87
88
    re_compile_checked,
88
89
    terminal_width,
89
90
    )
 
91
from bzrlib.symbol_versioning import (
 
92
    deprecated_function,
 
93
    deprecated_in,
 
94
    )
90
95
 
91
96
 
92
97
def find_touching_revisions(branch, file_id):
104
109
    last_path = None
105
110
    revno = 1
106
111
    for revision_id in branch.revision_history():
107
 
        this_inv = branch.repository.get_revision_inventory(revision_id)
 
112
        this_inv = branch.repository.get_inventory(revision_id)
108
113
        if file_id in this_inv:
109
114
            this_ie = this_inv[file_id]
110
115
            this_path = this_inv.id2path(file_id)
303
308
 
304
309
 
305
310
class Logger(object):
306
 
    """An object the generates, formats and displays a log."""
 
311
    """An object that generates, formats and displays a log."""
307
312
 
308
313
    def __init__(self, branch, rqst):
309
314
        """Create a Logger.
384
389
        :return: An iterator yielding LogRevision objects.
385
390
        """
386
391
        rqst = self.rqst
 
392
        levels = rqst.get('levels')
 
393
        limit = rqst.get('limit')
 
394
        diff_type = rqst.get('diff_type')
387
395
        log_count = 0
388
396
        revision_iterator = self._create_log_revision_iterator()
389
397
        for revs in revision_iterator:
390
398
            for (rev_id, revno, merge_depth), rev, delta in revs:
391
399
                # 0 levels means show everything; merge_depth counts from 0
392
 
                levels = rqst.get('levels')
393
400
                if levels != 0 and merge_depth >= levels:
394
401
                    continue
395
 
                diff = self._format_diff(rev, rev_id)
 
402
                if diff_type is None:
 
403
                    diff = None
 
404
                else:
 
405
                    diff = self._format_diff(rev, rev_id, diff_type)
396
406
                yield LogRevision(rev, revno, merge_depth, delta,
397
407
                    self.rev_tag_dict.get(rev_id), diff)
398
 
                limit = rqst.get('limit')
399
408
                if limit:
400
409
                    log_count += 1
401
410
                    if log_count >= limit:
402
411
                        return
403
412
 
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
 
413
    def _format_diff(self, rev, rev_id, diff_type):
408
414
        repo = self.branch.repository
409
415
        if len(rev.parent_ids) == 0:
410
416
            ancestor_id = _mod_revision.NULL_REVISION
528
534
 
529
535
 
530
536
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
531
 
    delayed_graph_generation):
 
537
                            delayed_graph_generation):
532
538
    # On large trees, generating the merge graph can take 30-60 seconds
533
539
    # so we delay doing it until a merge is detected, incrementally
534
540
    # returning initial (non-merge) revisions while we can.
 
541
 
 
542
    # The above is only true for old formats (<= 0.92), for newer formats, a
 
543
    # couple of seconds only should be needed to load the whole graph and the
 
544
    # other graph operations needed are even faster than that -- vila 100201
535
545
    initial_revisions = []
536
546
    if delayed_graph_generation:
537
547
        try:
538
 
            for rev_id, revno, depth in \
539
 
                _linear_view_revisions(branch, start_rev_id, end_rev_id):
 
548
            for rev_id, revno, depth in  _linear_view_revisions(
 
549
                branch, start_rev_id, end_rev_id):
540
550
                if _has_merges(branch, rev_id):
 
551
                    # The end_rev_id can be nested down somewhere. We need an
 
552
                    # explicit ancestry check. There is an ambiguity here as we
 
553
                    # may not raise _StartNotLinearAncestor for a revision that
 
554
                    # is an ancestor but not a *linear* one. But since we have
 
555
                    # loaded the graph to do the check (or calculate a dotted
 
556
                    # revno), we may as well accept to show the log...  We need
 
557
                    # the check only if start_rev_id is not None as all
 
558
                    # revisions have _mod_revision.NULL_REVISION as an ancestor
 
559
                    # -- vila 20100319
 
560
                    graph = branch.repository.get_graph()
 
561
                    if (start_rev_id is not None
 
562
                        and not graph.is_ancestor(start_rev_id, end_rev_id)):
 
563
                        raise _StartNotLinearAncestor()
 
564
                    # Since we collected the revisions so far, we need to
 
565
                    # adjust end_rev_id.
541
566
                    end_rev_id = rev_id
542
567
                    break
543
568
                else:
556
581
            raise errors.BzrCommandError('Start revision not found in'
557
582
                ' history of end revision.')
558
583
 
 
584
    # We exit the loop above because we encounter a revision with merges, from
 
585
    # this revision, we need to switch to _graph_view_revisions.
 
586
 
559
587
    # A log including nested merges is required. If the direction is reverse,
560
588
    # we rebase the initial merge depths so that the development line is
561
589
    # shown naturally, i.e. just like it is for linear logging. We can easily
563
591
    # indented at the end seems slightly nicer in that case.
564
592
    view_revisions = chain(iter(initial_revisions),
565
593
        _graph_view_revisions(branch, start_rev_id, end_rev_id,
566
 
        rebase_initial_depths=direction == 'reverse'))
 
594
                              rebase_initial_depths=(direction == 'reverse')))
567
595
    if direction == 'reverse':
568
596
        return view_revisions
569
597
    elif direction == 'forward':
595
623
        else:
596
624
            # not obvious
597
625
            return False
 
626
    # if either start or end is not specified then we use either the first or
 
627
    # the last revision and *they* are obvious ancestors.
598
628
    return True
599
629
 
600
630
 
633
663
 
634
664
 
635
665
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
636
 
    rebase_initial_depths=True):
 
666
                          rebase_initial_depths=True):
637
667
    """Calculate revisions to view including merges, newest to oldest.
638
668
 
639
669
    :param branch: the branch
662
692
                depth_adjustment = merge_depth
663
693
            if depth_adjustment:
664
694
                if merge_depth < depth_adjustment:
 
695
                    # From now on we reduce the depth adjustement, this can be
 
696
                    # surprising for users. The alternative requires two passes
 
697
                    # which breaks the fast display of the first revision
 
698
                    # though.
665
699
                    depth_adjustment = merge_depth
666
700
                merge_depth -= depth_adjustment
667
701
            yield rev_id, '.'.join(map(str, revno)), merge_depth
668
702
 
669
703
 
 
704
@deprecated_function(deprecated_in((2, 2, 0)))
670
705
def calculate_view_revisions(branch, start_revision, end_revision, direction,
671
706
        specific_fileid, generate_merge_revisions):
672
707
    """Calculate the revisions to view.
674
709
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
675
710
             a list of the same tuples.
676
711
    """
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
680
712
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
681
713
        end_revision)
682
714
    view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
1032
1064
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
1033
1065
 
1034
1066
 
 
1067
@deprecated_function(deprecated_in((2, 2, 0)))
1035
1068
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
1036
1069
    """Filter view_revisions based on revision ranges.
1037
1070
 
1046
1079
 
1047
1080
    :return: The filtered view_revisions.
1048
1081
    """
1049
 
    # This method is no longer called by the main code path.
1050
 
    # It may be removed soon. IGC 20090127
1051
1082
    if start_rev_id or end_rev_id:
1052
1083
        revision_ids = [r for r, n, d in view_revisions]
1053
1084
        if start_rev_id:
1159
1190
    return result
1160
1191
 
1161
1192
 
 
1193
@deprecated_function(deprecated_in((2, 2, 0)))
1162
1194
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
1163
1195
                       include_merges=True):
1164
1196
    """Produce an iterator of revisions to show
1165
1197
    :return: an iterator of (revision_id, revno, merge_depth)
1166
1198
    (if there is no revno for a revision, None is supplied)
1167
1199
    """
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
1171
1200
    if not include_merges:
1172
1201
        revision_ids = mainline_revs[1:]
1173
1202
        if direction == 'reverse':
1291
1320
    preferred_levels = 0
1292
1321
 
1293
1322
    def __init__(self, to_file, show_ids=False, show_timezone='original',
1294
 
                 delta_format=None, levels=None, show_advice=False):
 
1323
                 delta_format=None, levels=None, show_advice=False,
 
1324
                 to_exact_file=None):
1295
1325
        """Create a LogFormatter.
1296
1326
 
1297
1327
        :param to_file: the file to output to
 
1328
        :param to_exact_file: if set, gives an output stream to which 
 
1329
             non-Unicode diffs are written.
1298
1330
        :param show_ids: if True, revision-ids are to be displayed
1299
1331
        :param show_timezone: the timezone to use
1300
1332
        :param delta_format: the level of delta information to display
1307
1339
        self.to_file = to_file
1308
1340
        # 'exact' stream used to show diff, it should print content 'as is'
1309
1341
        # and should not try to decode/encode it to unicode to avoid bug #328007
1310
 
        self.to_exact_file = getattr(to_file, 'stream', to_file)
 
1342
        if to_exact_file is not None:
 
1343
            self.to_exact_file = to_exact_file
 
1344
        else:
 
1345
            # XXX: somewhat hacky; this assumes it's a codec writer; it's better
 
1346
            # for code that expects to get diffs to pass in the exact file
 
1347
            # stream
 
1348
            self.to_exact_file = getattr(to_file, 'stream', to_file)
1311
1349
        self.show_ids = show_ids
1312
1350
        self.show_timezone = show_timezone
1313
1351
        if delta_format is None:
1367
1405
        else:
1368
1406
            return ''
1369
1407
 
1370
 
    def show_foreign_info(self, rev, indent):
 
1408
    def show_properties(self, revision, indent):
 
1409
        """Displays the custom properties returned by each registered handler.
 
1410
 
 
1411
        If a registered handler raises an error it is propagated.
 
1412
        """
 
1413
        for line in self.custom_properties(revision):
 
1414
            self.to_file.write("%s%s\n" % (indent, line))
 
1415
 
 
1416
    def custom_properties(self, revision):
 
1417
        """Format the custom properties returned by each registered handler.
 
1418
 
 
1419
        If a registered handler raises an error it is propagated.
 
1420
 
 
1421
        :return: a list of formatted lines (excluding trailing newlines)
 
1422
        """
 
1423
        lines = self._foreign_info_properties(revision)
 
1424
        for key, handler in properties_handler_registry.iteritems():
 
1425
            lines.extend(self._format_properties(handler(revision)))
 
1426
        return lines
 
1427
 
 
1428
    def _foreign_info_properties(self, rev):
1371
1429
        """Custom log displayer for foreign revision identifiers.
1372
1430
 
1373
1431
        :param rev: Revision object.
1374
1432
        """
1375
1433
        # Revision comes directly from a foreign repository
1376
1434
        if isinstance(rev, foreign.ForeignRevision):
1377
 
            self._write_properties(indent, rev.mapping.vcs.show_foreign_revid(
1378
 
                rev.foreign_revid))
1379
 
            return
 
1435
            return self._format_properties(
 
1436
                rev.mapping.vcs.show_foreign_revid(rev.foreign_revid))
1380
1437
 
1381
1438
        # Imported foreign revision revision ids always contain :
1382
1439
        if not ":" in rev.revision_id:
1383
 
            return
 
1440
            return []
1384
1441
 
1385
1442
        # Revision was once imported from a foreign repository
1386
1443
        try:
1387
1444
            foreign_revid, mapping = \
1388
1445
                foreign.foreign_vcs_registry.parse_revision_id(rev.revision_id)
1389
1446
        except errors.InvalidRevisionId:
1390
 
            return
 
1447
            return []
1391
1448
 
1392
 
        self._write_properties(indent, 
 
1449
        return self._format_properties(
1393
1450
            mapping.vcs.show_foreign_revid(foreign_revid))
1394
1451
 
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):
 
1452
    def _format_properties(self, properties):
 
1453
        lines = []
1404
1454
        for key, value in properties.items():
1405
 
            self.to_file.write(indent + key + ': ' + value + '\n')
 
1455
            lines.append(key + ': ' + value)
 
1456
        return lines
1406
1457
 
1407
1458
    def show_diff(self, to_file, diff, indent):
1408
1459
        for l in diff.rstrip().split('\n'):
1409
1460
            to_file.write(indent + '%s\n' % (l,))
1410
1461
 
1411
1462
 
 
1463
# Separator between revisions in long format
 
1464
_LONG_SEP = '-' * 60
 
1465
 
 
1466
 
1412
1467
class LongLogFormatter(LogFormatter):
1413
1468
 
1414
1469
    supports_merge_revisions = True
1417
1472
    supports_tags = True
1418
1473
    supports_diff = True
1419
1474
 
 
1475
    def __init__(self, *args, **kwargs):
 
1476
        super(LongLogFormatter, self).__init__(*args, **kwargs)
 
1477
        if self.show_timezone == 'original':
 
1478
            self.date_string = self._date_string_original_timezone
 
1479
        else:
 
1480
            self.date_string = self._date_string_with_timezone
 
1481
 
 
1482
    def _date_string_with_timezone(self, rev):
 
1483
        return format_date(rev.timestamp, rev.timezone or 0,
 
1484
                           self.show_timezone)
 
1485
 
 
1486
    def _date_string_original_timezone(self, rev):
 
1487
        return format_date_with_offset_in_original_timezone(rev.timestamp,
 
1488
            rev.timezone or 0)
 
1489
 
1420
1490
    def log_revision(self, revision):
1421
1491
        """Log a revision, either merged or not."""
1422
1492
        indent = '    ' * revision.merge_depth
1423
 
        to_file = self.to_file
1424
 
        to_file.write(indent + '-' * 60 + '\n')
 
1493
        lines = [_LONG_SEP]
1425
1494
        if revision.revno is not None:
1426
 
            to_file.write(indent + 'revno: %s%s\n' % (revision.revno,
 
1495
            lines.append('revno: %s%s' % (revision.revno,
1427
1496
                self.merge_marker(revision)))
1428
1497
        if revision.tags:
1429
 
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
 
1498
            lines.append('tags: %s' % (', '.join(revision.tags)))
1430
1499
        if self.show_ids:
1431
 
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
1432
 
            to_file.write('\n')
 
1500
            lines.append('revision-id: %s' % (revision.rev.revision_id,))
1433
1501
            for parent_id in revision.rev.parent_ids:
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)
 
1502
                lines.append('parent: %s' % (parent_id,))
 
1503
        lines.extend(self.custom_properties(revision.rev))
1437
1504
 
1438
1505
        committer = revision.rev.committer
1439
1506
        authors = revision.rev.get_apparent_authors()
1440
1507
        if authors != [committer]:
1441
 
            to_file.write(indent + 'author: %s\n' % (", ".join(authors),))
1442
 
        to_file.write(indent + 'committer: %s\n' % (committer,))
 
1508
            lines.append('author: %s' % (", ".join(authors),))
 
1509
        lines.append('committer: %s' % (committer,))
1443
1510
 
1444
1511
        branch_nick = revision.rev.properties.get('branch-nick', None)
1445
1512
        if branch_nick is not None:
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')
 
1513
            lines.append('branch nick: %s' % (branch_nick,))
 
1514
 
 
1515
        lines.append('timestamp: %s' % (self.date_string(revision.rev),))
 
1516
 
 
1517
        lines.append('message:')
1454
1518
        if not revision.rev.message:
1455
 
            to_file.write(indent + '  (no message)\n')
 
1519
            lines.append('  (no message)')
1456
1520
        else:
1457
1521
            message = revision.rev.message.rstrip('\r\n')
1458
1522
            for l in message.split('\n'):
1459
 
                to_file.write(indent + '  %s\n' % (l,))
 
1523
                lines.append('  %s' % (l,))
 
1524
 
 
1525
        # Dump the output, appending the delta and diff if requested
 
1526
        to_file = self.to_file
 
1527
        to_file.write("%s%s\n" % (indent, ('\n' + indent).join(lines)))
1460
1528
        if revision.delta is not None:
1461
 
            # We don't respect delta_format for compatibility
1462
 
            revision.delta.show(to_file, self.show_ids, indent=indent,
1463
 
                                short_status=False)
 
1529
            # Use the standard status output to display changes
 
1530
            from bzrlib.delta import report_delta
 
1531
            report_delta(to_file, revision.delta, short_status=False, 
 
1532
                         show_ids=self.show_ids, indent=indent)
1464
1533
        if revision.diff is not None:
1465
1534
            to_file.write(indent + 'diff:\n')
 
1535
            to_file.flush()
1466
1536
            # Note: we explicitly don't indent the diff (relative to the
1467
1537
            # revision information) so that the output can be fed to patch -p0
1468
1538
            self.show_diff(self.to_exact_file, revision.diff, indent)
 
1539
            self.to_exact_file.flush()
1469
1540
 
1470
1541
    def get_advice_separator(self):
1471
1542
        """Get the text separating the log from the closing advice."""
1515
1586
                            self.show_timezone, date_fmt="%Y-%m-%d",
1516
1587
                            show_offset=False),
1517
1588
                tags, self.merge_marker(revision)))
1518
 
        self.show_foreign_info(revision.rev, indent+offset)
1519
1589
        self.show_properties(revision.rev, indent+offset)
1520
1590
        if self.show_ids:
1521
1591
            to_file.write(indent + offset + 'revision-id:%s\n'
1528
1598
                to_file.write(indent + offset + '%s\n' % (l,))
1529
1599
 
1530
1600
        if revision.delta is not None:
1531
 
            revision.delta.show(to_file, self.show_ids, indent=indent + offset,
1532
 
                                short_status=self.delta_format==1)
 
1601
            # Use the standard status output to display changes
 
1602
            from bzrlib.delta import report_delta
 
1603
            report_delta(to_file, revision.delta, 
 
1604
                         short_status=self.delta_format==1, 
 
1605
                         show_ids=self.show_ids, indent=indent + offset)
1533
1606
        if revision.diff is not None:
1534
1607
            self.show_diff(self.to_exact_file, revision.diff, '      ')
1535
1608
        to_file.write('\n')
1543
1616
 
1544
1617
    def __init__(self, *args, **kwargs):
1545
1618
        super(LineLogFormatter, self).__init__(*args, **kwargs)
1546
 
        self._max_chars = terminal_width() - 1
 
1619
        width = terminal_width()
 
1620
        if width is not None:
 
1621
            # we need one extra space for terminals that wrap on last char
 
1622
            width = width - 1
 
1623
        self._max_chars = width
1547
1624
 
1548
1625
    def truncate(self, str, max_len):
1549
 
        if len(str) <= max_len:
 
1626
        if max_len is None or len(str) <= max_len:
1550
1627
            return str
1551
 
        return str[:max_len-3]+'...'
 
1628
        return str[:max_len-3] + '...'
1552
1629
 
1553
1630
    def date_string(self, rev):
1554
1631
        return format_date(rev.timestamp, rev.timezone or 0,
1606
1683
                               self.show_timezone,
1607
1684
                               date_fmt='%Y-%m-%d',
1608
1685
                               show_offset=False)
1609
 
        committer_str = revision.rev.committer.replace (' <', '  <')
 
1686
        committer_str = revision.rev.get_apparent_authors()[0].replace (' <', '  <')
1610
1687
        to_file.write('%s  %s\n\n' % (date_str,committer_str))
1611
1688
 
1612
1689
        if revision.delta is not None and revision.delta.has_changed():
1846
1923
    :return: (branch, info_list, start_rev_info, end_rev_info) where
1847
1924
      info_list is a list of (relative_path, file_id, kind) tuples where
1848
1925
      kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
 
1926
      branch will be read-locked.
1849
1927
    """
1850
1928
    from builtins import _get_revision_range, safe_relpath_files
1851
1929
    tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
 
1930
    b.lock_read()
1852
1931
    # XXX: It's damn messy converting a list of paths to relative paths when
1853
1932
    # those paths might be deleted ones, they might be on a case-insensitive
1854
1933
    # filesystem and/or they might be in silly locations (like another branch).
1933
2012
 
1934
2013
properties_handler_registry = registry.Registry()
1935
2014
 
 
2015
# Use the properties handlers to print out bug information if available
 
2016
def _bugs_properties_handler(revision):
 
2017
    if revision.properties.has_key('bugs'):
 
2018
        bug_lines = revision.properties['bugs'].split('\n')
 
2019
        bug_rows = [line.split(' ', 1) for line in bug_lines]
 
2020
        fixed_bug_urls = [row[0] for row in bug_rows if
 
2021
                          len(row) > 1 and row[1] == 'fixed']
 
2022
 
 
2023
        if fixed_bug_urls:
 
2024
            return {'fixes bug(s)': ' '.join(fixed_bug_urls)}
 
2025
    return {}
 
2026
 
 
2027
properties_handler_registry.register('bugs_properties_handler',
 
2028
                                     _bugs_properties_handler)
 
2029
 
1936
2030
 
1937
2031
# adapters which revision ids to log are filtered. When log is called, the
1938
2032
# log_rev_iterator is adapted through each of these factory methods.