~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/log.py

  • Committer: Andrew Bennetts
  • Date: 2009-07-27 08:02:52 UTC
  • mto: This revision was merged to the branch mainline in revision 4573.
  • Revision ID: andrew.bennetts@canonical.com-20090727080252-1r4s9oqwlkzgywx7
Fix trivial bug in _vfs_set_tags_bytes.

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
 
    i18n,
78
78
    )
79
79
""")
80
80
 
81
81
from bzrlib import (
82
 
    lazy_regex,
83
82
    registry,
84
83
    )
85
84
from bzrlib.osutils import (
86
85
    format_date,
87
 
    format_date_with_offset_in_original_timezone,
88
 
    get_diff_header_encoding,
89
86
    get_terminal_encoding,
 
87
    re_compile_checked,
90
88
    terminal_width,
91
89
    )
92
90
 
106
104
    last_path = None
107
105
    revno = 1
108
106
    for revision_id in branch.revision_history():
109
 
        this_inv = branch.repository.get_inventory(revision_id)
110
 
        if this_inv.has_id(file_id):
 
107
        this_inv = branch.repository.get_revision_inventory(revision_id)
 
108
        if file_id in this_inv:
111
109
            this_ie = this_inv[file_id]
112
110
            this_path = this_inv.id2path(file_id)
113
111
        else:
153
151
             end_revision=None,
154
152
             search=None,
155
153
             limit=None,
156
 
             show_diff=False,
157
 
             match=None):
 
154
             show_diff=False):
158
155
    """Write out human-readable log of commits to this branch.
159
156
 
160
157
    This function is being retained for backwards compatibility but
183
180
        if None or 0.
184
181
 
185
182
    :param show_diff: If True, output a diff after each revision.
186
 
 
187
 
    :param match: Dictionary of search lists to use when matching revision
188
 
      properties.
189
183
    """
190
184
    # Convert old-style parameters to new-style parameters
191
185
    if specific_fileid is not None:
219
213
# make_log_request_dict() below
220
214
_DEFAULT_REQUEST_PARAMS = {
221
215
    'direction': 'reverse',
222
 
    'levels': None,
 
216
    'levels': 1,
223
217
    'generate_tags': True,
224
 
    'exclude_common_ancestry': False,
225
218
    '_match_using_deltas': True,
226
219
    }
227
220
 
228
221
 
229
222
def make_log_request_dict(direction='reverse', specific_fileids=None,
230
 
                          start_revision=None, end_revision=None, limit=None,
231
 
                          message_search=None, levels=None, generate_tags=True,
232
 
                          delta_type=None,
233
 
                          diff_type=None, _match_using_deltas=True,
234
 
                          exclude_common_ancestry=False, match=None,
235
 
                          signature=False,
236
 
                          ):
 
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):
237
226
    """Convenience function for making a logging request dictionary.
238
227
 
239
228
    Using this function may make code slightly safer by ensuring
259
248
      matching commit messages
260
249
 
261
250
    :param levels: the number of levels of revisions to
262
 
      generate; 1 for just the mainline; 0 for all levels, or None for
263
 
      a sensible default.
 
251
      generate; 1 for just the mainline; 0 for all levels.
264
252
 
265
253
    :param generate_tags: If True, include tags for matched revisions.
266
 
