/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/log.py

  • Committer: Marius Kruger
  • Date: 2010-07-10 21:28:56 UTC
  • mto: (5384.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5385.
  • Revision ID: marius.kruger@enerweb.co.za-20100710212856-uq4ji3go0u5se7hx
* Update documentation
* add NEWS

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 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
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
 
 
18
 
17
19
"""Code to show logs of changes.
18
20
 
19
21
Various flavors of log can be produced:
47
49
all the changes since the previous revision that touched hello.c.
48
50
"""
49
51
 
50
 
from __future__ import absolute_import
51
 
 
52
52
import codecs
53
 
import itertools
 
53
from cStringIO import StringIO
 
54
from itertools import (
 
55
    chain,
 
56
    izip,
 
57
    )
54
58
import re
55
59
import sys
56
60
from warnings import (
57
61
    warn,
58
62
    )
59
63
 
60
 
from .lazy_import import lazy_import
 
64
from bzrlib.lazy_import import lazy_import
61
65
lazy_import(globals(), """
62
66
 
63
 
from breezy import (
 
67
from bzrlib import (
 
68
    bzrdir,
64
69
    config,
65
 
    controldir,
66
70
    diff,
 
71
    errors,
67
72
    foreign,
68
 
    lazy_regex,
 
73
    osutils,
 
74
    repository as _mod_repository,
69
75
    revision as _mod_revision,
 
76
    revisionspec,
 
77
    trace,
 
78
    tsort,
70
79
    )
71
 
from breezy.i18n import gettext, ngettext
72
80
""")
73
81
 
74
 
from . import (
75
 
    errors,
 
82
from bzrlib import (
76
83
    registry,
77
 
    revisionspec,
78
 
    trace,
79
84
    )
80
 
from .osutils import (
 
85
from bzrlib.osutils import (
81
86
    format_date,
82
87
    format_date_with_offset_in_original_timezone,
83
 
    get_diff_header_encoding,
84
88
    get_terminal_encoding,
85
89
    terminal_width,
86
90
    )
87
 
from .sixish import (
88
 
    BytesIO,
89
 
    range,
90
 
    zip,
 
91
from bzrlib.symbol_versioning import (
 
92
    deprecated_function,
 
93
    deprecated_in,
91
94
    )
92
 
from .tree import InterTree
93
 
 
94
 
 
95
 
def find_touching_revisions(repository, last_revision, last_tree, last_path):
 
95
 
 
96
 
 
97
def find_touching_revisions(branch, file_id):
96
98
    """Yield a description of revisions which affect the file_id.
97
99
 
98
100
    Each returned element is (revno, revision_id, description)
103
105
    TODO: Perhaps some way to limit this to only particular revisions,
104
106
    or to traverse a non-mainline set of revisions?
105
107
    """
106
 
    last_verifier = last_tree.get_file_verifier(last_path)
107
 
    graph = repository.get_graph()
108
 
    history = list(graph.iter_lefthand_ancestry(last_revision, []))
109
 
    revno = len(history)
110
 
    for revision_id in history:
111
 
        this_tree = repository.revision_tree(revision_id)
112
 
        this_intertree = InterTree.get(this_tree, last_tree)
113
 
        this_path = this_intertree.find_source_path(last_path)
 
108
    last_ie = None
 
109
    last_path = None
 
110
    revno = 1
 
111
    for revision_id in branch.revision_history():
 
112
        this_inv = branch.repository.get_inventory(revision_id)
 
113
        if file_id in this_inv:
 
114
            this_ie = this_inv[file_id]
 
115
            this_path = this_inv.id2path(file_id)
 
116
        else:
 
117
            this_ie = this_path = None
114
118
 
115
119
        # now we know how it was last time, and how it is in this revision.
116
120
        # are those two states effectively the same or not?
117
 
        if this_path is not None and last_path is None:
118
 
            yield revno, revision_id, "deleted " + this_path
119
 
            this_verifier = this_tree.get_file_verifier(this_path)
120
 
        elif this_path is None and last_path is not None:
121
 
            yield revno, revision_id, "added " + last_path
 
121
 
 
122
        if not this_ie and not last_ie:
 
123
            # not present in either
 
124
            pass
 
125
        elif this_ie and not last_ie:
 
126
            yield revno, revision_id, "added " + this_path
 
127
        elif not this_ie and last_ie:
 
128
            # deleted here
 
129
            yield revno, revision_id, "deleted " + last_path
122
130
        elif this_path != last_path:
123
 
            yield revno, revision_id, ("renamed %s => %s" % (this_path, last_path))
124
 
            this_verifier = this_tree.get_file_verifier(this_path)
125
 
        else:
126
 
            this_verifier = this_tree.get_file_verifier(this_path)
127
 
            if (this_verifier != last_verifier):
128
 
                yield revno, revision_id, "modified " + this_path
 
131
            yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
 
132
        elif (this_ie.text_size != last_ie.text_size
 
133
              or this_ie.text_sha1 != last_ie.text_sha1):
 
134
            yield revno, revision_id, "modified " + this_path
129
135
 
130
 
        last_verifier = this_verifier
 
136
        last_ie = this_ie
131
137
        last_path = this_path
132
 
        last_tree = this_tree
133
 
        if last_path is None:
134
 
            return
135
 
        revno -= 1
 
138
        revno += 1
 
139
 
 
140
 
 
141
def _enumerate_history(branch):
 
142
    rh = []
 
143
    revno = 1
 
144
    for rev_id in branch.revision_history():
 
145
        rh.append((revno, rev_id))
 
146
        revno += 1
 
147
    return rh
136
148
 
137
149
 
138
150
def show_log(branch,
139
151
             lf,
 
152
             specific_fileid=None,
140
153
             verbose=False,
141
154
             direction='reverse',
142
155
             start_revision=None,
143
156
             end_revision=None,
144
157
             search=None,
145
158
             limit=None,
146
 
             show_diff=False,
147
 
             match=None):
 
159
             show_diff=False):
148
160
    """Write out human-readable log of commits to this branch.
149
161
 
150
162
    This function is being retained for backwards compatibility but
154
166
 
155
167
    :param lf: The LogFormatter object showing the output.
156
168
 
 
169
    :param specific_fileid: If not None, list only the commits affecting the
 
170
        specified file, rather than all commits.
 
171
 
157
172
    :param verbose: If True show added/changed/deleted/renamed files.
158
173
 
159
174
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
170
185
        if None or 0.
171
186
 
172
187
    :param show_diff: If True, output a diff after each revision.
173
 
 
174
 
    :param match: Dictionary of search lists to use when matching revision
175
 
      properties.
176
188
    """
 
189
    # Convert old-style parameters to new-style parameters
 
190
    if specific_fileid is not None:
 
191
        file_ids = [specific_fileid]
 
192
    else:
 
193
        file_ids = None
177
194
    if verbose:
178
 
        delta_type = 'full'
 
195
        if file_ids:
 
196
            delta_type = 'partial'
 
197
        else:
 
198
            delta_type = 'full'
179
199
    else:
180
200
        delta_type = None
181
201
    if show_diff:
182
 
        diff_type = 'full'
 
202
        if file_ids:
 
203
            diff_type = 'partial'
 
204
        else:
 
205
            diff_type = 'full'
183
206
    else:
184
207
        diff_type = None
185
208
 
186
 
    if isinstance(start_revision, int):
187
 
        try:
188
 
            start_revision = revisionspec.RevisionInfo(branch, start_revision)
189
 
        except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
190
 
            raise errors.InvalidRevisionNumber(start_revision)
191
 
 
192
 
    if isinstance(end_revision, int):
193
 
        try:
194
 
            end_revision = revisionspec.RevisionInfo(branch, end_revision)
195
 
        except (errors.NoSuchRevision, errors.RevnoOutOfBounds):
196
 
            raise errors.InvalidRevisionNumber(end_revision)
197
 
 
198
 
    if end_revision is not None and end_revision.revno == 0:
199
 
        raise errors.InvalidRevisionNumber(end_revision.revno)
200
 
 
201
209
    # Build the request and execute it
202
 
    rqst = make_log_request_dict(
203
 
        direction=direction,
 
210
    rqst = make_log_request_dict(direction=direction, specific_fileids=file_ids,
204
211
        start_revision=start_revision, end_revision=end_revision,
205
212
        limit=limit, message_search=search,
206
213
        delta_type=delta_type, diff_type=diff_type)
207
214
    Logger(branch, rqst).show(lf)
208
215
 
209
216
 
210
 
# Note: This needs to be kept in sync with the defaults in
 
217
# Note: This needs to be kept this in sync with the defaults in
211
218
# make_log_request_dict() below
212
219
_DEFAULT_REQUEST_PARAMS = {
213
220
    'direction': 'reverse',
214
 
    'levels': None,
 
221
    'levels': 1,
215
222
    'generate_tags': True,
216
223
    'exclude_common_ancestry': False,
217
224
    '_match_using_deltas': True,
220
227
 
221
228
def make_log_request_dict(direction='reverse', specific_fileids=None,
222
229
                          start_revision=None, end_revision=None, limit=None,
223
 
                          message_search=None, levels=None, generate_tags=True,
 
230
                          message_search=None, levels=1, generate_tags=True,
224
231
                          delta_type=None,
225
232
                          diff_type=None, _match_using_deltas=True,
226
 
                          exclude_common_ancestry=False, match=None,
227
 
                          signature=False, omit_merges=False,
 
233
                          exclude_common_ancestry=False,
228
234
                          ):
229
235
    """Convenience function for making a logging request dictionary.
230
236
 
251
257
      matching commit messages
252
258
 
253
259
    :param levels: the number of levels of revisions to
254
 
      generate; 1 for just the mainline; 0 for all levels, or None for
255
 
      a sensible default.
 
260
      generate; 1 for just the mainline; 0 for all levels.
256
261
 
257
262
    :param generate_tags: If True, include tags for matched revisions.
258
 
`
 
263
 
259
264
    :param delta_type: Either 'full', 'partial' or None.
260
265
      'full' means generate the complete delta - adds/deletes/modifies/etc;
261
266
      'partial' means filter the delta using specific_fileids;
268
273
 
269
274
    :param _match_using_deltas: a private parameter controlling the
270
275
      algorithm used for matching specific_fileids. This parameter
271
 
      may be removed in the future so breezy client code should NOT
 
276
      may be removed in the future so bzrlib client code should NOT
272
277
      use it.
273
278
 
274
279
    :param exclude_common_ancestry: Whether -rX..Y should be interpreted as a
275
280
      range operator or as a graph difference.
276
 
 
277
 
    :param signature: show digital signature information
278
 
 
279
 
    :param match: Dictionary of list of search strings to use when filtering
280
 
      revisions. Keys can be 'message', 'author', 'committer', 'bugs' or
281
 
      the empty string to match any of the preceding properties.
282
 
 
283
 
    :param omit_merges: If True, commits with more than one parent are
284
 
      omitted.
285
 
 
286
281
    """
287
 
    # Take care of old style message_search parameter
288
 
    if message_search:
289
 
        if match:
290
 
            if 'message' in match:
291
 
                match['message'].append(message_search)
292
 
            else:
293
 
                match['message'] = [message_search]
294
 
        else:
295
 
            match = {'message': [message_search]}
296
282
    return {
297
283
        'direction': direction,
298
284
        'specific_fileids': specific_fileids,
299
285
        'start_revision': start_revision,
300
286
        'end_revision': end_revision,
301
287
        'limit': limit,
 
288
        'message_search': message_search,
302
289
        'levels': levels,
303
290
        'generate_tags': generate_tags,
304
291
        'delta_type': delta_type,
305
292
        'diff_type': diff_type,
306
293
        'exclude_common_ancestry': exclude_common_ancestry,
307
 
        'signature': signature,
308
 
        'match': match,
309
 
        'omit_merges': omit_merges,
310
294
        # Add 'private' attributes for features that may be deprecated
311
295
        '_match_using_deltas': _match_using_deltas,
312
296
    }
314
298
 
315
299
def _apply_log_request_defaults(rqst):
316
300
    """Apply default values to a request dictionary."""
317
 
    result = _DEFAULT_REQUEST_PARAMS.copy()
 
301
    result = _DEFAULT_REQUEST_PARAMS
318
302
    if rqst:
319
303
        result.update(rqst)
320
304
    return result
321
305
 
322
306
 
323
 
def format_signature_validity(rev_id, branch):
324
 
    """get the signature validity
325
 
 
326
 
    :param rev_id: revision id to validate
327
 
    :param branch: branch of revision
328
 
    :return: human readable string to print to log
329
 
    """
330
 
    from breezy import gpg
331
 
 
332
 
    gpg_strategy = gpg.GPGStrategy(branch.get_config_stack())
333
 
    result = branch.repository.verify_revision_signature(rev_id, gpg_strategy)
334
 
    if result[0] == gpg.SIGNATURE_VALID:
335
 
        return u"valid signature from {0}".format(result[1])
336
 
    if result[0] == gpg.SIGNATURE_KEY_MISSING:
337
 
        return "unknown key {0}".format(result[1])
338
 
    if result[0] == gpg.SIGNATURE_NOT_VALID:
339
 
        return "invalid signature!"
340
 
    if result[0] == gpg.SIGNATURE_NOT_SIGNED:
341
 
        return "no signature"
342
 
 
343
 
 
344
307
class LogGenerator(object):
345
308
    """A generator of log revisions."""
346
309
 
373
336
        if not isinstance(lf, LogFormatter):
374
337
            warn("not a LogFormatter instance: %r" % lf)
375
338
 
376
 
        with self.branch.lock_read():
 
339
        self.branch.lock_read()
 
340
        try:
377
341
            if getattr(lf, 'begin_log', None):
378
342
                lf.begin_log()
379
343
            self._show_body(lf)
380
344
            if getattr(lf, 'end_log', None):
381
345
                lf.end_log()
 
346
        finally:
 
347
            self.branch.unlock()
382
348
 
383
349
    def _show_body(self, lf):
384
350
        """Show the main log output.
388
354
        # Tweak the LogRequest based on what the LogFormatter can handle.
389
355
        # (There's no point generating stuff if the formatter can't display it.)
390
356
        rqst = self.rqst
391
 
        if rqst['levels'] is None or lf.get_levels() > rqst['levels']:
392
 
            # user didn't specify levels, use whatever the LF can handle:
393
 
            rqst['levels'] = lf.get_levels()
394
 
 
 
357
        rqst['levels'] = lf.get_levels()
395
358
        if not getattr(lf, 'supports_tags', False):
396
359
            rqst['generate_tags'] = False
397
360
        if not getattr(lf, 'supports_delta', False):
398
361
            rqst['delta_type'] = None
399
362
        if not getattr(lf, 'supports_diff', False):
400
363
            rqst['diff_type'] = None
401
 
        if not getattr(lf, 'supports_signatures', False):
402
 
            rqst['signature'] = False
403
364
 
404
365
        # Find and print the interesting revisions
405
366
        generator = self._generator_factory(self.branch, rqst)
406
 
        try:
407
 
            for lr in generator.iter_log_revisions():
408
 
                lf.log_revision(lr)
409
 
        except errors.GhostRevisionUnusableHere:
410
 
            raise errors.BzrCommandError(
411
 
                gettext('Further revision history missing.'))
 
367
        for lr in generator.iter_log_revisions():
 
368
            lf.log_revision(lr)
412
369
        lf.show_advice()
413
370
 
414
371
    def _generator_factory(self, branch, rqst):
415
372
        """Make the LogGenerator object to use.
416
 
 
 
373
        
417
374
        Subclasses may wish to override this.
418
375
        """
419
376
        return _DefaultLogGenerator(branch, rqst)
443
400
        levels = rqst.get('levels')
444
401
        limit = rqst.get('limit')
445
402
        diff_type = rqst.get('diff_type')
446
 
        show_signature = rqst.get('signature')
447
 
        omit_merges = rqst.get('omit_merges')
448
403
        log_count = 0
449
404
        revision_iterator = self._create_log_revision_iterator()
450
405
        for revs in revision_iterator:
451
406
            for (rev_id, revno, merge_depth), rev, delta in revs:
452
407
                # 0 levels means show everything; merge_depth counts from 0
453
 
                if (levels != 0 and merge_depth is not None and
454
 
                        merge_depth >= levels):
455
 
                    continue
456
 
                if omit_merges and len(rev.parent_ids) > 1:
457
 
                    continue
458
 
                if rev is None:
459
 
                    raise errors.GhostRevisionUnusableHere(rev_id)
 
408
                if levels != 0 and merge_depth >= levels:
 
409
                    continue
460
410
                if diff_type is None:
461
411
                    diff = None
462
412
                else:
463
413
                    diff = self._format_diff(rev, rev_id, diff_type)
464
 
                if show_signature:
465
 
                    signature = format_signature_validity(rev_id, self.branch)
466
 
                else:
467
 
                    signature = None
468
 
                yield LogRevision(
469
 
                    rev, revno, merge_depth, delta,
470
 
                    self.rev_tag_dict.get(rev_id), diff, signature)
 
414
                yield LogRevision(rev, revno, merge_depth, delta,
 
415
                    self.rev_tag_dict.get(rev_id), diff)
471
416
                if limit:
472
417
                    log_count += 1
473
418
                    if log_count >= limit:
486
431
            specific_files = [tree_2.id2path(id) for id in file_ids]
487
432
        else:
488
433
            specific_files = None
489
 
        s = BytesIO()
490
 
        path_encoding = get_diff_header_encoding()
 
434
        s = StringIO()
 
435
        path_encoding = osutils.get_diff_header_encoding()
491
436
        diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
492
 
                             new_label='', path_encoding=path_encoding)
 
437
            new_label='', path_encoding=path_encoding)
493
438
        return s.getvalue()
494
439
 
495
440
    def _create_log_revision_iterator(self):
509
454
            # not a directory
510
455
            file_count = len(self.rqst.get('specific_fileids'))
511
456
            if file_count != 1:
512
 
                raise errors.BzrError(
513
 
                    "illegal LogRequest: must match-using-deltas "
 
457
                raise BzrError("illegal LogRequest: must match-using-deltas "
514
458
                    "when logging %d files" % file_count)
515
459
            return self._log_revision_iterator_using_per_file_graph()
516
460
 
519
463
        rqst = self.rqst
520
464
        generate_merge_revisions = rqst.get('levels') != 1
521
465
        delayed_graph_generation = not rqst.get('specific_fileids') and (
522
 
            rqst.get('limit') or self.start_rev_id or self.end_rev_id)
 
466
                rqst.get('limit') or self.start_rev_id or self.end_rev_id)
523
467
        view_revisions = _calc_view_revisions(
524
468
            self.branch, self.start_rev_id, self.end_rev_id,
525
469
            rqst.get('direction'),
529
473
 
530
474
        # Apply the other filters
531
475
        return make_log_rev_iterator(self.branch, view_revisions,
532
 
                                     rqst.get('delta_type'), rqst.get('match'),
533
 
                                     file_ids=rqst.get('specific_fileids'),
534
 
                                     direction=rqst.get('direction'))
 
476
            rqst.get('delta_type'), rqst.get('message_search'),
 
477
            file_ids=rqst.get('specific_fileids'),
 
478
            direction=rqst.get('direction'))
535
479
 
536
480
    def _log_revision_iterator_using_per_file_graph(self):
537
481
        # Get the base revisions, filtering by the revision range.
545
489
        if not isinstance(view_revisions, list):
546
490
            view_revisions = list(view_revisions)
547
491
        view_revisions = _filter_revisions_touching_file_id(self.branch,
548
 
                                                            rqst.get('specific_fileids')[
549
 
                                                                0], view_revisions,
550
 
                                                            include_merges=rqst.get('levels') != 1)
 
492
            rqst.get('specific_fileids')[0], view_revisions,
 
493
            include_merges=rqst.get('levels') != 1)
551
494
        return make_log_rev_iterator(self.branch, view_revisions,
552
 
                                     rqst.get('delta_type'), rqst.get('match'))
 
495
            rqst.get('delta_type'), rqst.get('message_search'))
553
496
 
554
497
 
555
498
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
563
506
             a list of the same tuples.
564
507
    """
565
508
    if (exclude_common_ancestry and start_rev_id == end_rev_id):
566
 
        raise errors.BzrCommandError(gettext(
567
 
            '--exclude-common-ancestry requires two different revisions'))
 
509
        raise errors.BzrCommandError(
 
510
            '--exclude-common-ancestry requires two different revisions')
568
511
    if direction not in ('reverse', 'forward'):
569
 
        raise ValueError(gettext('invalid direction %r') % direction)
570
 
    br_rev_id = branch.last_revision()
571
 
    if br_rev_id == _mod_revision.NULL_REVISION:
 
512
        raise ValueError('invalid direction %r' % direction)
 
513
    br_revno, br_rev_id = branch.last_revision_info()
 
514
    if br_revno == 0:
572
515
        return []
573
516
 
574
517
    if (end_rev_id and start_rev_id == end_rev_id
575
518
        and (not generate_merge_revisions
576
519
             or not _has_merges(branch, end_rev_id))):
577
520
        # If a single revision is requested, check we can handle it
578
 
        return _generate_one_revision(branch, end_rev_id, br_rev_id,
579
 
                                      branch.revno())
580
 
    if not generate_merge_revisions:
581
 
        try:
582
 
            # If we only want to see linear revisions, we can iterate ...
583
 
            iter_revs = _linear_view_revisions(
584
 
                branch, start_rev_id, end_rev_id,
585
 
                exclude_common_ancestry=exclude_common_ancestry)
586
 
            # If a start limit was given and it's not obviously an
587
 
            # ancestor of the end limit, check it before outputting anything
588
 
            if (direction == 'forward'
589
 
                or (start_rev_id and not _is_obvious_ancestor(
590
 
                    branch, start_rev_id, end_rev_id))):
591
 
                iter_revs = list(iter_revs)
592
 
            if direction == 'forward':
593
 
                iter_revs = reversed(iter_revs)
594
 
            return iter_revs
595
 
        except _StartNotLinearAncestor:
596
 
            # Switch to the slower implementation that may be able to find a
597
 
            # non-obvious ancestor out of the left-hand history.
598
 
            pass
599
 
    iter_revs = _generate_all_revisions(branch, start_rev_id, end_rev_id,
600
 
                                        direction, delayed_graph_generation,
601
 
                                        exclude_common_ancestry)
602
 
    if direction == 'forward':
603
 
        iter_revs = _rebase_merge_depth(reverse_by_depth(list(iter_revs)))
 
521
        iter_revs = _generate_one_revision(branch, end_rev_id, br_rev_id,
 
522
                                           br_revno)
 
523
    elif not generate_merge_revisions:
 
524
        # If we only want to see linear revisions, we can iterate ...
 
525
        iter_revs = _generate_flat_revisions(branch, start_rev_id, end_rev_id,
 
526
                                             direction, exclude_common_ancestry)
 
527
        if direction == 'forward':
 
528
            iter_revs = reversed(iter_revs)
 
529
    else:
 
530
        iter_revs = _generate_all_revisions(branch, start_rev_id, end_rev_id,
 
531
                                            direction, delayed_graph_generation,
 
532
                                            exclude_common_ancestry)
 
533
        if direction == 'forward':
 
534
            iter_revs = _rebase_merge_depth(reverse_by_depth(list(iter_revs)))
604
535
    return iter_revs
605
536
 
606
537
 
609
540
        # It's the tip
610
541
        return [(br_rev_id, br_revno, 0)]
611
542
    else:
612
 
        revno_str = _compute_revno_str(branch, rev_id)
 
543
        revno = branch.revision_id_to_dotted_revno(rev_id)
 
544
        revno_str = '.'.join(str(n) for n in revno)
613
545
        return [(rev_id, revno_str, 0)]
614
546
 
615
547
 
 
548
def _generate_flat_revisions(branch, start_rev_id, end_rev_id, direction,
 
549
                             exclude_common_ancestry=False):
 
550
    result = _linear_view_revisions(
 
551
        branch, start_rev_id, end_rev_id,
 
552
        exclude_common_ancestry=exclude_common_ancestry)
 
553
    # If a start limit was given and it's not obviously an
 
554
    # ancestor of the end limit, check it before outputting anything
 
555
    if direction == 'forward' or (start_rev_id
 
556
        and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
 
557
        try:
 
558
            result = list(result)
 
559
        except _StartNotLinearAncestor:
 
560
            raise errors.BzrCommandError('Start revision not found in'
 
561
                ' left-hand history of end revision.')
 
562
    return result
 
563
 
 
564
 
616
565
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
617
566
                            delayed_graph_generation,
618
567
                            exclude_common_ancestry=False):
626
575
    initial_revisions = []
627
576
    if delayed_graph_generation:
628
577
        try:
629
 
            for rev_id, revno, depth in _linear_view_revisions(
630
 
                    branch, start_rev_id, end_rev_id, exclude_common_ancestry):
 
578
            for rev_id, revno, depth in  _linear_view_revisions(
 
579
                branch, start_rev_id, end_rev_id, exclude_common_ancestry):
631
580
                if _has_merges(branch, rev_id):
632
581
                    # The end_rev_id can be nested down somewhere. We need an
633
582
                    # explicit ancestry check. There is an ambiguity here as we
640
589
                    # -- vila 20100319
641
590
                    graph = branch.repository.get_graph()
642
591
                    if (start_rev_id is not None
643
 
                            and not graph.is_ancestor(start_rev_id, end_rev_id)):
 
592
                        and not graph.is_ancestor(start_rev_id, end_rev_id)):
644
593
                        raise _StartNotLinearAncestor()
645
594
                    # Since we collected the revisions so far, we need to
646
595
                    # adjust end_rev_id.
654
603
        except _StartNotLinearAncestor:
655
604
            # A merge was never detected so the lower revision limit can't
656
605
            # be nested down somewhere
657
 
            raise errors.BzrCommandError(gettext('Start revision not found in'
658
 
                                                 ' history of end revision.'))
 
606
            raise errors.BzrCommandError('Start revision not found in'
 
607
                ' history of end revision.')
659
608
 
660
609
    # We exit the loop above because we encounter a revision with merges, from
661
610
    # this revision, we need to switch to _graph_view_revisions.
665
614
    # shown naturally, i.e. just like it is for linear logging. We can easily
666
615
    # make forward the exact opposite display, but showing the merge revisions
667
616
    # indented at the end seems slightly nicer in that case.
668
 
    view_revisions = itertools.chain(iter(initial_revisions),
669
 
                                     _graph_view_revisions(branch, start_rev_id, end_rev_id,
670
 
                                                           rebase_initial_depths=(
671
 
                                                               direction == 'reverse'),
672
 
                                                           exclude_common_ancestry=exclude_common_ancestry))
 
617
    view_revisions = chain(iter(initial_revisions),
 
618
        _graph_view_revisions(branch, start_rev_id, end_rev_id,
 
619
                              rebase_initial_depths=(direction == 'reverse'),
 
620
                              exclude_common_ancestry=exclude_common_ancestry))
673
621
    return view_revisions
674
622
 
675
623
 
679
627
    return len(parents) > 1
680
628
 
681
629
 
682
 
def _compute_revno_str(branch, rev_id):
683
 
    """Compute the revno string from a rev_id.
684
 
 
685
 
    :return: The revno string, or None if the revision is not in the supplied
686
 
        branch.
687
 
    """
688
 
    try:
689
 
        revno = branch.revision_id_to_dotted_revno(rev_id)
690
 
    except errors.NoSuchRevision:
691
 
        # The revision must be outside of this branch
692
 
        return None
693
 
    else:
694
 
        return '.'.join(str(n) for n in revno)
695
 
 
696
 
 
697
630
def _is_obvious_ancestor(branch, start_rev_id, end_rev_id):
698
631
    """Is start_rev_id an obvious ancestor of end_rev_id?"""
699
632
    if start_rev_id and end_rev_id:
700
 
        try:
701
 
            start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
702
 
            end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
703
 
        except errors.NoSuchRevision:
704
 
            # one or both is not in the branch; not obvious
705
 
            return False
 
633
        start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
 
634
        end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
706
635
        if len(start_dotted) == 1 and len(end_dotted) == 1:
707
636
            # both on mainline
708
637
            return start_dotted[0] <= end_dotted[0]
709
638
        elif (len(start_dotted) == 3 and len(end_dotted) == 3 and
710
 
              start_dotted[0:1] == end_dotted[0:1]):
 
639
            start_dotted[0:1] == end_dotted[0:1]):
711
640
            # both on same development line
712
641
            return start_dotted[2] <= end_dotted[2]
713
642
        else:
727
656
    :param exclude_common_ancestry: Whether the start_rev_id should be part of
728
657
        the iterated revisions.
729
658
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
730
 
        dotted_revno will be None for ghosts
731
659
    :raises _StartNotLinearAncestor: if a start_rev_id is specified but
732
660
        is not found walking the left-hand history
733
661
    """
 
662
    br_revno, br_rev_id = branch.last_revision_info()
734
663
    repo = branch.repository
735
 
    graph = repo.get_graph()
736
664
    if start_rev_id is None and end_rev_id is None:
737
 
        if branch._format.stores_revno() or \
738
 
                config.GlobalStack().get('calculate_revnos'):
739
 
            try:
740
 
                br_revno, br_rev_id = branch.last_revision_info()
741
 
            except errors.GhostRevisionsHaveNoRevno:
742
 
                br_rev_id = branch.last_revision()
743
 
                cur_revno = None
744
 
            else:
745
 
                cur_revno = br_revno
746
 
        else:
747
 
            br_rev_id = branch.last_revision()
748
 
            cur_revno = None
749
 
 
750
 
        graph_iter = graph.iter_lefthand_ancestry(br_rev_id,
751
 
                                                  (_mod_revision.NULL_REVISION,))
752
 
        while True:
753
 
            try:
754
 
                revision_id = next(graph_iter)
755
 
            except errors.RevisionNotPresent as e:
756
 
                # Oops, a ghost.
757
 
                yield e.revision_id, None, None
758
 
                break
759
 
            except StopIteration:
760
 
                break
761
 
            else:
762
 
                yield revision_id, str(cur_revno) if cur_revno is not None else None, 0
763
 
                if cur_revno is not None:
764
 
                    cur_revno -= 1
 
665
        cur_revno = br_revno
 
666
        for revision_id in repo.iter_reverse_revision_history(br_rev_id):
 
667
            yield revision_id, str(cur_revno), 0
 
668
            cur_revno -= 1
765
669
    else:
766
 
        br_rev_id = branch.last_revision()
767
670
        if end_rev_id is None:
768
671
            end_rev_id = br_rev_id
769
672
        found_start = start_rev_id is None
770
 
        graph_iter = graph.iter_lefthand_ancestry(end_rev_id,
771
 
                                                  (_mod_revision.NULL_REVISION,))
772
 
        while True:
773
 
            try:
774
 
                revision_id = next(graph_iter)
775
 
            except StopIteration:
776
 
                break
777
 
            except errors.RevisionNotPresent as e:
778
 
                # Oops, a ghost.
779
 
                yield e.revision_id, None, None
780
 
                break
781
 
            else:
782
 
                revno_str = _compute_revno_str(branch, revision_id)
783
 
                if not found_start and revision_id == start_rev_id:
784
 
                    if not exclude_common_ancestry:
785
 
                        yield revision_id, revno_str, 0
786
 
                    found_start = True
787
 
                    break
788
 
                else:
 
673
        for revision_id in repo.iter_reverse_revision_history(end_rev_id):
 
674
            revno = branch.revision_id_to_dotted_revno(revision_id)
 
675
            revno_str = '.'.join(str(n) for n in revno)
 
676
            if not found_start and revision_id == start_rev_id:
 
677
                if not exclude_common_ancestry:
789
678
                    yield revision_id, revno_str, 0
790
 
        if not found_start:
791
 
            raise _StartNotLinearAncestor()
 
679
                found_start = True
 
680
                break
 
681
            else:
 
682
                yield revision_id, revno_str, 0
 
683
        else:
 
684
            if not found_start:
 
685
                raise _StartNotLinearAncestor()
792
686
 
793
687
 
794
688
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
835
729
            yield rev_id, '.'.join(map(str, revno)), merge_depth
836
730
 
837
731
 
 
732
@deprecated_function(deprecated_in((2, 2, 0)))
 
733
def calculate_view_revisions(branch, start_revision, end_revision, direction,
 
734
        specific_fileid, generate_merge_revisions):
 
735
    """Calculate the revisions to view.
 
736
 
 
737
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
 
738
             a list of the same tuples.
 
739
    """
 
740
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
 
741
        end_revision)
 
742
    view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
 
743
        direction, generate_merge_revisions or specific_fileid))
 
744
    if specific_fileid:
 
745
        view_revisions = _filter_revisions_touching_file_id(branch,
 
746
            specific_fileid, view_revisions,
 
747
            include_merges=generate_merge_revisions)
 
748
    return _rebase_merge_depth(view_revisions)
 
749
 
 
750
 
838
751
def _rebase_merge_depth(view_revisions):
839
752
    """Adjust depths upwards so the top level is 0."""
840
753
    # If either the first or last revision have a merge_depth of 0, we're done
841
754
    if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
842
 
        min_depth = min([d for r, n, d in view_revisions])
 
755
        min_depth = min([d for r,n,d in view_revisions])
843
756
        if min_depth != 0:
844
 
            view_revisions = [(r, n, d - min_depth)
845
 
                              for r, n, d in view_revisions]
 
757
            view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
846
758
    return view_revisions
847
759
 
848
760
 
849
761
def make_log_rev_iterator(branch, view_revisions, generate_delta, search,
850
 
                          file_ids=None, direction='reverse'):
 
762
        file_ids=None, direction='reverse'):
851
763
    """Create a revision iterator for log.
852
764
 
853
765
    :param branch: The branch being logged.
863
775
    """
864
776
    # Convert view_revisions into (view, None, None) groups to fit with
865
777
    # the standard interface here.
866
 
    if isinstance(view_revisions, list):
 
778
    if type(view_revisions) == list:
867
779
        # A single batch conversion is faster than many incremental ones.
868
780
        # As we have all the data, do a batch conversion.
869
781
        nones = [None] * len(view_revisions)
870
 
        log_rev_iterator = iter([list(zip(view_revisions, nones, nones))])
 
782
        log_rev_iterator = iter([zip(view_revisions, nones, nones)])
871
783
    else:
872
784
        def _convert():
873
785
            for view in view_revisions:
877
789
        # It would be nicer if log adapters were first class objects
878
790
        # with custom parameters. This will do for now. IGC 20090127
879
791
        if adapter == _make_delta_filter:
880
 
            log_rev_iterator = adapter(
881
 
                branch, generate_delta, search, log_rev_iterator, file_ids,
882
 
                direction)
 
792
            log_rev_iterator = adapter(branch, generate_delta,
 
793
                search, log_rev_iterator, file_ids, direction)
883
794
        else:
884
 
            log_rev_iterator = adapter(
885
 
                branch, generate_delta, search, log_rev_iterator)
 
795
            log_rev_iterator = adapter(branch, generate_delta,
 
796
                search, log_rev_iterator)
886
797
    return log_rev_iterator
887
798
 
888
799
 
889
 
def _make_search_filter(branch, generate_delta, match, log_rev_iterator):
 
800
def _make_search_filter(branch, generate_delta, search, log_rev_iterator):
890
801
    """Create a filtered iterator of log_rev_iterator matching on a regex.
891
802
 
892
803
    :param branch: The branch being logged.
893
804
    :param generate_delta: Whether to generate a delta for each revision.
894
 
    :param match: A dictionary with properties as keys and lists of strings
895
 
        as values. To match, a revision may match any of the supplied strings
896
 
        within a single property but must match at least one string for each
897
 
        property.
 
805
    :param search: A user text search string.
898
806
    :param log_rev_iterator: An input iterator containing all revisions that
899
807
        could be displayed, in lists.
900
808
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
901
809
        delta).
902
810
    """
903
 
    if not match:
 
811
    if search is None:
904
812
        return log_rev_iterator
905
 
    # Use lazy_compile so mapping to InvalidPattern error occurs.
906
 
    searchRE = [(k, [lazy_regex.lazy_compile(x, re.IGNORECASE) for x in v])
907
 
                for k, v in match.items()]
908
 
    return _filter_re(searchRE, log_rev_iterator)
909
 
 
910
 
 
911
 
def _filter_re(searchRE, log_rev_iterator):
 
813
    searchRE = re.compile(search, re.IGNORECASE)
 
814
    return _filter_message_re(searchRE, log_rev_iterator)
 
815
 
 
816
 
 
817
def _filter_message_re(searchRE, log_rev_iterator):
912
818
    for revs in log_rev_iterator:
913
 
        new_revs = [rev for rev in revs if _match_filter(searchRE, rev[1])]
914
 
        if new_revs:
915
 
            yield new_revs
916
 
 
917
 
 
918
 
def _match_filter(searchRE, rev):
919
 
    strings = {
920
 
        'message': (rev.message,),
921
 
        'committer': (rev.committer,),
922
 
        'author': (rev.get_apparent_authors()),
923
 
        'bugs': list(rev.iter_bugs())
924
 
        }
925
 
    strings[''] = [item for inner_list in strings.values()
926
 
                   for item in inner_list]
927
 
    for k, v in searchRE:
928
 
        if k in strings and not _match_any_filter(strings[k], v):
929
 
            return False
930
 
    return True
931
 
 
932
 
 
933
 
def _match_any_filter(strings, res):
934
 
    return any(r.search(s) for r in res for s in strings)
 
819
        new_revs = []
 
820
        for (rev_id, revno, merge_depth), rev, delta in revs:
 
821
            if searchRE.search(rev.message):
 
822
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
 
823
        yield new_revs
935
824
 
936
825
 
937
826
def _make_delta_filter(branch, generate_delta, search, log_rev_iterator,
938
 
                       fileids=None, direction='reverse'):
 
827
    fileids=None, direction='reverse'):
939
828
    """Add revision deltas to a log iterator if needed.
940
829
 
941
830
    :param branch: The branch being logged.
953
842
    if not generate_delta and not fileids:
954
843
        return log_rev_iterator
955
844
    return _generate_deltas(branch.repository, log_rev_iterator,
956
 
                            generate_delta, fileids, direction)
 
845
        generate_delta, fileids, direction)
957
846
 
958
847
 
959
848
def _generate_deltas(repository, log_rev_iterator, delta_type, fileids,
960
 
                     direction):
 
849
    direction):
