~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/log.py

  • Committer: Ian Clatworthy
  • Date: 2009-07-02 08:26:00 UTC
  • mto: (4527.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4529.
  • Revision ID: ian.clatworthy@canonical.com-20090702082600-qwb1evvvfa8ctnye
first draft of a 2.0 Upgrade Guide

Show diffs side-by-side

added added

removed removed

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