`
 
254
 
267
255
    :param delta_type: Either 'full', 'partial' or None.
268
256
      'full' means generate the complete delta - adds/deletes/modifies/etc;
269
257
      'partial' means filter the delta using specific_fileids;
278
266
      algorithm used for matching specific_fileids. This parameter
279
267
      may be removed in the future so bzrlib client code should NOT
280
268
      use it.
281
 
 
282
 
    :param exclude_common_ancestry: Whether -rX..Y should be interpreted as a
283
 
      range operator or as a graph difference.
284
 
 
285
 
    :param signature: show digital signature information
286
 
 
287
 
    :param match: Dictionary of list of search strings to use when filtering
288
 
      revisions. Keys can be 'message', 'author', 'committer', 'bugs' or
289
 
      the empty string to match any of the preceding properties.
290
 
 
291
269
    """
292
 
    # Take care of old style message_search parameter
293
 
    if message_search:
294
 
        if match:
295
 
            if 'message' in match:
296
 
                match['message'].append(message_search)
297
 
            else:
298
 
                match['message'] = [message_search]
299
 
        else:
300
 
            match={ 'message': [message_search] }
301
270
    return {
302
271
        'direction': direction,
303
272
        'specific_fileids': specific_fileids,
304
273
        'start_revision': start_revision,
305
274
        'end_revision': end_revision,
306
275
        'limit': limit,
 
276
        'message_search': message_search,
307
277
        'levels': levels,
308
278
        'generate_tags': generate_tags,
309
279
        'delta_type': delta_type,
310
280
        'diff_type': diff_type,
311
 
        'exclude_common_ancestry': exclude_common_ancestry,
312
 
        'signature': signature,
313
 
        'match': match,
314
281
        # Add 'private' attributes for features that may be deprecated
315
282
        '_match_using_deltas': _match_using_deltas,
316
283
    }
318
285
 
319
286
def _apply_log_request_defaults(rqst):
320
287
    """Apply default values to a request dictionary."""
321
 
    result = _DEFAULT_REQUEST_PARAMS.copy()
 
288
    result = _DEFAULT_REQUEST_PARAMS
322
289
    if rqst:
323
290
        result.update(rqst)
324
291
    return result
325
292
 
326
293
 
327
 
def format_signature_validity(rev_id, repo):
328
 
    """get the signature validity
329
 
 
330
 
    :param rev_id: revision id to validate
331
 
    :param repo: repository of revision
332
 
    :return: human readable string to print to log
333
 
    """
334
 
    from bzrlib import gpg
335
 
 
336
 
    gpg_strategy = gpg.GPGStrategy(None)
337
 
    result = repo.verify_revision(rev_id, gpg_strategy)
338
 
    if result[0] == gpg.SIGNATURE_VALID:
339
 
        return "valid signature from {0}".format(result[1])
340
 
    if result[0] == gpg.SIGNATURE_KEY_MISSING:
341
 
        return "unknown key {0}".format(result[1])
342
 
    if result[0] == gpg.SIGNATURE_NOT_VALID:
343
 
        return "invalid signature!"
344
 
    if result[0] == gpg.SIGNATURE_NOT_SIGNED:
345
 
        return "no signature"
346
 
 
347
 
 
348
294
class LogGenerator(object):
349
295
    """A generator of log revisions."""
350
296
 
357
303
 
358
304
 
359
305
class Logger(object):
360
 
    """An object that generates, formats and displays a log."""
 
306
    """An object the generates, formats and displays a log."""
361
307
 
362
308
    def __init__(self, branch, rqst):
363
309
        """Create a Logger.
395
341
        # Tweak the LogRequest based on what the LogFormatter can handle.
396
342
        # (There's no point generating stuff if the formatter can't display it.)
397
343
        rqst = self.rqst
398
 
        if rqst['levels'] is None or lf.get_levels() > rqst['levels']:
399
 
            # user didn't specify levels, use whatever the LF can handle:
400
 
            rqst['levels'] = lf.get_levels()
401
 
 
 
344
        rqst['levels'] = lf.get_levels()
402
345
        if not getattr(lf, 'supports_tags', False):
403
346
            rqst['generate_tags'] = False
404
347
        if not getattr(lf, 'supports_delta', False):
405
348
            rqst['delta_type'] = None
406
349
        if not getattr(lf, 'supports_diff', False):
407
350
            rqst['diff_type'] = None
408
 
        if not getattr(lf, 'supports_signatures', False):
409
 
            rqst['signature'] = False
410
351
 
411
352
        # Find and print the interesting revisions
412
353
        generator = self._generator_factory(self.branch, rqst)
416
357
 
417
358
    def _generator_factory(self, branch, rqst):
418
359
        """Make the LogGenerator object to use.
419
 
 
 
360
        
420
361
        Subclasses may wish to override this.
421
362
        """
422
363
        return _DefaultLogGenerator(branch, rqst)
443
384
        :return: An iterator yielding LogRevision objects.
444
385
        """
445
386
        rqst = self.rqst
446
 
        levels = rqst.get('levels')
447
 
        limit = rqst.get('limit')
448
 
        diff_type = rqst.get('diff_type')
449
 
        show_signature = rqst.get('signature')
450
387
        log_count = 0
451
388
        revision_iterator = self._create_log_revision_iterator()
452
389
        for revs in revision_iterator:
453
390
            for (rev_id, revno, merge_depth), rev, delta in revs:
454
391
                # 0 levels means show everything; merge_depth counts from 0
 
392
                levels = rqst.get('levels')
455
393
                if levels != 0 and merge_depth >= levels:
456
394
                    continue
457
 
                if diff_type is None:
458
 
                    diff = None
459
 
                else:
460
 
                    diff = self._format_diff(rev, rev_id, diff_type)
461
 
                if show_signature:
462
 
                    signature = format_signature_validity(rev_id,
463
 
                                                self.branch.repository)
464
 
                else:
465
 
                    signature = None
 
395
                diff = self._format_diff(rev, rev_id)
466
396
                yield LogRevision(rev, revno, merge_depth, delta,
467
 
                    self.rev_tag_dict.get(rev_id), diff, signature)
 
397
                    self.rev_tag_dict.get(rev_id), diff)
 
398
                limit = rqst.get('limit')
468
399
                if limit:
469
400
                    log_count += 1
470
401
                    if log_count >= limit:
471
402
                        return
472
403
 
473
 
    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
474
408
        repo = self.branch.repository
475
409
        if len(rev.parent_ids) == 0:
476
410
            ancestor_id = _mod_revision.NULL_REVISION
484
418
        else:
485
419
            specific_files = None
486
420
        s = StringIO()
487
 
        path_encoding = get_diff_header_encoding()
488
421
        diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
489
 
            new_label='', path_encoding=path_encoding)
 
422
            new_label='')
490
423
        return s.getvalue()
491
424
 
492
425
    def _create_log_revision_iterator(self):
516
449
        generate_merge_revisions = rqst.get('levels') != 1
517
450
        delayed_graph_generation = not rqst.get('specific_fileids') and (
518
451
                rqst.get('limit') or self.start_rev_id or self.end_rev_id)
519
 
        view_revisions = _calc_view_revisions(
520
 
            self.branch, self.start_rev_id, self.end_rev_id,
521
 
            rqst.get('direction'),
522
 
            generate_merge_revisions=generate_merge_revisions,
523
 
            delayed_graph_generation=delayed_graph_generation,
524
 
            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)
525
455
 
526
456
        # Apply the other filters
527
457
        return make_log_rev_iterator(self.branch, view_revisions,
528
 
            rqst.get('delta_type'), rqst.get('match'),
 
458
            rqst.get('delta_type'), rqst.get('message_search'),
529
459
            file_ids=rqst.get('specific_fileids'),
530
460
            direction=rqst.get('direction'))
531
461
 
534
464
        # Note that we always generate the merge revisions because
535
465
        # filter_revisions_touching_file_id() requires them ...
536
466
        rqst = self.rqst
537
 
        view_revisions = _calc_view_revisions(
538
 
            self.branch, self.start_rev_id, self.end_rev_id,
539
 
            rqst.get('direction'), generate_merge_revisions=True,
540
 
            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)
541
469
        if not isinstance(view_revisions, list):
542
470
            view_revisions = list(view_revisions)
543
471
        view_revisions = _filter_revisions_touching_file_id(self.branch,
544
472
            rqst.get('specific_fileids')[0], view_revisions,
545
473
            include_merges=rqst.get('levels') != 1)
546
474
        return make_log_rev_iterator(self.branch, view_revisions,
547
 
            rqst.get('delta_type'), rqst.get('match'))
 
475
            rqst.get('delta_type'), rqst.get('message_search'))
548
476
 
549
477
 
550
478
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
551
 
                         generate_merge_revisions,
552
 
                         delayed_graph_generation=False,
553
 
                         exclude_common_ancestry=False,
554
 
                         ):
 
479
    generate_merge_revisions, delayed_graph_generation=False):
555
480
    """Calculate the revisions to view.
556
481
 
557
482
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
558
483
             a list of the same tuples.
559
484
    """
560
 
    if (exclude_common_ancestry and start_rev_id == end_rev_id):
561
 
        raise errors.BzrCommandError(
562
 
            '--exclude-common-ancestry requires two different revisions')
563
 
    if direction not in ('reverse', 'forward'):
564
 
        raise ValueError('invalid direction %r' % direction)
565
485
    br_revno, br_rev_id = branch.last_revision_info()
566
486
    if br_revno == 0:
567
487
        return []
568
488
 
569
 
    if (end_rev_id and start_rev_id == end_rev_id
570
 
        and (not generate_merge_revisions
571
 
             or not _has_merges(branch, end_rev_id))):
572
 
        # If a single revision is requested, check we can handle it
573
 
        iter_revs = _generate_one_revision(branch, end_rev_id, br_rev_id,
574
 
                                           br_revno)
575
 
    elif not generate_merge_revisions:
576
 
        # If we only want to see linear revisions, we can iterate ...
577
 
        iter_revs = _generate_flat_revisions(branch, start_rev_id, end_rev_id,
578
 
                                             direction, exclude_common_ancestry)
579
 
        if direction == 'forward':
580
 
            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)
581
499
    else:
582
 
        iter_revs = _generate_all_revisions(branch, start_rev_id, end_rev_id,
583
 
                                            direction, delayed_graph_generation,
584
 
                                            exclude_common_ancestry)
585
 
        if direction == 'forward':
586
 
            iter_revs = _rebase_merge_depth(reverse_by_depth(list(iter_revs)))
587
 
    return iter_revs
 
500
        return _generate_all_revisions(branch, start_rev_id, end_rev_id,
 
501
            direction, delayed_graph_generation)
588
502
 
589
503
 
590
504
def _generate_one_revision(branch, rev_id, br_rev_id, br_revno):
592
506
        # It's the tip
593
507
        return [(br_rev_id, br_revno, 0)]
594
508
    else:
595
 
        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)
596
511
        return [(rev_id, revno_str, 0)]
597
512
 
598
513
 
599
 
def _generate_flat_revisions(branch, start_rev_id, end_rev_id, direction,
600
 
                             exclude_common_ancestry=False):
601
 
    result = _linear_view_revisions(
602
 
        branch, start_rev_id, end_rev_id,
603
 
        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)
604
516
    # If a start limit was given and it's not obviously an
605
517
    # ancestor of the end limit, check it before outputting anything
606
518
    if direction == 'forward' or (start_rev_id
610
522
        except _StartNotLinearAncestor:
611
523
            raise errors.BzrCommandError('Start revision not found in'
612
524
                ' left-hand history of end revision.')
 
525
    if direction == 'forward':
 
526
        result = reversed(result)
613
527
    return result
614
528
 
615
529
 
616
530
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
617
 
                            delayed_graph_generation,
618
 
                            exclude_common_ancestry=False):
 
531
    delayed_graph_generation):
619
532
    # On large trees, generating the merge graph can take 30-60 seconds
620
533
    # so we delay doing it until a merge is detected, incrementally
621
534
    # returning initial (non-merge) revisions while we can.
622
 
 
623
 
    # The above is only true for old formats (<= 0.92), for newer formats, a
624
 
    # couple of seconds only should be needed to load the whole graph and the
625
 
    # other graph operations needed are even faster than that -- vila 100201
626
535
    initial_revisions = []
627
536
    if delayed_graph_generation:
628
537
        try:
629
 
            for rev_id, revno, depth in  _linear_view_revisions(
630
 
                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):
631
540
                if _has_merges(branch, rev_id):
632
 
                    # The end_rev_id can be nested down somewhere. We need an
633
 
                    # explicit ancestry check. There is an ambiguity here as we
634
 
                    # may not raise _StartNotLinearAncestor for a revision that
635
 
                    # is an ancestor but not a *linear* one. But since we have
636
 
                    # loaded the graph to do the check (or calculate a dotted
637
 
                    # revno), we may as well accept to show the log...  We need
638
 
                    # the check only if start_rev_id is not None as all
639
 
                    # revisions have _mod_revision.NULL_REVISION as an ancestor
640
 
                    # -- vila 20100319
641
 
                    graph = branch.repository.get_graph()
642
 
                    if (start_rev_id is not None
643
 
                        and not graph.is_ancestor(start_rev_id, end_rev_id)):
644
 
                        raise _StartNotLinearAncestor()
645
 
                    # Since we collected the revisions so far, we need to
646
 
                    # adjust end_rev_id.
647
541
                    end_rev_id = rev_id
648
542
                    break
649
543
                else:
650
544
                    initial_revisions.append((rev_id, revno, depth))
651
545
            else:
652
546
                # No merged revisions found
653
 
                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)
654
553
        except _StartNotLinearAncestor:
655
554
            # A merge was never detected so the lower revision limit can't
656
555
            # be nested down somewhere
657
556
            raise errors.BzrCommandError('Start revision not found in'
658
557
                ' history of end revision.')
659
558
 
660
 
    # We exit the loop above because we encounter a revision with merges, from
661
 
    # this revision, we need to switch to _graph_view_revisions.
662
 
 
663
559
    # A log including nested merges is required. If the direction is reverse,
664
560
    # we rebase the initial merge depths so that the development line is
665
561
    # shown naturally, i.e. just like it is for linear logging. We can easily
667
563
    # indented at the end seems slightly nicer in that case.
668
564
    view_revisions = chain(iter(initial_revisions),
669
565
        _graph_view_revisions(branch, start_rev_id, end_rev_id,
670
 
                              rebase_initial_depths=(direction == 'reverse'),
671
 
                              exclude_common_ancestry=exclude_common_ancestry))
672
 
    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)
673
575
 
674
576
 
675
577
def _has_merges(branch, rev_id):
678
580
    return len(parents) > 1
679
581
 
680
582
 
681
 
def _compute_revno_str(branch, rev_id):
682
 
    """Compute the revno string from a rev_id.
683
 
 
684
 
    :return: The revno string, or None if the revision is not in the supplied
685
 
        branch.
686
 
    """
687
 
    try:
688
 
        revno = branch.revision_id_to_dotted_revno(rev_id)
689
 
    except errors.NoSuchRevision:
690
 
        # The revision must be outside of this branch
691
 
        return None
692
 
    else:
693
 
        return '.'.join(str(n) for n in revno)
694
 
 
695
 
 
696
583
def _is_obvious_ancestor(branch, start_rev_id, end_rev_id):
697
584
    """Is start_rev_id an obvious ancestor of end_rev_id?"""
698
585
    if start_rev_id and end_rev_id:
699
 
        try:
700
 
            start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
701
 
            end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
702
 
        except errors.NoSuchRevision:
703
 
            # one or both is not in the branch; not obvious
704
 
            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)
705
588
        if len(start_dotted) == 1 and len(end_dotted) == 1:
706
589
            # both on mainline
707
590
            return start_dotted[0] <= end_dotted[0]
712
595
        else:
713
596
            # not obvious
714
597
            return False
715
 
    # if either start or end is not specified then we use either the first or
716
 
    # the last revision and *they* are obvious ancestors.
717
598
    return True
718
599
 
719
600
 
720
 
def _linear_view_revisions(branch, start_rev_id, end_rev_id,
721
 
                           exclude_common_ancestry=False):
 
601
def _linear_view_revisions(branch, start_rev_id, end_rev_id):
722
602
    """Calculate a sequence of revisions to view, newest to oldest.
723
603
 
724
604
    :param start_rev_id: the lower revision-id
725
605
    :param end_rev_id: the upper revision-id
726
 
    :param exclude_common_ancestry: Whether the start_rev_id should be part of
727
 
        the iterated revisions.
728
606
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
729
607
    :raises _StartNotLinearAncestor: if a start_rev_id is specified but
730
 
        is not found walking the left-hand history
 
608
      is not found walking the left-hand history
731
609
    """
732
610
    br_revno, br_rev_id = branch.last_revision_info()
733
611
    repo = branch.repository
734
 
    graph = repo.get_graph()
735
612
    if start_rev_id is None and end_rev_id is None:
736
613
        cur_revno = br_revno
737
 
        for revision_id in graph.iter_lefthand_ancestry(br_rev_id,
738
 
            (_mod_revision.NULL_REVISION,)):
 
614
        for revision_id in repo.iter_reverse_revision_history(br_rev_id):
739
615
            yield revision_id, str(cur_revno), 0
740
616
            cur_revno -= 1
741
617
    else:
742
618
        if end_rev_id is None:
743
619
            end_rev_id = br_rev_id
744
620
        found_start = start_rev_id is None
745
 
        for revision_id in graph.iter_lefthand_ancestry(end_rev_id,
746
 
                (_mod_revision.NULL_REVISION,)):
747
 
            revno_str = _compute_revno_str(branch, revision_id)
 
621
        for revision_id in repo.iter_reverse_revision_history(end_rev_id):
 
622
            revno = branch.revision_id_to_dotted_revno(revision_id)
 
623
            revno_str = '.'.join(str(n) for n in revno)
748
624
            if not found_start and revision_id == start_rev_id:
749
 
                if not exclude_common_ancestry:
750
 
                    yield revision_id, revno_str, 0
 
625
                yield revision_id, revno_str, 0
751
626
                found_start = True
752
627
                break
753
628
            else:
758
633
 
759
634
 
760
635
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
761
 
                          rebase_initial_depths=True,
762
 
                          exclude_common_ancestry=False):
 
636
    rebase_initial_depths=True):
763
637
    """Calculate revisions to view including merges, newest to oldest.
764
638
 
765
639
    :param branch: the branch
769
643
      revision is found?
770
644
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
771
645
    """
772
 
    if exclude_common_ancestry:
773
 
        stop_rule = 'with-merges-without-common-ancestry'
774
 
    else:
775
 
        stop_rule = 'with-merges'
776
646
    view_revisions = branch.iter_merge_sorted_revisions(
777
647
        start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
778
 
        stop_rule=stop_rule)
 
648
        stop_rule="with-merges")
779
649
    if not rebase_initial_depths:
780
650
        for (rev_id, merge_depth, revno, end_of_merge
781
651
             ) in view_revisions:
792
662
                depth_adjustment = merge_depth
793
663
            if depth_adjustment:
794
664
                if merge_depth < depth_adjustment:
795
 
                    # From now on we reduce the depth adjustement, this can be
796
 
                    # surprising for users. The alternative requires two passes
797
 
                    # which breaks the fast display of the first revision
798
 
                    # though.
799
665
                    depth_adjustment = merge_depth
800
666
                merge_depth -= depth_adjustment
801
667
            yield rev_id, '.'.join(map(str, revno)), merge_depth
802
668
 
803
669
 
 
670
def calculate_view_revisions(branch, start_revision, end_revision, direction,
 
671
        specific_fileid, generate_merge_revisions):
 
672
    """Calculate the revisions to view.
 
673
 
 
674
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
 
675
             a list of the same tuples.
 
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
 
680
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
 
681
        end_revision)
 
682
    view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
 
683
        direction, generate_merge_revisions or specific_fileid))
 
684
    if specific_fileid:
 
685
        view_revisions = _filter_revisions_touching_file_id(branch,
 
686
            specific_fileid, view_revisions,
 
687
            include_merges=generate_merge_revisions)
 
688
    return _rebase_merge_depth(view_revisions)
 
689
 
 
690
 
804
691
def _rebase_merge_depth(view_revisions):
805
692
    """Adjust depths upwards so the top level is 0."""
806
693
    # If either the first or last revision have a merge_depth of 0, we're done
850
737
    return log_rev_iterator
851
738
 
852
739
 
853
 
def _make_search_filter(branch, generate_delta, match, log_rev_iterator):
 
740
def _make_search_filter(branch, generate_delta, search, log_rev_iterator):
854
741
    """Create a filtered iterator of log_rev_iterator matching on a regex.
855
742
 
856
743
    :param branch: The branch being logged.
857
744
    :param generate_delta: Whether to generate a delta for each revision.
858
 
    :param match: A dictionary with properties as keys and lists of strings
859
 
        as values. To match, a revision may match any of the supplied strings
860
 
        within a single property but must match at least one string for each
861
 
        property.
 
745
    :param search: A user text search string.
862
746
    :param log_rev_iterator: An input iterator containing all revisions that
863
747
        could be displayed, in lists.
864
748
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
865
749
        delta).
866
750
    """
867
 
    if match is None:
 
751
    if search is None:
868
752
        return log_rev_iterator
869
 
    searchRE = [(k, [re.compile(x, re.IGNORECASE) for x in v])
870
 
                for (k,v) in match.iteritems()]
871
 
    return _filter_re(searchRE, log_rev_iterator)
872
 
 
873
 
 
874
 
def _filter_re(searchRE, log_rev_iterator):
 
753
    searchRE = re_compile_checked(search, re.IGNORECASE,
 
754
            'log message filter')
 
755
    return _filter_message_re(searchRE, log_rev_iterator)
 
756
 
 
757
 
 
758
def _filter_message_re(searchRE, log_rev_iterator):
875
759
    for revs in log_rev_iterator:
876
 
        new_revs = [rev for rev in revs if _match_filter(searchRE, rev[1])]
877
 
        if new_revs:
878
 
            yield new_revs
879
 
 
880
 
def _match_filter(searchRE, rev):
881
 
    strings = {
882
 
               'message': (rev.message,),
883
 
               'committer': (rev.committer,),
884
 
               'author': (rev.get_apparent_authors()),
885
 
               'bugs': list(rev.iter_bugs())
886
 
               }
887
 
    strings[''] = [item for inner_list in strings.itervalues()
888
 
                   for item in inner_list]
889
 
    for (k,v) in searchRE:
890
 
        if k in strings and not _match_any_filter(strings[k], v):
891
 
            return False
892
 
    return True
893
 
 
894
 
def _match_any_filter(strings, res):
895
 
    return any([filter(None, map(re.search, strings)) for re in res])
 
760
        new_revs = []
 
761
        for (rev_id, revno, merge_depth), rev, delta in revs:
 
762
            if searchRE.search(rev.message):
 
763
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
 
764
        yield new_revs
 
765
 
896
766
 
897
767
def _make_delta_filter(branch, generate_delta, search, log_rev_iterator,
898
768
    fileids=None, direction='reverse'):
971
841
 
972
842
def _update_fileids(delta, fileids, stop_on):
973
843
    """Update the set of file-ids to search based on file lifecycle events.
974
 
 
 
844
    
975
845
    :param fileids: a set of fileids to update
976
846
    :param stop_on: either 'add' or 'remove' - take file-ids out of the
977
847
      fileids set once their add or remove entry is detected respectively
1018
888
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
1019
889
        delta).
1020
890
    """
 
891
    repository = branch.repository
1021
892
    num = 9
1022
893
    for batch in log_rev_iterator:
1023
894
        batch = iter(batch)
1140
1011
    cur_revno = branch_revno
1141
1012
    rev_nos = {}
1142
1013
    mainline_revs = []
1143
 
    graph = branch.repository.get_graph()
1144
 
    for revision_id in graph.iter_lefthand_ancestry(
1145
 
            branch_last_revision, (_mod_revision.NULL_REVISION,)):
 
1014
    for revision_id in branch.repository.iter_reverse_revision_history(
 
1015
                        branch_last_revision):
1146
1016
        if cur_revno < start_revno:
1147
1017
            # We have gone far enough, but we always add 1 more revision
1148
1018
            rev_nos[revision_id] = cur_revno
1162
1032
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
1163
1033
 
1164
1034
 
 
1035
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
 
1036
    """Filter view_revisions based on revision ranges.
 
1037
 
 
1038
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
 
1039
            tuples to be filtered.
 
1040
 
 
1041
    :param start_rev_id: If not NONE specifies the first revision to be logged.
 
1042
            If NONE then all revisions up to the end_rev_id are logged.
 
1043
 
 
1044
    :param end_rev_id: If not NONE specifies the last revision to be logged.
 
1045
            If NONE then all revisions up to the end of the log are logged.
 
1046
 
 
1047
    :return: The filtered view_revisions.
 
1048
    """
 
1049
    # This method is no longer called by the main code path.
 
1050
    # It may be removed soon. IGC 20090127
 
1051
    if start_rev_id or end_rev_id:
 
1052
        revision_ids = [r for r, n, d in view_revisions]
 
1053
        if start_rev_id:
 
1054
            start_index = revision_ids.index(start_rev_id)
 
1055
        else:
 
1056
            start_index = 0
 
1057
        if start_rev_id == end_rev_id:
 
1058
            end_index = start_index
 
1059
        else:
 
1060
            if end_rev_id:
 
1061
                end_index = revision_ids.index(end_rev_id)
 
1062
            else:
 
1063
                end_index = len(view_revisions) - 1
 
1064
        # To include the revisions merged into the last revision,
 
1065
        # extend end_rev_id down to, but not including, the next rev
 
1066
        # with the same or lesser merge_depth
 
1067
        end_merge_depth = view_revisions[end_index][2]
 
1068
        try:
 
1069
            for index in xrange(end_index+1, len(view_revisions)+1):
 
1070
                if view_revisions[index][2] <= end_merge_depth:
 
1071
                    end_index = index - 1
 
1072
                    break
 
1073
        except IndexError:
 
1074
            # if the search falls off the end then log to the end as well
 
1075
            end_index = len(view_revisions) - 1
 
1076
        view_revisions = view_revisions[start_index:end_index+1]
 
1077
    return view_revisions
 
1078
 
 
1079
 
1165
1080
def _filter_revisions_touching_file_id(branch, file_id, view_revisions,
1166
1081
    include_merges=True):
1167
1082
    r"""Return the list of revision ids which touch a given file id.
1170
1085
    This includes the revisions which directly change the file id,
1171
1086
    and the revisions which merge these changes. So if the
1172
1087
    revision graph is::
1173
 
 
1174
1088
        A-.
1175
1089
        |\ \
1176
1090
        B C E
1203
1117
    """
1204
1118
    # Lookup all possible text keys to determine which ones actually modified
1205
1119
    # the file.
1206
 
    graph = branch.repository.get_file_graph()
1207
 
    get_parent_map = graph.get_parent_map
1208
1120
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
1209
1121
    next_keys = None
1210
1122
    # Looking up keys in batches of 1000 can cut the time in half, as well as
1214
1126
    #       indexing layer. We might consider passing in hints as to the known
1215
1127
    #       access pattern (sparse/clustered, high success rate/low success
1216
1128
    #       rate). This particular access is clustered with a low success rate.
 
1129
    get_parent_map = branch.repository.texts.get_parent_map
1217
1130
    modified_text_revisions = set()
1218
1131
    chunk_size = 1000
1219
1132
    for start in xrange(0, len(text_keys), chunk_size):
1246
1159
    return result
1247
1160
 
1248
1161
 
 
1162
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
 
1163
                       include_merges=True):
 
1164
    """Produce an iterator of revisions to show
 
1165
    :return: an iterator of (revision_id, revno, merge_depth)
 
1166
    (if there is no revno for a revision, None is supplied)
 
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
 
1171
    if not include_merges:
 
1172
        revision_ids = mainline_revs[1:]
 
1173
        if direction == 'reverse':
 
1174
            revision_ids.reverse()
 
1175
        for revision_id in revision_ids:
 
1176
            yield revision_id, str(rev_nos[revision_id]), 0
 
1177
        return
 
1178
    graph = branch.repository.get_graph()
 
1179
    # This asks for all mainline revisions, which means we only have to spider
 
1180
    # sideways, rather than depth history. That said, its still size-of-history
 
1181
    # and should be addressed.
 
1182
    # mainline_revisions always includes an extra revision at the beginning, so
 
1183
    # don't request it.
 
1184
    parent_map = dict(((key, value) for key, value in
 
1185
        graph.iter_ancestry(mainline_revs[1:]) if value is not None))
 
1186
    # filter out ghosts; merge_sort errors on ghosts.
 
1187
    rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
 
1188
    merge_sorted_revisions = tsort.merge_sort(
 
1189
        rev_graph,
 
1190
        mainline_revs[-1],
 
1191
        mainline_revs,
 
1192
        generate_revno=True)
 
1193
 
 
1194
    if direction == 'forward':
 
1195
        # forward means oldest first.
 
1196
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
 
1197
    elif direction != 'reverse':
 
1198
        raise ValueError('invalid direction %r' % direction)
 
1199
 
 
1200
    for (sequence, rev_id, merge_depth, revno, end_of_merge
 
1201
         ) in merge_sorted_revisions:
 
1202
        yield rev_id, '.'.join(map(str, revno)), merge_depth
 
1203
 
 
1204
 
1249
1205
def reverse_by_depth(merge_sorted_revisions, _depth=0):
1250
1206
    """Reverse revisions by depth.
1251
1207
 
1286
1242
    """
1287
1243
 
1288
1244
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
1289
 
                 tags=None, diff=None, signature=None):
 
1245
                 tags=None, diff=None):
1290
1246
        self.rev = rev
1291
 
        if revno is None:
1292
 
            self.revno = None
1293
 
        else:
1294
 
            self.revno = str(revno)
 
1247
        self.revno = str(revno)
1295
1248
        self.merge_depth = merge_depth
1296
1249
        self.delta = delta
1297
1250
        self.tags = tags
1298
1251
        self.diff = diff
1299
 
        self.signature = signature
1300
1252
 
1301
1253
 
1302
1254
class LogFormatter(object):
1311
1263
    to indicate which LogRevision attributes it supports:
1312
1264
 
1313
1265
    - supports_delta must be True if this log formatter supports delta.
1314
 
      Otherwise the delta attribute may not be populated.  The 'delta_format'
1315
 
      attribute describes whether the 'short_status' format (1) or the long
1316
 
      one (2) should be used.
 
1266
        Otherwise the delta attribute may not be populated.  The 'delta_format'
 
1267
        attribute describes whether the 'short_status' format (1) or the long
 
1268
        one (2) should be used.
1317
1269
 
1318
1270
    - supports_merge_revisions must be True if this log formatter supports
1319
 
      merge revisions.  If not, then only mainline revisions will be passed
1320
 
      to the formatter.
 
1271
        merge revisions.  If not, then only mainline revisions will be passed
 
1272
        to the formatter.
1321
1273
 
1322
1274
    - preferred_levels is the number of levels this formatter defaults to.
1323
 
      The default value is zero meaning display all levels.
1324
 
      This value is only relevant if supports_merge_revisions is True.
 
1275
        The default value is zero meaning display all levels.
 
1276
        This value is only relevant if supports_merge_revisions is True.
1325
1277
 
1326
1278
    - supports_tags must be True if this log formatter supports tags.
1327
 
      Otherwise the tags attribute may not be populated.
 
1279
        Otherwise the tags attribute may not be populated.
1328
1280
 
1329
1281
    - supports_diff must be True if this log formatter supports diffs.
1330
 
      Otherwise the diff attribute may not be populated.
1331
 
 
1332
 
    - supports_signatures must be True if this log formatter supports GPG
1333
 
      signatures.
 
1282
        Otherwise the diff attribute may not be populated.
1334
1283
 
1335
1284
    Plugins can register functions to show custom revision properties using
1336
1285
    the properties_handler_registry. The registered function
1337
 
    must respect the following interface description::
1338
 
 
 
1286
    must respect the following interface description:
1339
1287
        def my_show_properties(properties_dict):
1340
1288
            # code that returns a dict {'name':'value'} of the properties
1341
1289
            # to be shown
1343
1291
    preferred_levels = 0
1344
1292
 
1345
1293
    def __init__(self, to_file, show_ids=False, show_timezone='original',
1346
 
                 delta_format=None, levels=None, show_advice=False,
1347
 
                 to_exact_file=None, author_list_handler=None):
 
1294
                 delta_format=None, levels=None, show_advice=False):
1348
1295
        """Create a LogFormatter.
1349
1296
 
1350
1297
        :param to_file: the file to output to
1351
 
        :param to_exact_file: if set, gives an output stream to which
1352
 
             non-Unicode diffs are written.
1353
1298
        :param show_ids: if True, revision-ids are to be displayed
1354
1299
        :param show_timezone: the timezone to use
1355
1300
        :param delta_format: the level of delta information to display
1358
1303
          let the log formatter decide.
1359
1304
        :param show_advice: whether to show advice at the end of the
1360
1305
          log or not
1361
 
        :param author_list_handler: callable generating a list of
1362
 
          authors to display for a given revision
1363
1306
        """
1364
1307
        self.to_file = to_file
1365
1308
        # 'exact' stream used to show diff, it should print content 'as is'
1366
1309
        # and should not try to decode/encode it to unicode to avoid bug #328007
1367
 
        if to_exact_file is not None:
1368
 
            self.to_exact_file = to_exact_file
1369
 
        else:
1370
 
            # XXX: somewhat hacky; this assumes it's a codec writer; it's better
1371
 
            # for code that expects to get diffs to pass in the exact file
1372
 
            # stream
1373
 
            self.to_exact_file = getattr(to_file, 'stream', to_file)
 
1310
        self.to_exact_file = getattr(to_file, 'stream', to_file)
1374
1311
        self.show_ids = show_ids
1375
1312
        self.show_timezone = show_timezone
1376
1313
        if delta_format is None:
1380
1317
        self.levels = levels
1381
1318
        self._show_advice = show_advice
1382
1319
        self._merge_count = 0
1383
 
        self._author_list_handler = author_list_handler
1384
1320
 
1385
1321
    def get_levels(self):
1386
1322
        """Get the number of levels to display or 0 for all."""
1418
1354
        return address
1419
1355
 
1420
1356
    def short_author(self, rev):
1421
 
        return self.authors(rev, 'first', short=True, sep=', ')
1422
 
 
1423
 
    def authors(self, rev, who, short=False, sep=None):
1424
 
        """Generate list of authors, taking --authors option into account.
1425
 
 
1426
 
        The caller has to specify the name of a author list handler,
1427
 
        as provided by the author list registry, using the ``who``
1428
 
        argument.  That name only sets a default, though: when the
1429
 
        user selected a different author list generation using the
1430
 
        ``--authors`` command line switch, as represented by the
1431
 
        ``author_list_handler`` constructor argument, that value takes
1432
 
        precedence.
1433
 
 
1434
 
        :param rev: The revision for which to generate the list of authors.
1435
 
        :param who: Name of the default handler.
1436
 
        :param short: Whether to shorten names to either name or address.
1437
 
        :param sep: What separator to use for automatic concatenation.
1438
 
        """
1439
 
        if self._author_list_handler is not None:
1440
 
            # The user did specify --authors, which overrides the default
1441
 
            author_list_handler = self._author_list_handler
1442
 
        else:
1443
 
            # The user didn't specify --authors, so we use the caller's default
1444
 
            author_list_handler = author_list_registry.get(who)
1445
 
        names = author_list_handler(rev)
1446
 
        if short:
1447
 
            for i in range(len(names)):
1448
 
                name, address = config.parse_username(names[i])
1449
 
                if name:
1450
 
                    names[i] = name
1451
 
                else:
1452
 
                    names[i] = address
1453
 
        if sep is not None:
1454
 
            names = sep.join(names)
1455
 
        return names
 
1357
        name, address = config.parse_username(rev.get_apparent_authors()[0])
 
1358
        if name:
 
1359
            return name
 
1360
        return address
1456
1361
 
1457
1362
    def merge_marker(self, revision):
1458
1363
        """Get the merge marker to include in the output or '' if none."""
1462
1367
        else:
1463
1368
            return ''
1464
1369
 
1465
 
    def show_properties(self, revision, indent):
1466
 
        """Displays the custom properties returned by each registered handler.
1467
 
 
1468
 
        If a registered handler raises an error it is propagated.
1469
 
        """
1470
 
        for line in self.custom_properties(revision):
1471
 
            self.to_file.write("%s%s\n" % (indent, line))
1472
 
 
1473
 
    def custom_properties(self, revision):
1474
 
        """Format the custom properties returned by each registered handler.
1475
 
 
1476
 
        If a registered handler raises an error it is propagated.
1477
 
 
1478
 
        :return: a list of formatted lines (excluding trailing newlines)
1479
 
        """
1480
 
        lines = self._foreign_info_properties(revision)
1481
 
        for key, handler in properties_handler_registry.iteritems():
1482
 
            lines.extend(self._format_properties(handler(revision)))
1483
 
        return lines
1484
 
 
1485
 
    def _foreign_info_properties(self, rev):
 
1370
    def show_foreign_info(self, rev, indent):
1486
1371
        """Custom log displayer for foreign revision identifiers.
1487
1372
 
1488
1373
        :param rev: Revision object.
1489
1374
        """
1490
1375
        # Revision comes directly from a foreign repository
1491
1376
        if isinstance(rev, foreign.ForeignRevision):
1492
 
            return self._format_properties(
1493
 
                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
1494
1380
 
1495
1381
        # Imported foreign revision revision ids always contain :
1496
1382
        if not ":" in rev.revision_id:
1497
 
            return []
 
1383
            return
1498
1384
 
1499
1385
        # Revision was once imported from a foreign repository
1500
1386
        try:
1501
1387
            foreign_revid, mapping = \
1502
1388
                foreign.foreign_vcs_registry.parse_revision_id(rev.revision_id)
1503
1389
        except errors.InvalidRevisionId:
1504
 
            return []
 
1390
            return
1505
1391
 
1506
 
        return self._format_properties(
 
1392
        self._write_properties(indent, 
1507
1393
            mapping.vcs.show_foreign_revid(foreign_revid))
1508
1394
 
1509
 
    def _format_properties(self, properties):
1510
 
        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):
1511
1404
        for key, value in properties.items():
1512
 
            lines.append(key + ': ' + value)
1513
 
        return lines
 
1405
            self.to_file.write(indent + key + ': ' + value + '\n')
1514
1406
 
1515
1407
    def show_diff(self, to_file, diff, indent):
1516
1408
        for l in diff.rstrip().split('\n'):
1517
1409
            to_file.write(indent + '%s\n' % (l,))
1518
1410
 
1519
1411
 
1520
 
# Separator between revisions in long format
1521
 
_LONG_SEP = '-' * 60
1522
 
 
1523
 
 
1524
1412
class LongLogFormatter(LogFormatter):
1525
1413
 
1526
1414
    supports_merge_revisions = True
1528
1416
    supports_delta = True
1529
1417
    supports_tags = True
1530
1418
    supports_diff = True
1531
 
    supports_signatures = True
1532
 
 
1533
 
    def __init__(self, *args, **kwargs):
1534
 
        super(LongLogFormatter, self).__init__(*args, **kwargs)
1535
 
        if self.show_timezone == 'original':
1536
 
            self.date_string = self._date_string_original_timezone
1537
 
        else:
1538
 
            self.date_string = self._date_string_with_timezone
1539
 
 
1540
 
    def _date_string_with_timezone(self, rev):
1541
 
        return format_date(rev.timestamp, rev.timezone or 0,
1542
 
                           self.show_timezone)
1543
 
 
1544
 
    def _date_string_original_timezone(self, rev):
1545
 
        return format_date_with_offset_in_original_timezone(rev.timestamp,
1546
 
            rev.timezone or 0)
1547
1419
 
1548
1420
    def log_revision(self, revision):
1549
1421
        """Log a revision, either merged or not."""
1550
1422
        indent = '    ' * revision.merge_depth
1551
 
        lines = [_LONG_SEP]
 
1423
        to_file = self.to_file
 
1424
        to_file.write(indent + '-' * 60 + '\n')
1552
1425
        if revision.revno is not None:
1553
 
            lines.append('revno: %s%s' % (revision.revno,
 
1426
            to_file.write(indent + 'revno: %s%s\n' % (revision.revno,
1554
1427
                self.merge_marker(revision)))
1555
1428
        if revision.tags:
1556
 
            lines.append('tags: %s' % (', '.join(revision.tags)))
1557
 
        if self.show_ids or revision.revno is None:
1558
 
            lines.append('revision-id: %s' % (revision.rev.revision_id,))
 
1429
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
1559
1430
        if self.show_ids:
 
1431
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
 
1432
            to_file.write('\n')
1560
1433
            for parent_id in revision.rev.parent_ids:
1561
 
                lines.append('parent: %s' % (parent_id,))
1562
 
        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)
1563
1437
 
1564
1438
        committer = revision.rev.committer
1565
 
        authors = self.authors(revision.rev, 'all')
 
1439
        authors = revision.rev.get_apparent_authors()
1566
1440
        if authors != [committer]:
1567
 
            lines.append('author: %s' % (", ".join(authors),))
1568
 
        lines.append('committer: %s' % (committer,))
 
1441
            to_file.write(indent + 'author: %s\n' % (", ".join(authors),))
 
1442
        to_file.write(indent + 'committer: %s\n' % (committer,))
1569
1443
 
1570
1444
        branch_nick = revision.rev.properties.get('branch-nick', None)
1571
1445
        if branch_nick is not None:
1572
 
            lines.append('branch nick: %s' % (branch_nick,))
1573
 
 
1574
 
        lines.append('timestamp: %s' % (self.date_string(revision.rev),))
1575
 
 
1576
 
        if revision.signature is not None:
1577
 
            lines.append('signature: ' + revision.signature)
1578
 
 
1579
 
        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')
1580
1454
        if not revision.rev.message:
1581
 
            lines.append('  (no message)')
 
1455
            to_file.write(indent + '  (no message)\n')
1582
1456
        else:
1583
1457
            message = revision.rev.message.rstrip('\r\n')
1584
1458
            for l in message.split('\n'):
1585
 
                lines.append('  %s' % (l,))
1586
 
 
1587
 
        # Dump the output, appending the delta and diff if requested
1588
 
        to_file = self.to_file
1589
 
        to_file.write("%s%s\n" % (indent, ('\n' + indent).join(lines)))
 
1459
                to_file.write(indent + '  %s\n' % (l,))
1590
1460
        if revision.delta is not None:
1591
 
            # Use the standard status output to display changes
1592
 
            from bzrlib.delta import report_delta
1593
 
            report_delta(to_file, revision.delta, short_status=False,
1594
 
                         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)
1595
1464
        if revision.diff is not None:
1596
1465
            to_file.write(indent + 'diff:\n')
1597
 
            to_file.flush()
1598
1466
            # Note: we explicitly don't indent the diff (relative to the
1599
1467
            # revision information) so that the output can be fed to patch -p0
1600
1468
            self.show_diff(self.to_exact_file, revision.diff, indent)
1601
 
            self.to_exact_file.flush()
1602
1469
 
1603
1470
    def get_advice_separator(self):
1604
1471
        """Get the text separating the log from the closing advice."""
1628
1495
        indent = '    ' * depth
1629
1496
        revno_width = self.revno_width_by_depth.get(depth)
1630
1497
        if revno_width is None:
1631
 
            if revision.revno is None or revision.revno.find('.') == -1:
 
1498
            if revision.revno.find('.') == -1:
1632
1499
                # mainline revno, e.g. 12345
1633
1500
                revno_width = 5
1634
1501
            else:
1642
1509
        if revision.tags:
1643
1510
            tags = ' {%s}' % (', '.join(revision.tags))
1644
1511
        to_file.write(indent + "%*s %s\t%s%s%s\n" % (revno_width,
1645
 
                revision.revno or "", self.short_author(revision.rev),
 
1512
                revision.revno, self.short_author(revision.rev),
1646
1513
                format_date(revision.rev.timestamp,
1647
1514
                            revision.rev.timezone or 0,
1648
1515
                            self.show_timezone, date_fmt="%Y-%m-%d",
1649
1516
                            show_offset=False),
1650
1517
                tags, self.merge_marker(revision)))
 
1518
        self.show_foreign_info(revision.rev, indent+offset)
1651
1519
        self.show_properties(revision.rev, indent+offset)
1652
 
        if self.show_ids or revision.revno is None:
 
1520
        if self.show_ids:
1653
1521
            to_file.write(indent + offset + 'revision-id:%s\n'
1654
1522
                          % (revision.rev.revision_id,))
1655
1523
        if not revision.rev.message:
1660
1528
                to_file.write(indent + offset + '%s\n' % (l,))
1661
1529
 
1662
1530
        if revision.delta is not None:
1663
 
            # Use the standard status output to display changes
1664
 
            from bzrlib.delta import report_delta
1665
 
            report_delta(to_file, revision.delta,
1666
 
                         short_status=self.delta_format==1,
1667
 
                         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)
1668
1533
        if revision.diff is not None:
1669
1534
            self.show_diff(self.to_exact_file, revision.diff, '      ')
1670
1535
        to_file.write('\n')
1678
1543
 
1679
1544
    def __init__(self, *args, **kwargs):
1680
1545
        super(LineLogFormatter, self).__init__(*args, **kwargs)
1681
 
        width = terminal_width()
1682
 
        if width is not None:
1683
 
            # we need one extra space for terminals that wrap on last char
1684
 
            width = width - 1
1685
 
        self._max_chars = width
 
1546
        self._max_chars = terminal_width() - 1
1686
1547
 
1687
1548
    def truncate(self, str, max_len):
1688
 
        if max_len is None or len(str) <= max_len:
 
1549
        if len(str) <= max_len:
1689
1550
            return str
1690
 
        return str[:max_len-3] + '...'
 
1551
        return str[:max_len-3]+'...'
1691
1552
 
1692
1553
    def date_string(self, rev):
1693
1554
        return format_date(rev.timestamp, rev.timezone or 0,
1708
1569
 
1709
1570
    def log_string(self, revno, rev, max_chars, tags=None, prefix=''):
1710
1571
        """Format log info into one string. Truncate tail of string
1711
 
 
1712
 
        :param revno:      revision number or None.
1713
 
                           Revision numbers counts from 1.
1714
 
        :param rev:        revision object
1715
 
        :param max_chars:  maximum length of resulting string
1716
 
        :param tags:       list of tags or None
1717
 
        :param prefix:     string to prefix each line
1718
 
        :return:           formatted truncated string
 
1572
        :param  revno:      revision number or None.
 
1573
                            Revision numbers counts from 1.
 
1574
        :param  rev:        revision object
 
1575
        :param  max_chars:  maximum length of resulting string
 
1576
        :param  tags:       list of tags or None
 
1577
        :param  prefix:     string to prefix each line
 
1578
        :return:            formatted truncated string
1719
1579
        """
1720
1580
        out = []
1721
1581
        if revno:
1722
1582
            # show revno only when is not None
1723
1583
            out.append("%s:" % revno)
1724
 
        if max_chars is not None:
1725
 
            out.append(self.truncate(self.short_author(rev), (max_chars+3)/4))
1726
 
        else:
1727
 
            out.append(self.short_author(rev))
 
1584
        out.append(self.truncate(self.short_author(rev), 20))
1728
1585
        out.append(self.date_string(rev))
1729
1586
        if len(rev.parent_ids) > 1:
1730
1587
            out.append('[merge]')
1749
1606
                               self.show_timezone,
1750
1607
                               date_fmt='%Y-%m-%d',
1751
1608
                               show_offset=False)
1752
 
        committer_str = self.authors(revision.rev, 'first', sep=', ')
1753
 
        committer_str = committer_str.replace(' <', '  <')
 
1609
        committer_str = revision.rev.committer.replace (' <', '  <')
1754
1610
        to_file.write('%s  %s\n\n' % (date_str,committer_str))
1755
1611
 
1756
1612
        if revision.delta is not None and revision.delta.has_changed():
1821
1677
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
1822
1678
 
1823
1679
 
1824
 
def author_list_all(rev):
1825
 
    return rev.get_apparent_authors()[:]
1826
 
 
1827
 
 
1828
 
def author_list_first(rev):
1829
 
    lst = rev.get_apparent_authors()
1830
 
    try:
1831
 
        return [lst[0]]
1832
 
    except IndexError:
1833
 
        return []
1834
 
 
1835
 
 
1836
 
def author_list_committer(rev):
1837
 
    return [rev.committer]
1838
 
 
1839
 
 
1840
 
author_list_registry = registry.Registry()
1841
 
 
1842
 
author_list_registry.register('all', author_list_all,
1843
 
                              'All authors')
1844
 
 
1845
 
author_list_registry.register('first', author_list_first,
1846
 
                              'The first author')
1847
 
 
1848
 
author_list_registry.register('committer', author_list_committer,
1849
 
                              'The committer')
 
1680
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
 
1681
    # deprecated; for compatibility
 
1682
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
 
1683
    lf.show(revno, rev, delta)
1850
1684
 
1851
1685
 
1852
1686
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
1917
1751
    old_revisions = set()
1918
1752
    new_history = []
1919
1753
    new_revisions = set()
1920
 
    graph = repository.get_graph()
1921
 
    new_iter = graph.iter_lefthand_ancestry(new_revision_id)
1922
 
    old_iter = graph.iter_lefthand_ancestry(old_revision_id)
 
1754
    new_iter = repository.iter_reverse_revision_history(new_revision_id)
 
1755
    old_iter = repository.iter_reverse_revision_history(old_revision_id)
1923
1756
    stop_revision = None
1924
1757
    do_old = True
1925
1758
    do_new = True
2000
1833
        lf.log_revision(lr)
2001
1834
 
2002
1835
 
2003
 
def _get_info_for_log_files(revisionspec_list, file_list, add_cleanup):
 
1836
def _get_info_for_log_files(revisionspec_list, file_list):
2004
1837
    """Find file-ids and kinds given a list of files and a revision range.
2005
1838
 
2006
1839
    We search for files at the end of the range. If not found there,
2010
1843
    :param file_list: the list of paths given on the command line;
2011
1844
      the first of these can be a branch location or a file path,
2012
1845
      the remainder must be file paths
2013
 
    :param add_cleanup: When the branch returned is read locked,
2014
 
      an unlock call will be queued to the cleanup.
2015
1846
    :return: (branch, info_list, start_rev_info, end_rev_info) where
2016
1847
      info_list is a list of (relative_path, file_id, kind) tuples where
2017
1848
      kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
2018
 
      branch will be read-locked.
2019
1849
    """
2020
 
    from builtins import _get_revision_range
 
1850
    from builtins import _get_revision_range, safe_relpath_files
2021
1851
    tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
2022
 
    add_cleanup(b.lock_read().unlock)
2023
1852
    # XXX: It's damn messy converting a list of paths to relative paths when
2024
1853
    # those paths might be deleted ones, they might be on a case-insensitive
2025
1854
    # filesystem and/or they might be in silly locations (like another branch).
2029
1858
    # case of running log in a nested directory, assuming paths beyond the
2030
1859
    # first one haven't been deleted ...
2031
1860
    if tree:
2032
 
        relpaths = [path] + tree.safe_relpath_files(file_list[1:])
 
1861
        relpaths = [path] + safe_relpath_files(tree, file_list[1:])
2033
1862
    else:
2034
1863
        relpaths = [path] + file_list[1:]
2035
1864
    info_list = []
2104
1933
 
2105
1934
properties_handler_registry = registry.Registry()
2106
1935
 
2107
 
# Use the properties handlers to print out bug information if available
2108
 
def _bugs_properties_handler(revision):
2109
 
    if revision.properties.has_key('bugs'):
2110
 
        bug_lines = revision.properties['bugs'].split('\n')
2111
 
        bug_rows = [line.split(' ', 1) for line in bug_lines]
2112
 
        fixed_bug_urls = [row[0] for row in bug_rows if
2113
 
                          len(row) > 1 and row[1] == 'fixed']
2114
 
 
2115
 
        if fixed_bug_urls:
2116
 
            return {'fixes bug(s)': ' '.join(fixed_bug_urls)}
2117
 
    return {}
2118
 
 
2119
 
properties_handler_registry.register('bugs_properties_handler',
2120
 
                                     _bugs_properties_handler)
2121
 
 
2122
1936
 
2123
1937
# adapters which revision ids to log are filtered. When log is called, the
2124
1938
# log_rev_iterator is adapted through each of these factory methods.