961
850
    """Create deltas for each batch of revisions in log_rev_iterator.
962
851
 
963
852
    If we're only generating deltas for the sake of filtering against
983
872
        new_revs = []
984
873
        if delta_type == 'full' and not check_fileids:
985
874
            deltas = repository.get_deltas_for_revisions(revisions)
986
 
            for rev, delta in zip(revs, deltas):
 
875
            for rev, delta in izip(revs, deltas):
987
876
                new_revs.append((rev[0], rev[1], delta))
988
877
        else:
989
878
            deltas = repository.get_deltas_for_revisions(revisions, fileid_set)
990
 
            for rev, delta in zip(revs, deltas):
 
879
            for rev, delta in izip(revs, deltas):
991
880
                if check_fileids:
992
881
                    if delta is None or not delta.has_changed():
993
882
                        continue
1011
900
 
1012
901
def _update_fileids(delta, fileids, stop_on):
1013
902
    """Update the set of file-ids to search based on file lifecycle events.
1014
 
 
 
903
    
1015
904
    :param fileids: a set of fileids to update
1016
905
    :param stop_on: either 'add' or 'remove' - take file-ids out of the
1017
906
      fileids set once their add or remove entry is detected respectively
1018
907
    """
1019
908
    if stop_on == 'add':
1020
 
        for item in delta.added + delta.copied:
1021
 
            if item.file_id in fileids:
1022
 
                fileids.remove(item.file_id)
 
909
        for item in delta.added:
 
910
            if item[1] in fileids:
 
911
                fileids.remove(item[1])
1023
912
    elif stop_on == 'delete':
1024
913
        for item in delta.removed:
1025
 
            if item.file_id in fileids:
1026
 
                fileids.remove(item.file_id)
 
914
            if item[1] in fileids:
 
915
                fileids.remove(item[1])
1027
916
 
1028
917
 
1029
918
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
1041
930
    for revs in log_rev_iterator:
1042
931
        # r = revision_id, n = revno, d = merge depth
1043
932
        revision_ids = [view[0] for view, _, _ in revs]
1044
 
        revisions = dict(repository.iter_revisions(revision_ids))
1045
 
        yield [(rev[0], revisions[rev[0][0]], rev[2]) for rev in revs]
 
933
        revisions = repository.get_revisions(revision_ids)
 
934
        revs = [(rev[0], revision, rev[2]) for rev, revision in
 
935
            izip(revs, revisions)]
 
936
        yield revs
1046
937
 
1047
938
 
1048
939
def _make_batch_filter(branch, generate_delta, search, log_rev_iterator):
1056
947
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
1057
948
        delta).
1058
949
    """
 
950
    repository = branch.repository
1059
951
    num = 9
1060
952
    for batch in log_rev_iterator:
1061
953
        batch = iter(batch)
1073
965
    :param  branch: The branch containing the revisions.
1074
966
 
1075
967
    :param  start_revision: The first revision to be logged.
 
968
            For backwards compatibility this may be a mainline integer revno,
1076
969
            but for merge revision support a RevisionInfo is expected.
1077
970
 
1078
971
    :param  end_revision: The last revision to be logged.
1081
974
 
1082
975
    :return: (start_rev_id, end_rev_id) tuple.
1083
976
    """
 
977
    branch_revno, branch_rev_id = branch.last_revision_info()
1084
978
    start_rev_id = None
1085
 
    start_revno = None
1086
 
    if start_revision is not None:
1087
 
        if not isinstance(start_revision, revisionspec.RevisionInfo):
1088
 
            raise TypeError(start_revision)
1089
 
        start_rev_id = start_revision.rev_id
1090
 
        start_revno = start_revision.revno
1091
 
    if start_revno is None:
 
979
    if start_revision is None:
1092
980
        start_revno = 1
 
981
    else:
 
982
        if isinstance(start_revision, revisionspec.RevisionInfo):
 
983
            start_rev_id = start_revision.rev_id
 
984
            start_revno = start_revision.revno or 1
 
985
        else:
 
986
            branch.check_real_revno(start_revision)
 
987
            start_revno = start_revision
 
988
            start_rev_id = branch.get_rev_id(start_revno)
1093
989
 
1094
990
    end_rev_id = None
1095
 
    end_revno = None
1096
 
    if end_revision is not None:
1097
 
        if not isinstance(end_revision, revisionspec.RevisionInfo):
1098
 
            raise TypeError(start_revision)
1099
 
        end_rev_id = end_revision.rev_id
1100
 
        end_revno = end_revision.revno
 
991
    if end_revision is None:
 
992
        end_revno = branch_revno
 
993
    else:
 
994
        if isinstance(end_revision, revisionspec.RevisionInfo):
 
995
            end_rev_id = end_revision.rev_id
 
996
            end_revno = end_revision.revno or branch_revno
 
997
        else:
 
998
            branch.check_real_revno(end_revision)
 
999
            end_revno = end_revision
 
1000
            end_rev_id = branch.get_rev_id(end_revno)
1101
1001
 
1102
 
    if branch.last_revision() != _mod_revision.NULL_REVISION:
 
1002
    if branch_revno != 0:
1103
1003
        if (start_rev_id == _mod_revision.NULL_REVISION
1104
 
                or end_rev_id == _mod_revision.NULL_REVISION):
1105
 
            raise errors.BzrCommandError(
1106
 
                gettext('Logging revision 0 is invalid.'))
1107
 
        if end_revno is not None and start_revno > end_revno:
1108
 
            raise errors.BzrCommandError(
1109
 
                gettext("Start revision must be older than the end revision."))
 
1004
            or end_rev_id == _mod_revision.NULL_REVISION):
 
1005
            raise errors.BzrCommandError('Logging revision 0 is invalid.')
 
1006
        if start_revno > end_revno:
 
1007
            raise errors.BzrCommandError("Start revision must be older than "
 
1008
                                         "the end revision.")
1110
1009
    return (start_rev_id, end_rev_id)
1111
1010
 
1112
1011
 
1160
1059
            end_revno = end_revision
1161
1060
 
1162
1061
    if ((start_rev_id == _mod_revision.NULL_REVISION)
1163
 
            or (end_rev_id == _mod_revision.NULL_REVISION)):
1164
 
        raise errors.BzrCommandError(gettext('Logging revision 0 is invalid.'))
 
1062
        or (end_rev_id == _mod_revision.NULL_REVISION)):
 
1063
        raise errors.BzrCommandError('Logging revision 0 is invalid.')
1165
1064
    if start_revno > end_revno:
1166
 
        raise errors.BzrCommandError(gettext("Start revision must be older "
1167
 
                                             "than the end revision."))
 
1065
        raise errors.BzrCommandError("Start revision must be older than "
 
1066
                                     "the end revision.")
1168
1067
 
1169
1068
    if end_revno < start_revno:
1170
1069
        return None, None, None, None
1171
1070
    cur_revno = branch_revno
1172
1071
    rev_nos = {}
1173
1072
    mainline_revs = []
1174
 
    graph = branch.repository.get_graph()
1175
 
    for revision_id in graph.iter_lefthand_ancestry(
1176
 
            branch_last_revision, (_mod_revision.NULL_REVISION,)):
 
1073
    for revision_id in branch.repository.iter_reverse_revision_history(
 
1074
                        branch_last_revision):
1177
1075
        if cur_revno < start_revno:
1178
1076
            # We have gone far enough, but we always add 1 more revision
1179
1077
            rev_nos[revision_id] = cur_revno
1193
1091
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
1194
1092
 
1195
1093
 
 
1094
@deprecated_function(deprecated_in((2, 2, 0)))
 
1095
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
 
1096
    """Filter view_revisions based on revision ranges.
 
1097
 
 
1098
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
 
1099
            tuples to be filtered.
 
1100
 
 
1101
    :param start_rev_id: If not NONE specifies the first revision to be logged.
 
1102
            If NONE then all revisions up to the end_rev_id are logged.
 
1103
 
 
1104
    :param end_rev_id: If not NONE specifies the last revision to be logged.
 
1105
            If NONE then all revisions up to the end of the log are logged.
 
1106
 
 
1107
    :return: The filtered view_revisions.
 
1108
    """
 
1109
    if start_rev_id or end_rev_id:
 
1110
        revision_ids = [r for r, n, d in view_revisions]
 
1111
        if start_rev_id:
 
1112
            start_index = revision_ids.index(start_rev_id)
 
1113
        else:
 
1114
            start_index = 0
 
1115
        if start_rev_id == end_rev_id:
 
1116
            end_index = start_index
 
1117
        else:
 
1118
            if end_rev_id:
 
1119
                end_index = revision_ids.index(end_rev_id)
 
1120
            else:
 
1121
                end_index = len(view_revisions) - 1
 
1122
        # To include the revisions merged into the last revision,
 
1123
        # extend end_rev_id down to, but not including, the next rev
 
1124
        # with the same or lesser merge_depth
 
1125
        end_merge_depth = view_revisions[end_index][2]
 
1126
        try:
 
1127
            for index in xrange(end_index+1, len(view_revisions)+1):
 
1128
                if view_revisions[index][2] <= end_merge_depth:
 
1129
                    end_index = index - 1
 
1130
                    break
 
1131
        except IndexError:
 
1132
            # if the search falls off the end then log to the end as well
 
1133
            end_index = len(view_revisions) - 1
 
1134
        view_revisions = view_revisions[start_index:end_index+1]
 
1135
    return view_revisions
 
1136
 
 
1137
 
1196
1138
def _filter_revisions_touching_file_id(branch, file_id, view_revisions,
1197
 
                                       include_merges=True):
 
1139
    include_merges=True):
1198
1140
    r"""Return the list of revision ids which touch a given file id.
1199
1141
 
1200
1142
    The function filters view_revisions and returns a subset.
1201
1143
    This includes the revisions which directly change the file id,
1202
1144
    and the revisions which merge these changes. So if the
1203
1145
    revision graph is::
1204
 
 
1205
1146
        A-.
1206
1147
        |\ \
1207
1148
        B C E
1234
1175
    """
1235
1176
    # Lookup all possible text keys to determine which ones actually modified
1236
1177
    # the file.
1237
 
    graph = branch.repository.get_file_graph()
1238
 
    get_parent_map = graph.get_parent_map
1239
1178
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
1240
1179
    next_keys = None
1241
1180
    # Looking up keys in batches of 1000 can cut the time in half, as well as
1245
1184
    #       indexing layer. We might consider passing in hints as to the known
1246
1185
    #       access pattern (sparse/clustered, high success rate/low success
1247
1186
    #       rate). This particular access is clustered with a low success rate.
 
1187
    get_parent_map = branch.repository.texts.get_parent_map
1248
1188
    modified_text_revisions = set()
1249
1189
    chunk_size = 1000
1250
 
    for start in range(0, len(text_keys), chunk_size):
 
1190
    for start in xrange(0, len(text_keys), chunk_size):
1251
1191
        next_keys = text_keys[start:start + chunk_size]
1252
1192
        # Only keep the revision_id portion of the key
1253
1193
        modified_text_revisions.update(
1268
1208
 
1269
1209
        if rev_id in modified_text_revisions:
1270
1210
            # This needs to be logged, along with the extra revisions
1271
 
            for idx in range(len(current_merge_stack)):
 
1211
            for idx in xrange(len(current_merge_stack)):
1272
1212
                node = current_merge_stack[idx]
1273
1213
                if node is not None:
1274
1214
                    if include_merges or node[2] == 0:
1277
1217
    return result
1278
1218
 
1279
1219
 
 
1220
@deprecated_function(deprecated_in((2, 2, 0)))
 
1221
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
 
1222
                       include_merges=True):
 
1223
    """Produce an iterator of revisions to show
 
1224
    :return: an iterator of (revision_id, revno, merge_depth)
 
1225
    (if there is no revno for a revision, None is supplied)
 
1226
    """
 
1227
    if not include_merges:
 
1228
        revision_ids = mainline_revs[1:]
 
1229
        if direction == 'reverse':
 
1230
            revision_ids.reverse()
 
1231
        for revision_id in revision_ids:
 
1232
            yield revision_id, str(rev_nos[revision_id]), 0
 
1233
        return
 
1234
    graph = branch.repository.get_graph()
 
1235
    # This asks for all mainline revisions, which means we only have to spider
 
1236
    # sideways, rather than depth history. That said, its still size-of-history
 
1237
    # and should be addressed.
 
1238
    # mainline_revisions always includes an extra revision at the beginning, so
 
1239
    # don't request it.
 
1240
    parent_map = dict(((key, value) for key, value in
 
1241
        graph.iter_ancestry(mainline_revs[1:]) if value is not None))
 
1242
    # filter out ghosts; merge_sort errors on ghosts.
 
1243
    rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
 
1244
    merge_sorted_revisions = tsort.merge_sort(
 
1245
        rev_graph,
 
1246
        mainline_revs[-1],
 
1247
        mainline_revs,
 
1248
        generate_revno=True)
 
1249
 
 
1250
    if direction == 'forward':
 
1251
        # forward means oldest first.
 
1252
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
 
1253
    elif direction != 'reverse':
 
1254
        raise ValueError('invalid direction %r' % direction)
 
1255
 
 
1256
    for (sequence, rev_id, merge_depth, revno, end_of_merge
 
1257
         ) in merge_sorted_revisions:
 
1258
        yield rev_id, '.'.join(map(str, revno)), merge_depth
 
1259
 
 
1260
 
1280
1261
def reverse_by_depth(merge_sorted_revisions, _depth=0):
1281
1262
    """Reverse revisions by depth.
1282
1263
 
1283
1264
    Revisions with a different depth are sorted as a group with the previous
1284
 
    revision of that depth.  There may be no topological justification for this
 
1265
    revision of that depth.  There may be no topological justification for this,
1285
1266
    but it looks much nicer.
1286
1267
    """
1287
1268
    # Add a fake revision at start so that we can always attach sub revisions
1317
1298
    """
1318
1299
 
1319
1300
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
1320
 
                 tags=None, diff=None, signature=None):
 
1301
                 tags=None, diff=None):
1321
1302
        self.rev = rev
1322
 
        if revno is None:
1323
 
            self.revno = None
1324
 
        else:
1325
 
            self.revno = str(revno)
 
1303
        self.revno = str(revno)
1326
1304
        self.merge_depth = merge_depth
1327
1305
        self.delta = delta
1328
1306
        self.tags = tags
1329
1307
        self.diff = diff
1330
 
        self.signature = signature
1331
1308
 
1332
1309
 
1333
1310
class LogFormatter(object):
1342
1319
    to indicate which LogRevision attributes it supports:
1343
1320
 
1344
1321
    - supports_delta must be True if this log formatter supports delta.
1345
 
      Otherwise the delta attribute may not be populated.  The 'delta_format'
1346
 
      attribute describes whether the 'short_status' format (1) or the long
1347
 
      one (2) should be used.
 
1322
        Otherwise the delta attribute may not be populated.  The 'delta_format'
 
1323
        attribute describes whether the 'short_status' format (1) or the long
 
1324
        one (2) should be used.
1348
1325
 
1349
1326
    - supports_merge_revisions must be True if this log formatter supports
1350
 
      merge revisions.  If not, then only mainline revisions will be passed
1351
 
      to the formatter.
 
1327
        merge revisions.  If not, then only mainline revisions will be passed
 
1328
        to the formatter.
1352
1329
 
1353
1330
    - preferred_levels is the number of levels this formatter defaults to.
1354
 
      The default value is zero meaning display all levels.
1355
 
      This value is only relevant if supports_merge_revisions is True.
 
1331
        The default value is zero meaning display all levels.
 
1332
        This value is only relevant if supports_merge_revisions is True.
1356
1333
 
1357
1334
    - supports_tags must be True if this log formatter supports tags.
1358
 
      Otherwise the tags attribute may not be populated.
 
1335
        Otherwise the tags attribute may not be populated.
1359
1336
 
1360
1337
    - supports_diff must be True if this log formatter supports diffs.
1361
 
      Otherwise the diff attribute may not be populated.
1362
 
 
1363
 
    - supports_signatures must be True if this log formatter supports GPG
1364
 
      signatures.
 
1338
        Otherwise the diff attribute may not be populated.
1365
1339
 
1366
1340
    Plugins can register functions to show custom revision properties using
1367
1341
    the properties_handler_registry. The registered function
1368
 
    must respect the following interface description::
1369
 
 
 
1342
    must respect the following interface description:
1370
1343
        def my_show_properties(properties_dict):
1371
1344
            # code that returns a dict {'name':'value'} of the properties
1372
1345
            # to be shown
1379
1352
        """Create a LogFormatter.
1380
1353
 
1381
1354
        :param to_file: the file to output to
1382
 
        :param to_exact_file: if set, gives an output stream to which
 
1355
        :param to_exact_file: if set, gives an output stream to which 
1383
1356
             non-Unicode diffs are written.
1384
1357
        :param show_ids: if True, revision-ids are to be displayed
1385
1358
        :param show_timezone: the timezone to use
1394
1367
        """
1395
1368
        self.to_file = to_file
1396
1369
        # 'exact' stream used to show diff, it should print content 'as is'
1397
 
        # and should not try to decode/encode it to unicode to avoid bug
1398
 
        # #328007
 
1370
        # and should not try to decode/encode it to unicode to avoid bug #328007
1399
1371
        if to_exact_file is not None:
1400
1372
            self.to_exact_file = to_exact_file
1401
1373
        else:
1402
 
            # XXX: somewhat hacky; this assumes it's a codec writer; it's
1403
 
            # better for code that expects to get diffs to pass in the exact
1404
 
            # file stream
 
1374
            # XXX: somewhat hacky; this assumes it's a codec writer; it's better
 
1375
            # for code that expects to get diffs to pass in the exact file
 
1376
            # stream
1405
1377
            self.to_exact_file = getattr(to_file, 'stream', to_file)
1406
1378
        self.show_ids = show_ids
1407
1379
        self.show_timezone = show_timezone
1408
1380
        if delta_format is None:
1409
1381
            # Ensures backward compatibility
1410
 
            delta_format = 2  # long format
 
1382
            delta_format = 2 # long format
1411
1383
        self.delta_format = delta_format
1412
1384
        self.levels = levels
1413
1385
        self._show_advice = show_advice
1437
1409
            if advice_sep:
1438
1410
                self.to_file.write(advice_sep)
1439
1411
            self.to_file.write(
1440
 
                "Use --include-merged or -n0 to see merged revisions.\n")
 
1412
                "Use --include-merges or -n0 to see merged revisions.\n")
1441
1413
 
1442
1414
    def get_advice_separator(self):
1443
1415
        """Get the text separating the log from the closing advice."""
1511
1483
        """
1512
1484
        lines = self._foreign_info_properties(revision)
1513
1485
        for key, handler in properties_handler_registry.iteritems():
1514
 
            try:
1515
 
                lines.extend(self._format_properties(handler(revision)))
1516
 
            except Exception:
1517
 
                trace.log_exception_quietly()
1518
 
                trace.print_exception(sys.exc_info(), self.to_file)
 
1486
            lines.extend(self._format_properties(handler(revision)))
1519
1487
        return lines
1520
1488
 
1521
1489
    def _foreign_info_properties(self, rev):
1529
1497
                rev.mapping.vcs.show_foreign_revid(rev.foreign_revid))
1530
1498
 
1531
1499
        # Imported foreign revision revision ids always contain :
1532
 
        if b":" not in rev.revision_id:
 
1500
        if not ":" in rev.revision_id:
1533
1501
            return []
1534
1502
 
1535
1503
        # Revision was once imported from a foreign repository
1549
1517
        return lines
1550
1518
 
1551
1519
    def show_diff(self, to_file, diff, indent):
1552
 
        encoding = get_terminal_encoding()
1553
 
        for l in diff.rstrip().split(b'\n'):
1554
 
            to_file.write(indent + l.decode(encoding, 'ignore') + '\n')
 
1520
        for l in diff.rstrip().split('\n'):
 
1521
            to_file.write(indent + '%s\n' % (l,))
1555
1522
 
1556
1523
 
1557
1524
# Separator between revisions in long format
1565
1532
    supports_delta = True
1566
1533
    supports_tags = True
1567
1534
    supports_diff = True
1568
 
    supports_signatures = True
1569
1535
 
1570
1536
    def __init__(self, *args, **kwargs):
1571
1537
        super(LongLogFormatter, self).__init__(*args, **kwargs)
1580
1546
 
1581
1547
    def _date_string_original_timezone(self, rev):
1582
1548
        return format_date_with_offset_in_original_timezone(rev.timestamp,
1583
 
                                                            rev.timezone or 0)
 
1549
            rev.timezone or 0)
1584
1550
 
1585
1551
    def log_revision(self, revision):
1586
1552
        """Log a revision, either merged or not."""
1588
1554
        lines = [_LONG_SEP]
1589
1555
        if revision.revno is not None:
1590
1556
            lines.append('revno: %s%s' % (revision.revno,
1591
 
                                          self.merge_marker(revision)))
 
1557
                self.merge_marker(revision)))
1592
1558
        if revision.tags:
1593
 
            lines.append('tags: %s' % (', '.join(sorted(revision.tags))))
1594
 
        if self.show_ids or revision.revno is None:
1595
 
            lines.append('revision-id: %s' %
1596
 
                         (revision.rev.revision_id.decode('utf-8'),))
 
1559
            lines.append('tags: %s' % (', '.join(revision.tags)))
1597
1560
        if self.show_ids:
 
1561
            lines.append('revision-id: %s' % (revision.rev.revision_id,))
1598
1562
            for parent_id in revision.rev.parent_ids:
1599
 
                lines.append('parent: %s' % (parent_id.decode('utf-8'),))
 
1563
                lines.append('parent: %s' % (parent_id,))
1600
1564
        lines.extend(self.custom_properties(revision.rev))
1601
1565
 
1602
1566
        committer = revision.rev.committer
1611
1575
 
1612
1576
        lines.append('timestamp: %s' % (self.date_string(revision.rev),))
1613
1577
 
1614
 
        if revision.signature is not None:
1615
 
            lines.append('signature: ' + revision.signature)
1616
 
 
1617
1578
        lines.append('message:')
1618
1579
        if not revision.rev.message:
1619
1580
            lines.append('  (no message)')
1627
1588
        to_file.write("%s%s\n" % (indent, ('\n' + indent).join(lines)))
1628
1589
        if revision.delta is not None:
1629
1590
            # Use the standard status output to display changes
1630
 
            from breezy.delta import report_delta
1631
 
            report_delta(to_file, revision.delta, short_status=False,
 
1591
            from bzrlib.delta import report_delta
 
1592
            report_delta(to_file, revision.delta, short_status=False, 
1632
1593
                         show_ids=self.show_ids, indent=indent)
1633
1594
        if revision.diff is not None:
1634
1595
            to_file.write(indent + 'diff:\n')
1666
1627
        indent = '    ' * depth
1667
1628
        revno_width = self.revno_width_by_depth.get(depth)
1668
1629
        if revno_width is None:
1669
 
            if revision.revno is None or revision.revno.find('.') == -1:
 
1630
            if revision.revno.find('.') == -1:
1670
1631
                # mainline revno, e.g. 12345
1671
1632
                revno_width = 5
1672
1633
            else:
1678
1639
        to_file = self.to_file
1679
1640
        tags = ''
1680
1641
        if revision.tags:
1681
 
            tags = ' {%s}' % (', '.join(sorted(revision.tags)))
 
1642
            tags = ' {%s}' % (', '.join(revision.tags))
1682
1643
        to_file.write(indent + "%*s %s\t%s%s%s\n" % (revno_width,
1683
 
                                                     revision.revno or "", self.short_author(
1684
 
                                                         revision.rev),
1685
 
                                                     format_date(revision.rev.timestamp,
1686
 
                                                                 revision.rev.timezone or 0,
1687
 
                                                                 self.show_timezone, date_fmt="%Y-%m-%d",
1688
 
                                                                 show_offset=False),
1689
 
                                                     tags, self.merge_marker(revision)))
1690
 
        self.show_properties(revision.rev, indent + offset)
1691
 
        if self.show_ids or revision.revno is None:
 
1644
                revision.revno, self.short_author(revision.rev),
 
1645
                format_date(revision.rev.timestamp,
 
1646
                            revision.rev.timezone or 0,
 
1647
                            self.show_timezone, date_fmt="%Y-%m-%d",
 
1648
                            show_offset=False),
 
1649
                tags, self.merge_marker(revision)))
 
1650
        self.show_properties(revision.rev, indent+offset)
 
1651
        if self.show_ids:
1692
1652
            to_file.write(indent + offset + 'revision-id:%s\n'
1693
 
                          % (revision.rev.revision_id.decode('utf-8'),))
 
1653
                          % (revision.rev.revision_id,))
1694
1654
        if not revision.rev.message:
1695
1655
            to_file.write(indent + offset + '(no message)\n')
1696
1656
        else:
1700
1660
 
1701
1661
        if revision.delta is not None:
1702
1662
            # Use the standard status output to display changes
1703
 
            from breezy.delta import report_delta
1704
 
            report_delta(to_file, revision.delta,
1705
 
                         short_status=self.delta_format == 1,
 
1663
            from bzrlib.delta import report_delta
 
1664
            report_delta(to_file, revision.delta, 
 
1665
                         short_status=self.delta_format==1, 
1706
1666
                         show_ids=self.show_ids, indent=indent + offset)
1707
1667
        if revision.diff is not None:
1708
1668
            self.show_diff(self.to_exact_file, revision.diff, '      ')
1726
1686
    def truncate(self, str, max_len):
1727
1687
        if max_len is None or len(str) <= max_len:
1728
1688
            return str
1729
 
        return str[:max_len - 3] + '...'
 
1689
        return str[:max_len-3] + '...'
1730
1690
 
1731
1691
    def date_string(self, rev):
1732
1692
        return format_date(rev.timestamp, rev.timezone or 0,
1742
1702
    def log_revision(self, revision):
1743
1703
        indent = '  ' * revision.merge_depth
1744
1704
        self.to_file.write(self.log_string(revision.revno, revision.rev,
1745
 
                                           self._max_chars, revision.tags, indent))
 
1705
            self._max_chars, revision.tags, indent))
1746
1706
        self.to_file.write('\n')
1747
1707
 
1748
1708
    def log_string(self, revno, rev, max_chars, tags=None, prefix=''):
1749
1709
        """Format log info into one string. Truncate tail of string
1750
 
 
1751
 
        :param revno:      revision number or None.
1752
 
                           Revision numbers counts from 1.
1753
 
        :param rev:        revision object
1754
 
        :param max_chars:  maximum length of resulting string
1755
 
        :param tags:       list of tags or None
1756
 
        :param prefix:     string to prefix each line
1757
 
        :return:           formatted truncated string
 
1710
        :param  revno:      revision number or None.
 
1711
                            Revision numbers counts from 1.
 
1712
        :param  rev:        revision object
 
1713
        :param  max_chars:  maximum length of resulting string
 
1714
        :param  tags:       list of tags or None
 
1715
        :param  prefix:     string to prefix each line
 
1716
        :return:            formatted truncated string
1758
1717
        """
1759
1718
        out = []
1760
1719
        if revno:
1761
1720
            # show revno only when is not None
1762
1721
            out.append("%s:" % revno)
1763
 
        if max_chars is not None:
1764
 
            out.append(self.truncate(
1765
 
                self.short_author(rev), (max_chars + 3) // 4))
1766
 
        else:
1767
 
            out.append(self.short_author(rev))
 
1722
        out.append(self.truncate(self.short_author(rev), 20))
1768
1723
        out.append(self.date_string(rev))
1769
1724
        if len(rev.parent_ids) > 1:
1770
1725
            out.append('[merge]')
1771
1726
        if tags:
1772
 
            tag_str = '{%s}' % (', '.join(sorted(tags)))
 
1727
            tag_str = '{%s}' % (', '.join(tags))
1773
1728
            out.append(tag_str)
1774
1729
        out.append(rev.get_summary())
1775
1730
        return self.truncate(prefix + " ".join(out).rstrip('\n'), max_chars)
1791
1746
                               show_offset=False)
1792
1747
        committer_str = self.authors(revision.rev, 'first', sep=', ')
1793
1748
        committer_str = committer_str.replace(' <', '  <')
1794
 
        to_file.write('%s  %s\n\n' % (date_str, committer_str))
 
1749
        to_file.write('%s  %s\n\n' % (date_str,committer_str))
1795
1750
 
1796
1751
        if revision.delta is not None and revision.delta.has_changed():
1797
1752
            for c in revision.delta.added + revision.delta.removed + revision.delta.modified:
1798
 
                if c.path[0] is None:
1799
 
                    path = c.path[1]
1800
 
                else:
1801
 
                    path = c.path[0]
 
1753
                path, = c[:1]
1802
1754
                to_file.write('\t* %s:\n' % (path,))
1803
 
            for c in revision.delta.renamed + revision.delta.copied:
 
1755
            for c in revision.delta.renamed:
 
1756
                oldpath,newpath = c[:2]
1804
1757
                # For renamed files, show both the old and the new path
1805
 
                to_file.write('\t* %s:\n\t* %s:\n' % (c.path[0], c.path[1]))
 
1758
                to_file.write('\t* %s:\n\t* %s:\n' % (oldpath,newpath))
1806
1759
            to_file.write('\n')
1807
1760
 
1808
1761
        if not revision.rev.message:
1831
1784
        return self.get(name)(*args, **kwargs)
1832
1785
 
1833
1786
    def get_default(self, branch):
1834
 
        c = branch.get_config_stack()
1835
 
        return self.get(c.get('log_format'))
 
1787
        return self.get(branch.get_config().log_format())
1836
1788
 
1837
1789
 
1838
1790
log_formatter_registry = LogFormatterRegistry()
1839
1791
 
1840
1792
 
1841
1793
log_formatter_registry.register('short', ShortLogFormatter,
1842
 
                                'Moderately short log format.')
 
1794
                                'Moderately short log format')
1843
1795
log_formatter_registry.register('long', LongLogFormatter,
1844
 
                                'Detailed log format.')
 
1796
                                'Detailed log format')
1845
1797
log_formatter_registry.register('line', LineLogFormatter,
1846
 
                                'Log format with one line per revision.')
 
1798
                                'Log format with one line per revision')
1847
1799
log_formatter_registry.register('gnu-changelog', GnuChangelogLogFormatter,
1848
 
                                'Format used by GNU ChangeLog files.')
 
1800
                                'Format used by GNU ChangeLog files')
1849
1801
 
1850
1802
 
1851
1803
def register_formatter(name, formatter):
1861
1813
    try:
1862
1814
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
1863
1815
    except KeyError:
1864
 
        raise errors.BzrCommandError(
1865
 
            gettext("unknown log formatter: %r") % name)
 
1816
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
1866
1817
 
1867
1818
 
1868
1819
def author_list_all(rev):
1893
1844
                              'The committer')
1894
1845
 
1895
1846
 
 
1847
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
 
1848
    # deprecated; for compatibility
 
1849
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
 
1850
    lf.show(revno, rev, delta)
 
1851
 
 
1852
 
1896
1853
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
1897
1854
                           log_format='long'):
1898
1855
    """Show the change in revision history comparing the old revision history to the new one.
1904
1861
    """
1905
1862
    if to_file is None:
1906
1863
        to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
1907
 
                                                            errors='replace')
 
1864
            errors='replace')
1908
1865
    lf = log_formatter(log_format,
1909
1866
                       show_ids=False,
1910
1867
                       to_file=to_file,
1913
1870
    # This is the first index which is different between
1914
1871
    # old and new
1915
1872
    base_idx = None
1916
 
    for i in range(max(len(new_rh), len(old_rh))):
 
1873
    for i in xrange(max(len(new_rh),
 
1874
                        len(old_rh))):
1917
1875
        if (len(new_rh) <= i
1918
1876
            or len(old_rh) <= i
1919
 
                or new_rh[i] != old_rh[i]):
 
1877
            or new_rh[i] != old_rh[i]):
1920
1878
            base_idx = i
1921
1879
            break
1922
1880
 
1923
1881
    if base_idx is None:
1924
1882
        to_file.write('Nothing seems to have changed\n')
1925
1883
        return
1926
 
    # TODO: It might be nice to do something like show_log
1927
 
    # and show the merged entries. But since this is the
1928
 
    # removed revisions, it shouldn't be as important
 
1884
    ## TODO: It might be nice to do something like show_log
 
1885
    ##       and show the merged entries. But since this is the
 
1886
    ##       removed revisions, it shouldn't be as important
1929
1887
    if base_idx < len(old_rh):
1930
 
        to_file.write('*' * 60)
 
1888
        to_file.write('*'*60)
1931
1889
        to_file.write('\nRemoved Revisions:\n')
1932
1890
        for i in range(base_idx, len(old_rh)):
1933
1891
            rev = branch.repository.get_revision(old_rh[i])
1934
 
            lr = LogRevision(rev, i + 1, 0, None)
 
1892
            lr = LogRevision(rev, i+1, 0, None)
1935
1893
            lf.log_revision(lr)
1936
 
        to_file.write('*' * 60)
 
1894
        to_file.write('*'*60)
1937
1895
        to_file.write('\n\n')
1938
1896
    if base_idx < len(new_rh):
1939
1897
        to_file.write('Added Revisions:\n')
1940
1898
        show_log(branch,
1941
1899
                 lf,
 
1900
                 None,
1942
1901
                 verbose=False,
1943
1902
                 direction='forward',
1944
 
                 start_revision=base_idx + 1,
 
1903
                 start_revision=base_idx+1,
1945
1904
                 end_revision=len(new_rh),
1946
1905
                 search=None)
1947
1906
 
1959
1918
    old_revisions = set()
1960
1919
    new_history = []
1961
1920
    new_revisions = set()
1962
 
    graph = repository.get_graph()
1963
 
    new_iter = graph.iter_lefthand_ancestry(new_revision_id)
1964
 
    old_iter = graph.iter_lefthand_ancestry(old_revision_id)
 
1921
    new_iter = repository.iter_reverse_revision_history(new_revision_id)
 
1922
    old_iter = repository.iter_reverse_revision_history(old_revision_id)
1965
1923
    stop_revision = None
1966
1924
    do_old = True
1967
1925
    do_new = True
1968
1926
    while do_new or do_old:
1969
1927
        if do_new:
1970
1928
            try:
1971
 
                new_revision = next(new_iter)
 
1929
                new_revision = new_iter.next()
1972
1930
            except StopIteration:
1973
1931
                do_new = False
1974
1932
            else:
1979
1937
                    break
1980
1938
        if do_old:
1981
1939
            try:
1982
 
                old_revision = next(old_iter)
 
1940
                old_revision = old_iter.next()
1983
1941
            except StopIteration:
1984
1942
                do_old = False
1985
1943
            else:
2015
1973
    log_format = log_formatter_registry.get_default(branch)
2016
1974
    lf = log_format(show_ids=False, to_file=output, show_timezone='original')
2017
1975
    if old_history != []:
2018
 
        output.write('*' * 60)
 
1976
        output.write('*'*60)
2019
1977
        output.write('\nRemoved Revisions:\n')
2020
1978
        show_flat_log(branch.repository, old_history, old_revno, lf)
2021
 
        output.write('*' * 60)
 
1979
        output.write('*'*60)
2022
1980
        output.write('\n\n')
2023
1981
    if new_history != []:
2024
1982
        output.write('Added Revisions:\n')
2025
1983
        start_revno = new_revno - len(new_history) + 1
2026
 
        show_log(branch, lf, verbose=False, direction='forward',
2027
 
                 start_revision=start_revno)
 
1984
        show_log(branch, lf, None, verbose=False, direction='forward',
 
1985
                 start_revision=start_revno,)
2028
1986
 
2029
1987
 
2030
1988
def show_flat_log(repository, history, last_revno, lf):
2035
1993
    :param last_revno: The revno of the last revision_id in the history.
2036
1994
    :param lf: The log formatter to use.
2037
1995
    """
 
1996
    start_revno = last_revno - len(history) + 1
2038
1997
    revisions = repository.get_revisions(history)
2039
1998
    for i, rev in enumerate(revisions):
2040
1999
        lr = LogRevision(rev, i + last_revno, 0, None)
2041
2000
        lf.log_revision(lr)
2042
2001
 
2043
2002
 
2044
 
def _get_info_for_log_files(revisionspec_list, file_list, exit_stack):
 
2003
def _get_info_for_log_files(revisionspec_list, file_list, add_cleanup):
2045
2004
    """Find file-ids and kinds given a list of files and a revision range.
2046
2005
 
2047
2006
    We search for files at the end of the range. If not found there,
2051
2010
    :param file_list: the list of paths given on the command line;
2052
2011
      the first of these can be a branch location or a file path,
2053
2012
      the remainder must be file paths
2054
 
    :param exit_stack: When the branch returned is read locked,
2055
 
      an unlock call will be queued to the exit stack.
 
2013
    :param add_cleanup: When the branch returned is read locked,
 
2014
      an unlock call will be queued to the cleanup.
2056
2015
    :return: (branch, info_list, start_rev_info, end_rev_info) where
2057
2016
      info_list is a list of (relative_path, file_id, kind) tuples where
2058
2017
      kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
2059
2018
      branch will be read-locked.
2060
2019
    """
2061
 
    from breezy.builtins import _get_revision_range
2062
 
    tree, b, path = controldir.ControlDir.open_containing_tree_or_branch(
2063
 
        file_list[0])
2064
 
    exit_stack.enter_context(b.lock_read())
 
2020
    from builtins import _get_revision_range, safe_relpath_files
 
2021
    tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
 
2022
    add_cleanup(b.lock_read().unlock)
2065
2023
    # XXX: It's damn messy converting a list of paths to relative paths when
2066
2024
    # those paths might be deleted ones, they might be on a case-insensitive
2067
2025
    # filesystem and/or they might be in silly locations (like another branch).
2071
2029
    # case of running log in a nested directory, assuming paths beyond the
2072
2030
    # first one haven't been deleted ...
2073
2031
    if tree:
2074
 
        relpaths = [path] + tree.safe_relpath_files(file_list[1:])
 
2032
        relpaths = [path] + safe_relpath_files(tree, file_list[1:])
2075
2033
    else:
2076
2034
        relpaths = [path] + file_list[1:]
2077
2035
    info_list = []
2078
2036
    start_rev_info, end_rev_info = _get_revision_range(revisionspec_list, b,
2079
 
                                                       "log")
 
2037
        "log")
2080
2038
    if relpaths in ([], [u'']):
2081
2039
        return b, [], start_rev_info, end_rev_info
2082
2040
    if start_rev_info is None and end_rev_info is None:
2085
2043
        tree1 = None
2086
2044
        for fp in relpaths:
2087
2045
            file_id = tree.path2id(fp)
2088
 
            kind = _get_kind_for_file_id(tree, fp, file_id)
 
2046
            kind = _get_kind_for_file_id(tree, file_id)
2089
2047
            if file_id is None:
2090
2048
                # go back to when time began
2091
2049
                if tree1 is None:
2099
2057
                        tree1 = b.repository.revision_tree(rev1)
2100
2058
                if tree1:
2101
2059
                    file_id = tree1.path2id(fp)
2102
 
                    kind = _get_kind_for_file_id(tree1, fp, file_id)
 
2060
                    kind = _get_kind_for_file_id(tree1, file_id)
2103
2061
            info_list.append((fp, file_id, kind))
2104
2062
 
2105
2063
    elif start_rev_info == end_rev_info:
2107
2065
        tree = b.repository.revision_tree(end_rev_info.rev_id)
2108
2066
        for fp in relpaths:
2109
2067
            file_id = tree.path2id(fp)
2110
 
            kind = _get_kind_for_file_id(tree, fp, file_id)
 
2068
            kind = _get_kind_for_file_id(tree, file_id)
2111
2069
            info_list.append((fp, file_id, kind))
2112
2070
 
2113
2071
    else:
2121
2079
        tree1 = None
2122
2080
        for fp in relpaths:
2123
2081
            file_id = tree.path2id(fp)
2124
 
            kind = _get_kind_for_file_id(tree, fp, file_id)
 
2082
            kind = _get_kind_for_file_id(tree, file_id)
2125
2083
            if file_id is None:
2126
2084
                if tree1 is None:
2127
2085
                    rev_id = start_rev_info.rev_id
2131
2089
                    else:
2132
2090
                        tree1 = b.repository.revision_tree(rev_id)
2133
2091
                file_id = tree1.path2id(fp)
2134
 
                kind = _get_kind_for_file_id(tree1, fp, file_id)
 
2092
                kind = _get_kind_for_file_id(tree1, file_id)
2135
2093
            info_list.append((fp, file_id, kind))
2136
2094
    return b, info_list, start_rev_info, end_rev_info
2137
2095
 
2138
2096
 
2139
 
def _get_kind_for_file_id(tree, path, file_id):
 
2097
def _get_kind_for_file_id(tree, file_id):
2140
2098
    """Return the kind of a file-id or None if it doesn't exist."""
2141
2099
    if file_id is not None:
2142
 
        return tree.kind(path)
 
2100
        return tree.kind(file_id)
2143
2101
    else:
2144
2102
        return None
2145
2103
 
2147
2105
properties_handler_registry = registry.Registry()
2148
2106
 
2149
2107
# Use the properties handlers to print out bug information if available
2150
 
 
2151
 
 
2152
2108
def _bugs_properties_handler(revision):
2153
 
    fixed_bug_urls = []
2154
 
    related_bug_urls = []
2155
 
    for bug_url, status in revision.iter_bugs():
2156
 
        if status == 'fixed':
2157
 
            fixed_bug_urls.append(bug_url)
2158
 
        elif status == 'related':
2159
 
            related_bug_urls.append(bug_url)
2160
 
    ret = {}
2161
 
    if fixed_bug_urls:
2162
 
        text = ngettext('fixes bug', 'fixes bugs', len(fixed_bug_urls))
2163
 
        ret[text] = ' '.join(fixed_bug_urls)
2164
 
    if related_bug_urls:
2165
 
        text = ngettext('related bug', 'related bugs',
2166
 
                        len(related_bug_urls))
2167
 
        ret[text] = ' '.join(related_bug_urls)
2168
 
    return ret
 
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']
2169
2114
 
 
2115
        if fixed_bug_urls:
 
2116
            return {'fixes bug(s)': ' '.join(fixed_bug_urls)}
 
2117
    return {}
2170
2118
 
2171
2119
properties_handler_registry.register('bugs_properties_handler',
2172
2120
                                     _bugs_properties_handler)