~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/log.py

  • Committer: Sabin Iacob
  • Date: 2009-03-23 14:59:43 UTC
  • mto: (4189.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4193.
  • Revision ID: iacobs@m0n5t3r.info-20090323145943-3s3p1px5q1rkh2e5
update FSF mailing address

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
18
18
 
50
50
"""
51
51
 
52
52
import codecs
 
53
from cStringIO import StringIO
53
54
from itertools import (
 
55
    chain,
54
56
    izip,
55
57
    )
56
58
import re
59
61
    warn,
60
62
    )
61
63
 
 
64
from bzrlib.lazy_import import lazy_import
 
65
lazy_import(globals(), """
 
66
 
62
67
from bzrlib import (
63
68
    config,
64
 
    lazy_regex,
 
69
    diff,
 
70
    errors,
 
71
    repository as _mod_repository,
 
72
    revision as _mod_revision,
 
73
    revisionspec,
 
74
    trace,
 
75
    tsort,
 
76
    )
 
77
""")
 
78
 
 
79
from bzrlib import (
65
80
    registry,
66
 
    symbol_versioning,
67
 
    )
68
 
from bzrlib.errors import (
69
 
    BzrCommandError,
70
81
    )
71
82
from bzrlib.osutils import (
72
83
    format_date,
73
84
    get_terminal_encoding,
74
85
    terminal_width,
75
86
    )
76
 
from bzrlib.revision import (
77
 
    NULL_REVISION,
78
 
    )
79
 
from bzrlib.revisionspec import (
80
 
    RevisionInfo,
81
 
    )
82
 
from bzrlib.symbol_versioning import (
83
 
    deprecated_method,
84
 
    zero_seventeen,
85
 
    )
86
 
from bzrlib.trace import mutter
87
 
from bzrlib.tsort import (
88
 
    merge_sort,
89
 
    topo_sort,
90
 
    )
91
87
 
92
88
 
93
89
def find_touching_revisions(branch, file_id):
151
147
             start_revision=None,
152
148
             end_revision=None,
153
149
             search=None,
154
 
             limit=None):
 
150
             limit=None,
 
151
             show_diff=False):
155
152
    """Write out human-readable log of commits to this branch.
156
153
 
157
 
    lf
158
 
        LogFormatter object to show the output.
159
 
 
160
 
    specific_fileid
161
 
        If true, list only the commits affecting the specified
162
 
        file, rather than all commits.
163
 
 
164
 
    verbose
165
 
        If true show added/changed/deleted/renamed files.
166
 
 
167
 
    direction
168
 
        'reverse' (default) is latest to earliest;
169
 
        'forward' is earliest to latest.
170
 
 
171
 
    start_revision
172
 
        If not None, only show revisions >= start_revision
173
 
 
174
 
    end_revision
175
 
        If not None, only show revisions <= end_revision
176
 
 
177
 
    search
178
 
        If not None, only show revisions with matching commit messages
179
 
 
180
 
    limit
181
 
        If not None or 0, only show limit revisions
 
154
    :param lf: The LogFormatter object showing the output.
 
155
 
 
156
    :param specific_fileid: If not None, list only the commits affecting the
 
157
        specified file, rather than all commits.
 
158
 
 
159
    :param verbose: If True show added/changed/deleted/renamed files.
 
160
 
 
161
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
 
162
        earliest to latest.
 
163
 
 
164
    :param start_revision: If not None, only show revisions >= start_revision
 
165
 
 
166
    :param end_revision: If not None, only show revisions <= end_revision
 
167
 
 
168
    :param search: If not None, only show revisions with matching commit
 
169
        messages
 
170
 
 
171
    :param limit: If set, shows only 'limit' revisions, all revisions are shown
 
172
        if None or 0.
 
173
 
 
174
    :param show_diff: If True, output a diff after each revision.
182
175
    """
183
176
    branch.lock_read()
184
177
    try:
186
179
            lf.begin_log()
187
180
 
188
181
        _show_log(branch, lf, specific_fileid, verbose, direction,
189
 
                  start_revision, end_revision, search, limit)
 
182
                  start_revision, end_revision, search, limit, show_diff)
190
183
 
191
184
        if getattr(lf, 'end_log', None):
192
185
            lf.end_log()
193
186
    finally:
194
187
        branch.unlock()
195
188
 
 
189
 
196
190
def _show_log(branch,
197
191
             lf,
198
192
             specific_fileid=None,
201
195
             start_revision=None,
202
196
             end_revision=None,
203
197
             search=None,
204
 
             limit=None):
 
198
             limit=None,
 
199
             show_diff=False):
205
200
    """Worker function for show_log - see show_log."""
206
201
    if not isinstance(lf, LogFormatter):
207
202
        warn("not a LogFormatter instance: %r" % lf)
208
 
 
209
 
    if specific_fileid:
210
 
        mutter('get log for file_id %r', specific_fileid)
211
 
 
212
 
    if search is not None:
213
 
        searchRE = re.compile(search, re.IGNORECASE)
214
 
    else:
215
 
        searchRE = None
216
 
 
217
 
    mainline_revs, rev_nos, start_rev_id, end_rev_id = \
218
 
        _get_mainline_revs(branch, start_revision, end_revision)
219
 
    if not mainline_revs:
220
 
        return
221
 
 
 
203
    if specific_fileid:
 
204
        trace.mutter('get log for file_id %r', specific_fileid)
 
205
 
 
206
    # Consult the LogFormatter about what it needs and can handle
 
207
    levels_to_display = lf.get_levels()
 
208
    generate_merge_revisions = levels_to_display != 1
 
209
    allow_single_merge_revision = True
 
210
    if not getattr(lf, 'supports_merge_revisions', False):
 
211
        allow_single_merge_revision = getattr(lf,
 
212
            'supports_single_merge_revision', False)
 
213
    generate_tags = getattr(lf, 'supports_tags', False)
 
214
    if generate_tags and branch.supports_tags():
 
215
        rev_tag_dict = branch.tags.get_reverse_tag_dict()
 
216
    else:
 
217
        rev_tag_dict = {}
 
218
    generate_delta = verbose and getattr(lf, 'supports_delta', False)
 
219
    generate_diff = show_diff and getattr(lf, 'supports_diff', False)
 
220
 
 
221
    # Find and print the interesting revisions
 
222
    repo = branch.repository
 
223
    log_count = 0
 
224
    revision_iterator = _create_log_revision_iterator(branch,
 
225
        start_revision, end_revision, direction, specific_fileid, search,
 
226
        generate_merge_revisions, allow_single_merge_revision,
 
227
        generate_delta, limited_output=limit > 0)
 
228
    for revs in revision_iterator:
 
229
        for (rev_id, revno, merge_depth), rev, delta in revs:
 
230
            # Note: 0 levels means show everything; merge_depth counts from 0
 
231
            if levels_to_display != 0 and merge_depth >= levels_to_display:
 
232
                continue
 
233
            if generate_diff:
 
234
                diff = _format_diff(repo, rev, rev_id, specific_fileid)
 
235
            else:
 
236
                diff = None
 
237
            lr = LogRevision(rev, revno, merge_depth, delta,
 
238
                             rev_tag_dict.get(rev_id), diff)
 
239
            lf.log_revision(lr)
 
240
            if limit:
 
241
                log_count += 1
 
242
                if log_count >= limit:
 
243
                    return
 
244
 
 
245
 
 
246
def _format_diff(repo, rev, rev_id, specific_fileid):
 
247
    if len(rev.parent_ids) == 0:
 
248
        ancestor_id = _mod_revision.NULL_REVISION
 
249
    else:
 
250
        ancestor_id = rev.parent_ids[0]
 
251
    tree_1 = repo.revision_tree(ancestor_id)
 
252
    tree_2 = repo.revision_tree(rev_id)
 
253
    if specific_fileid:
 
254
        specific_files = [tree_2.id2path(specific_fileid)]
 
255
    else:
 
256
        specific_files = None
 
257
    s = StringIO()
 
258
    diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
 
259
        new_label='')
 
260
    return s.getvalue()
 
261
 
 
262
 
 
263
class _StartNotLinearAncestor(Exception):
 
264
    """Raised when a start revision is not found walking left-hand history."""
 
265
 
 
266
 
 
267
def _create_log_revision_iterator(branch, start_revision, end_revision,
 
268
    direction, specific_fileid, search, generate_merge_revisions,
 
269
    allow_single_merge_revision, generate_delta, limited_output=False):
 
270
    """Create a revision iterator for log.
 
271
 
 
272
    :param branch: The branch being logged.
 
273
    :param start_revision: If not None, only show revisions >= start_revision
 
274
    :param end_revision: If not None, only show revisions <= end_revision
 
275
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
 
276
        earliest to latest.
 
277
    :param specific_fileid: If not None, list only the commits affecting the
 
278
        specified file.
 
279
    :param search: If not None, only show revisions with matching commit
 
280
        messages.
 
281
    :param generate_merge_revisions: If False, show only mainline revisions.
 
282
    :param allow_single_merge_revision: If True, logging of a single
 
283
        revision off the mainline is to be allowed
 
284
    :param generate_delta: Whether to generate a delta for each revision.
 
285
    :param limited_output: if True, the user only wants a limited result
 
286
 
 
287
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
288
        delta).
 
289
    """
 
290
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
 
291
        end_revision)
 
292
 
 
293
    # Decide how file-ids are matched: delta-filtering vs per-file graph.
 
294
    # Delta filtering allows revisions to be displayed incrementally
 
295
    # though the total time is much slower for huge repositories: log -v
 
296
    # is the *lower* performance bound. At least until the split
 
297
    # inventory format arrives, per-file-graph needs to remain the
 
298
    # default except in verbose mode. Delta filtering should give more
 
299
    # accurate results (e.g. inclusion of FILE deletions) so arguably
 
300
    # it should always be used in the future.
 
301
    use_deltas_for_matching = specific_fileid and generate_delta
 
302
    delayed_graph_generation = not specific_fileid and (
 
303
            start_rev_id or end_rev_id or limited_output)
 
304
    generate_merges = generate_merge_revisions or (specific_fileid and
 
305
        not use_deltas_for_matching)
 
306
    view_revisions = _calc_view_revisions(branch, start_rev_id, end_rev_id,
 
307
        direction, generate_merges, allow_single_merge_revision,
 
308
        delayed_graph_generation=delayed_graph_generation)
 
309
    search_deltas_for_fileids = None
 
310
    if use_deltas_for_matching:
 
311
        search_deltas_for_fileids = set([specific_fileid])
 
312
    elif specific_fileid:
 
313
        if not isinstance(view_revisions, list):
 
314
            view_revisions = list(view_revisions)
 
315
        view_revisions = _filter_revisions_touching_file_id(branch,
 
316
            specific_fileid, view_revisions,
 
317
            include_merges=generate_merge_revisions)
 
318
    return make_log_rev_iterator(branch, view_revisions, generate_delta,
 
319
        search, file_ids=search_deltas_for_fileids, direction=direction)
 
320
 
 
321
 
 
322
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
 
323
    generate_merge_revisions, allow_single_merge_revision,
 
324
    delayed_graph_generation=False):
 
325
    """Calculate the revisions to view.
 
326
 
 
327
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
 
328
             a list of the same tuples.
 
329
    """
 
330
    br_revno, br_rev_id = branch.last_revision_info()
 
331
    if br_revno == 0:
 
332
        return []
 
333
 
 
334
    # If a single revision is requested, check we can handle it
 
335
    generate_single_revision = (end_rev_id and start_rev_id == end_rev_id and
 
336
        (not generate_merge_revisions or not _has_merges(branch, end_rev_id)))
 
337
    if generate_single_revision:
 
338
        if end_rev_id == br_rev_id:
 
339
            # It's the tip
 
340
            return [(br_rev_id, br_revno, 0)]
 
341
        else:
 
342
            revno = branch.revision_id_to_dotted_revno(end_rev_id)
 
343
            if len(revno) > 1 and not allow_single_merge_revision:
 
344
                # It's a merge revision and the log formatter is
 
345
                # completely brain dead. This "feature" of allowing
 
346
                # log formatters incapable of displaying dotted revnos
 
347
                # ought to be deprecated IMNSHO. IGC 20091022
 
348
                raise errors.BzrCommandError('Selected log formatter only'
 
349
                    ' supports mainline revisions.')
 
350
            revno_str = '.'.join(str(n) for n in revno)
 
351
            return [(end_rev_id, revno_str, 0)]
 
352
 
 
353
    # If we only want to see linear revisions, we can iterate ...
 
354
    if not generate_merge_revisions:
 
355
        result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
 
356
        # If a start limit was given and it's not obviously an
 
357
        # ancestor of the end limit, check it before outputting anything
 
358
        if direction == 'forward' or (start_rev_id
 
359
            and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
 
360
            try:
 
361
                result = list(result)
 
362
            except _StartNotLinearAncestor:
 
363
                raise errors.BzrCommandError('Start revision not found in'
 
364
                    ' left-hand history of end revision.')
 
365
        if direction == 'forward':
 
366
            result = reversed(list(result))
 
367
        return result
 
368
 
 
369
    # On large trees, generating the merge graph can take 30-60 seconds
 
370
    # so we delay doing it until a merge is detected, incrementally
 
371
    # returning initial (non-merge) revisions while we can.
 
372
    initial_revisions = []
 
373
    if delayed_graph_generation:
 
374
        try:
 
375
            for rev_id, revno, depth in \
 
376
                _linear_view_revisions(branch, start_rev_id, end_rev_id):
 
377
                if _has_merges(branch, rev_id):
 
378
                    end_rev_id = rev_id
 
379
                    break
 
380
                else:
 
381
                    initial_revisions.append((rev_id, revno, depth))
 
382
            else:
 
383
                # No merged revisions found
 
384
                if direction == 'reverse':
 
385
                    return initial_revisions
 
386
                elif direction == 'forward':
 
387
                    return reversed(initial_revisions)
 
388
                else:
 
389
                    raise ValueError('invalid direction %r' % direction)
 
390
        except _StartNotLinearAncestor:
 
391
            # A merge was never detected so the lower revision limit can't
 
392
            # be nested down somewhere
 
393
            raise errors.BzrCommandError('Start revision not found in'
 
394
                ' history of end revision.')
 
395
 
 
396
    # A log including nested merges is required. If the direction is reverse,
 
397
    # we rebase the initial merge depths so that the development line is
 
398
    # shown naturally, i.e. just like it is for linear logging. We can easily
 
399
    # make forward the exact opposite display, but showing the merge revisions
 
400
    # indented at the end seems slightly nicer in that case.
 
401
    view_revisions = chain(iter(initial_revisions),
 
402
        _graph_view_revisions(branch, start_rev_id, end_rev_id,
 
403
        rebase_initial_depths=direction == 'reverse'))
222
404
    if direction == 'reverse':
223
 
        start_rev_id, end_rev_id = end_rev_id, start_rev_id
224
 
        
225
 
    legacy_lf = getattr(lf, 'log_revision', None) is None
226
 
    if legacy_lf:
227
 
        # pre-0.17 formatters use show for mainline revisions.
228
 
        # how should we show merged revisions ?
229
 
        #   pre-0.11 api: show_merge
230
 
        #   0.11-0.16 api: show_merge_revno
231
 
        show_merge_revno = getattr(lf, 'show_merge_revno', None)
232
 
        show_merge = getattr(lf, 'show_merge', None)
233
 
        if show_merge is None and show_merge_revno is None:
234
 
            # no merged-revno support
235
 
            generate_merge_revisions = False
236
 
        else:
237
 
            generate_merge_revisions = True
238
 
        # tell developers to update their code
239
 
        symbol_versioning.warn('LogFormatters should provide log_revision '
240
 
            'instead of show and show_merge_revno since bzr 0.17.',
241
 
            DeprecationWarning, stacklevel=3)
242
 
    else:
243
 
        generate_merge_revisions = getattr(lf, 'supports_merge_revisions', 
244
 
                                           False)
245
 
    generate_single_revision = False
246
 
    if ((not generate_merge_revisions)
247
 
        and ((start_rev_id and (start_rev_id not in rev_nos))
248
 
            or (end_rev_id and (end_rev_id not in rev_nos)))):
249
 
        generate_single_revision = ((start_rev_id == end_rev_id)
250
 
            and getattr(lf, 'supports_single_merge_revision', False))
251
 
        if not generate_single_revision:
252
 
            raise BzrCommandError('Selected log formatter only supports '
253
 
                'mainline revisions.')
254
 
        generate_merge_revisions = generate_single_revision
255
 
    view_revs_iter = get_view_revisions(mainline_revs, rev_nos, branch,
256
 
                          direction, include_merges=generate_merge_revisions)
257
 
    view_revisions = _filter_revision_range(list(view_revs_iter),
258
 
                                            start_rev_id,
259
 
                                            end_rev_id)
260
 
    if view_revisions and generate_single_revision:
261
 
        view_revisions = view_revisions[0:1]
 
405
        return view_revisions
 
406
    elif direction == 'forward':
 
407
        # Forward means oldest first, adjusting for depth.
 
408
        view_revisions = reverse_by_depth(list(view_revisions))
 
409
        return _rebase_merge_depth(view_revisions)
 
410
    else:
 
411
        raise ValueError('invalid direction %r' % direction)
 
412
 
 
413
 
 
414
def _has_merges(branch, rev_id):
 
415
    """Does a revision have multiple parents or not?"""
 
416
    parents = branch.repository.get_parent_map([rev_id]).get(rev_id, [])
 
417
    return len(parents) > 1
 
418
 
 
419
 
 
420
def _is_obvious_ancestor(branch, start_rev_id, end_rev_id):
 
421
    """Is start_rev_id an obvious ancestor of end_rev_id?"""
 
422
    if start_rev_id and end_rev_id:
 
423
        start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
 
424
        end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
 
425
        if len(start_dotted) == 1 and len(end_dotted) == 1:
 
426
            # both on mainline
 
427
            return start_dotted[0] <= end_dotted[0]
 
428
        elif (len(start_dotted) == 3 and len(end_dotted) == 3 and
 
429
            start_dotted[0:1] == end_dotted[0:1]):
 
430
            # both on same development line
 
431
            return start_dotted[2] <= end_dotted[2]
 
432
        else:
 
433
            # not obvious
 
434
            return False
 
435
    return True
 
436
 
 
437
 
 
438
def _linear_view_revisions(branch, start_rev_id, end_rev_id):
 
439
    """Calculate a sequence of revisions to view, newest to oldest.
 
440
 
 
441
    :param start_rev_id: the lower revision-id
 
442
    :param end_rev_id: the upper revision-id
 
443
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
 
444
    :raises _StartNotLinearAncestor: if a start_rev_id is specified but
 
445
      is not found walking the left-hand history
 
446
    """
 
447
    br_revno, br_rev_id = branch.last_revision_info()
 
448
    repo = branch.repository
 
449
    if start_rev_id is None and end_rev_id is None:
 
450
        cur_revno = br_revno
 
451
        for revision_id in repo.iter_reverse_revision_history(br_rev_id):
 
452
            yield revision_id, str(cur_revno), 0
 
453
            cur_revno -= 1
 
454
    else:
 
455
        if end_rev_id is None:
 
456
            end_rev_id = br_rev_id
 
457
        found_start = start_rev_id is None
 
458
        for revision_id in repo.iter_reverse_revision_history(end_rev_id):
 
459
            revno = branch.revision_id_to_dotted_revno(revision_id)
 
460
            revno_str = '.'.join(str(n) for n in revno)
 
461
            if not found_start and revision_id == start_rev_id:
 
462
                yield revision_id, revno_str, 0
 
463
                found_start = True
 
464
                break
 
465
            else:
 
466
                yield revision_id, revno_str, 0
 
467
        else:
 
468
            if not found_start:
 
469
                raise _StartNotLinearAncestor()
 
470
 
 
471
 
 
472
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
 
473
    rebase_initial_depths=True):
 
474
    """Calculate revisions to view including merges, newest to oldest.
 
475
 
 
476
    :param branch: the branch
 
477
    :param start_rev_id: the lower revision-id
 
478
    :param end_rev_id: the upper revision-id
 
479
    :param rebase_initial_depth: should depths be rebased until a mainline
 
480
      revision is found?
 
481
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
 
482
    """
 
483
    view_revisions = branch.iter_merge_sorted_revisions(
 
484
        start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
 
485
        stop_rule="with-merges")
 
486
    if not rebase_initial_depths:
 
487
        for (rev_id, merge_depth, revno, end_of_merge
 
488
             ) in view_revisions:
 
489
            yield rev_id, '.'.join(map(str, revno)), merge_depth
 
490
    else:
 
491
        # We're following a development line starting at a merged revision.
 
492
        # We need to adjust depths down by the initial depth until we find
 
493
        # a depth less than it. Then we use that depth as the adjustment.
 
494
        # If and when we reach the mainline, depth adjustment ends.
 
495
        depth_adjustment = None
 
496
        for (rev_id, merge_depth, revno, end_of_merge
 
497
             ) in view_revisions:
 
498
            if depth_adjustment is None:
 
499
                depth_adjustment = merge_depth
 
500
            if depth_adjustment:
 
501
                if merge_depth < depth_adjustment:
 
502
                    depth_adjustment = merge_depth
 
503
                merge_depth -= depth_adjustment
 
504
            yield rev_id, '.'.join(map(str, revno)), merge_depth
 
505
 
 
506
 
 
507
def calculate_view_revisions(branch, start_revision, end_revision, direction,
 
508
        specific_fileid, generate_merge_revisions, allow_single_merge_revision):
 
509
    """Calculate the revisions to view.
 
510
 
 
511
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
 
512
             a list of the same tuples.
 
513
    """
 
514
    # This method is no longer called by the main code path.
 
515
    # It is retained for API compatibility and may be deprecated
 
516
    # soon. IGC 20090116
 
517
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
 
518
        end_revision)
 
519
    view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
 
520
        direction, generate_merge_revisions or specific_fileid,
 
521
        allow_single_merge_revision))
262
522
    if specific_fileid:
263
523
        view_revisions = _filter_revisions_touching_file_id(branch,
264
 
                                                         specific_fileid,
265
 
                                                         mainline_revs,
266
 
                                                         view_revisions)
267
 
 
268
 
    # rebase merge_depth - unless there are no revisions or 
269
 
    # either the first or last revision have merge_depth = 0.
 
524
            specific_fileid, view_revisions,
 
525
            include_merges=generate_merge_revisions)
 
526
    return _rebase_merge_depth(view_revisions)
 
527
 
 
528
 
 
529
def _rebase_merge_depth(view_revisions):
 
530
    """Adjust depths upwards so the top level is 0."""
 
531
    # If either the first or last revision have a merge_depth of 0, we're done
270
532
    if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
271
533
        min_depth = min([d for r,n,d in view_revisions])
272
534
        if min_depth != 0:
273
535
            view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
274
 
        
275
 
    rev_tag_dict = {}
276
 
    generate_tags = getattr(lf, 'supports_tags', False)
277
 
    if generate_tags:
278
 
        if branch.supports_tags():
279
 
            rev_tag_dict = branch.tags.get_reverse_tag_dict()
280
 
 
281
 
    generate_delta = verbose and getattr(lf, 'supports_delta', False)
282
 
 
283
 
    def iter_revisions():
284
 
        # r = revision, n = revno, d = merge depth
285
 
        revision_ids = [r for r, n, d in view_revisions]
286
 
        num = 9
287
 
        repository = branch.repository
288
 
        while revision_ids:
289
 
            cur_deltas = {}
290
 
            revisions = repository.get_revisions(revision_ids[:num])
291
 
            if generate_delta:
292
 
                deltas = repository.get_deltas_for_revisions(revisions)
293
 
                cur_deltas = dict(izip((r.revision_id for r in revisions),
294
 
                                       deltas))
295
 
            for revision in revisions:
296
 
                yield revision, cur_deltas.get(revision.revision_id)
297
 
            revision_ids  = revision_ids[num:]
 
536
    return view_revisions
 
537
 
 
538
 
 
539
def make_log_rev_iterator(branch, view_revisions, generate_delta, search,
 
540
        file_ids=None, direction='reverse'):
 
541
    """Create a revision iterator for log.
 
542
 
 
543
    :param branch: The branch being logged.
 
544
    :param view_revisions: The revisions being viewed.
 
545
    :param generate_delta: Whether to generate a delta for each revision.
 
546
    :param search: A user text search string.
 
547
    :param file_ids: If non empty, only revisions matching one or more of
 
548
      the file-ids are to be kept.
 
549
    :param direction: the direction in which view_revisions is sorted
 
550
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
551
        delta).
 
552
    """
 
553
    # Convert view_revisions into (view, None, None) groups to fit with
 
554
    # the standard interface here.
 
555
    if type(view_revisions) == list:
 
556
        # A single batch conversion is faster than many incremental ones.
 
557
        # As we have all the data, do a batch conversion.
 
558
        nones = [None] * len(view_revisions)
 
559
        log_rev_iterator = iter([zip(view_revisions, nones, nones)])
 
560
    else:
 
561
        def _convert():
 
562
            for view in view_revisions:
 
563
                yield (view, None, None)
 
564
        log_rev_iterator = iter([_convert()])
 
565
    for adapter in log_adapters:
 
566
        # It would be nicer if log adapters were first class objects
 
567
        # with custom parameters. This will do for now. IGC 20090127
 
568
        if adapter == _make_delta_filter:
 
569
            log_rev_iterator = adapter(branch, generate_delta,
 
570
                search, log_rev_iterator, file_ids, direction)
 
571
        else:
 
572
            log_rev_iterator = adapter(branch, generate_delta,
 
573
                search, log_rev_iterator)
 
574
    return log_rev_iterator
 
575
 
 
576
 
 
577
def _make_search_filter(branch, generate_delta, search, log_rev_iterator):
 
578
    """Create a filtered iterator of log_rev_iterator matching on a regex.
 
579
 
 
580
    :param branch: The branch being logged.
 
581
    :param generate_delta: Whether to generate a delta for each revision.
 
582
    :param search: A user text search string.
 
583
    :param log_rev_iterator: An input iterator containing all revisions that
 
584
        could be displayed, in lists.
 
585
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
586
        delta).
 
587
    """
 
588
    if search is None:
 
589
        return log_rev_iterator
 
590
    # Compile the search now to get early errors.
 
591
    searchRE = re.compile(search, re.IGNORECASE)
 
592
    return _filter_message_re(searchRE, log_rev_iterator)
 
593
 
 
594
 
 
595
def _filter_message_re(searchRE, log_rev_iterator):
 
596
    for revs in log_rev_iterator:
 
597
        new_revs = []
 
598
        for (rev_id, revno, merge_depth), rev, delta in revs:
 
599
            if searchRE.search(rev.message):
 
600
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
 
601
        yield new_revs
 
602
 
 
603
 
 
604
def _make_delta_filter(branch, generate_delta, search, log_rev_iterator,
 
605
    fileids=None, direction='reverse'):
 
606
    """Add revision deltas to a log iterator if needed.
 
607
 
 
608
    :param branch: The branch being logged.
 
609
    :param generate_delta: Whether to generate a delta for each revision.
 
610
    :param search: A user text search string.
 
611
    :param log_rev_iterator: An input iterator containing all revisions that
 
612
        could be displayed, in lists.
 
613
    :param fileids: If non empty, only revisions matching one or more of
 
614
      the file-ids are to be kept.
 
615
    :param direction: the direction in which view_revisions is sorted
 
616
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
617
        delta).
 
618
    """
 
619
    if not generate_delta and not fileids:
 
620
        return log_rev_iterator
 
621
    return _generate_deltas(branch.repository, log_rev_iterator,
 
622
        generate_delta, fileids, direction)
 
623
 
 
624
 
 
625
def _generate_deltas(repository, log_rev_iterator, always_delta, fileids,
 
626
    direction):
 
627
    """Create deltas for each batch of revisions in log_rev_iterator.
 
628
 
 
629
    If we're only generating deltas for the sake of filtering against
 
630
    file-ids, we stop generating deltas once all file-ids reach the
 
631
    appropriate life-cycle point. If we're receiving data newest to
 
632
    oldest, then that life-cycle point is 'add', otherwise it's 'remove'.
 
633
    """
 
634
    check_fileids = fileids is not None and len(fileids) > 0
 
635
    if check_fileids:
 
636
        fileid_set = set(fileids)
 
637
        if direction == 'reverse':
 
638
            stop_on = 'add'
 
639
        else:
 
640
            stop_on = 'remove'
 
641
    else:
 
642
        fileid_set = None
 
643
    for revs in log_rev_iterator:
 
644
        # If we were matching against fileids and we've run out,
 
645
        # there's nothing left to do
 
646
        if check_fileids and not fileid_set:
 
647
            return
 
648
        revisions = [rev[1] for rev in revs]
 
649
        deltas = repository.get_deltas_for_revisions(revisions)
 
650
        new_revs = []
 
651
        for rev, delta in izip(revs, deltas):
 
652
            if check_fileids:
 
653
                if not _delta_matches_fileids(delta, fileid_set, stop_on):
 
654
                    continue
 
655
                elif not always_delta:
 
656
                    # Delta was created just for matching - ditch it
 
657
                    # Note: It would probably be a better UI to return
 
658
                    # a delta filtered by the file-ids, rather than
 
659
                    # None at all. That functional enhancement can
 
660
                    # come later ...
 
661
                    delta = None
 
662
            new_revs.append((rev[0], rev[1], delta))
 
663
        yield new_revs
 
664
 
 
665
 
 
666
def _delta_matches_fileids(delta, fileids, stop_on='add'):
 
667
    """Check is a delta matches one of more file-ids.
 
668
 
 
669
    :param fileids: a set of fileids to match against.
 
670
    :param stop_on: either 'add' or 'remove' - take file-ids out of the
 
671
      fileids set once their add or remove entry is detected respectively
 
672
    """
 
673
    if not fileids:
 
674
        return False
 
675
    result = False
 
676
    for item in delta.added:
 
677
        if item[1] in fileids:
 
678
            if stop_on == 'add':
 
679
                fileids.remove(item[1])
 
680
            result = True
 
681
    for item in delta.removed:
 
682
        if item[1] in fileids:
 
683
            if stop_on == 'delete':
 
684
                fileids.remove(item[1])
 
685
            result = True
 
686
    if result:
 
687
        return True
 
688
    for l in (delta.modified, delta.renamed, delta.kind_changed):
 
689
        for item in l:
 
690
            if item[1] in fileids:
 
691
                return True
 
692
    return False
 
693
 
 
694
 
 
695
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
 
696
    """Extract revision objects from the repository
 
697
 
 
698
    :param branch: The branch being logged.
 
699
    :param generate_delta: Whether to generate a delta for each revision.
 
700
    :param search: A user text search string.
 
701
    :param log_rev_iterator: An input iterator containing all revisions that
 
702
        could be displayed, in lists.
 
703
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
704
        delta).
 
705
    """
 
706
    repository = branch.repository
 
707
    for revs in log_rev_iterator:
 
708
        # r = revision_id, n = revno, d = merge depth
 
709
        revision_ids = [view[0] for view, _, _ in revs]
 
710
        revisions = repository.get_revisions(revision_ids)
 
711
        revs = [(rev[0], revision, rev[2]) for rev, revision in
 
712
            izip(revs, revisions)]
 
713
        yield revs
 
714
 
 
715
 
 
716
def _make_batch_filter(branch, generate_delta, search, log_rev_iterator):
 
717
    """Group up a single large batch into smaller ones.
 
718
 
 
719
    :param branch: The branch being logged.
 
720
    :param generate_delta: Whether to generate a delta for each revision.
 
721
    :param search: A user text search string.
 
722
    :param log_rev_iterator: An input iterator containing all revisions that
 
723
        could be displayed, in lists.
 
724
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
725
        delta).
 
726
    """
 
727
    repository = branch.repository
 
728
    num = 9
 
729
    for batch in log_rev_iterator:
 
730
        batch = iter(batch)
 
731
        while True:
 
732
            step = [detail for _, detail in zip(range(num), batch)]
 
733
            if len(step) == 0:
 
734
                break
 
735
            yield step
298
736
            num = min(int(num * 1.5), 200)
299
737
 
300
 
    # now we just print all the revisions
301
 
    log_count = 0
302
 
    for ((rev_id, revno, merge_depth), (rev, delta)) in \
303
 
         izip(view_revisions, iter_revisions()):
304
 
 
305
 
        if searchRE:
306
 
            if not searchRE.search(rev.message):
307
 
                continue
308
 
 
309
 
        if not legacy_lf:
310
 
            lr = LogRevision(rev, revno, merge_depth, delta,
311
 
                             rev_tag_dict.get(rev_id))
312
 
            lf.log_revision(lr)
313
 
        else:
314
 
            # support for legacy (pre-0.17) LogFormatters
315
 
            if merge_depth == 0:
316
 
                if generate_tags:
317
 
                    lf.show(revno, rev, delta, rev_tag_dict.get(rev_id))
318
 
                else:
319
 
                    lf.show(revno, rev, delta)
320
 
            else:
321
 
                if show_merge_revno is None:
322
 
                    lf.show_merge(rev, merge_depth)
323
 
                else:
324
 
                    if generate_tags:
325
 
                        lf.show_merge_revno(rev, merge_depth, revno,
326
 
                                            rev_tag_dict.get(rev_id))
327
 
                    else:
328
 
                        lf.show_merge_revno(rev, merge_depth, revno)
329
 
        if limit:
330
 
            log_count += 1
331
 
            if log_count >= limit:
332
 
                break
 
738
 
 
739
def _get_revision_limits(branch, start_revision, end_revision):
 
740
    """Get and check revision limits.
 
741
 
 
742
    :param  branch: The branch containing the revisions.
 
743
 
 
744
    :param  start_revision: The first revision to be logged.
 
745
            For backwards compatibility this may be a mainline integer revno,
 
746
            but for merge revision support a RevisionInfo is expected.
 
747
 
 
748
    :param  end_revision: The last revision to be logged.
 
749
            For backwards compatibility this may be a mainline integer revno,
 
750
            but for merge revision support a RevisionInfo is expected.
 
751
 
 
752
    :return: (start_rev_id, end_rev_id) tuple.
 
753
    """
 
754
    branch_revno, branch_rev_id = branch.last_revision_info()
 
755
    start_rev_id = None
 
756
    if start_revision is None:
 
757
        start_revno = 1
 
758
    else:
 
759
        if isinstance(start_revision, revisionspec.RevisionInfo):
 
760
            start_rev_id = start_revision.rev_id
 
761
            start_revno = start_revision.revno or 1
 
762
        else:
 
763
            branch.check_real_revno(start_revision)
 
764
            start_revno = start_revision
 
765
            start_rev_id = branch.get_rev_id(start_revno)
 
766
 
 
767
    end_rev_id = None
 
768
    if end_revision is None:
 
769
        end_revno = branch_revno
 
770
    else:
 
771
        if isinstance(end_revision, revisionspec.RevisionInfo):
 
772
            end_rev_id = end_revision.rev_id
 
773
            end_revno = end_revision.revno or branch_revno
 
774
        else:
 
775
            branch.check_real_revno(end_revision)
 
776
            end_revno = end_revision
 
777
            end_rev_id = branch.get_rev_id(end_revno)
 
778
 
 
779
    if branch_revno != 0:
 
780
        if (start_rev_id == _mod_revision.NULL_REVISION
 
781
            or end_rev_id == _mod_revision.NULL_REVISION):
 
782
            raise errors.BzrCommandError('Logging revision 0 is invalid.')
 
783
        if start_revno > end_revno:
 
784
            raise errors.BzrCommandError("Start revision must be older than "
 
785
                                         "the end revision.")
 
786
    return (start_rev_id, end_rev_id)
333
787
 
334
788
 
335
789
def _get_mainline_revs(branch, start_revision, end_revision):
336
790
    """Get the mainline revisions from the branch.
337
 
    
 
791
 
338
792
    Generates the list of mainline revisions for the branch.
339
 
    
340
 
    :param  branch: The branch containing the revisions. 
 
793
 
 
794
    :param  branch: The branch containing the revisions.
341
795
 
342
796
    :param  start_revision: The first revision to be logged.
343
797
            For backwards compatibility this may be a mainline integer revno,
349
803
 
350
804
    :return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
351
805
    """
352
 
    which_revs = _enumerate_history(branch)
353
 
    if not which_revs:
 
806
    branch_revno, branch_last_revision = branch.last_revision_info()
 
807
    if branch_revno == 0:
354
808
        return None, None, None, None
355
809
 
356
 
    # For mainline generation, map start_revision and end_revision to 
357
 
    # mainline revnos. If the revision is not on the mainline choose the 
358
 
    # appropriate extreme of the mainline instead - the extra will be 
 
810
    # For mainline generation, map start_revision and end_revision to
 
811
    # mainline revnos. If the revision is not on the mainline choose the
 
812
    # appropriate extreme of the mainline instead - the extra will be
359
813
    # filtered later.
360
814
    # Also map the revisions to rev_ids, to be used in the later filtering
361
815
    # stage.
362
 
    start_rev_id = None 
 
816
    start_rev_id = None
363
817
    if start_revision is None:
364
818
        start_revno = 1
365
819
    else:
366
 
        if isinstance(start_revision,RevisionInfo):
 
820
        if isinstance(start_revision, revisionspec.RevisionInfo):
367
821
            start_rev_id = start_revision.rev_id
368
822
            start_revno = start_revision.revno or 1
369
823
        else:
370
824
            branch.check_real_revno(start_revision)
371
825
            start_revno = start_revision
372
 
    
 
826
 
373
827
    end_rev_id = None
374
828
    if end_revision is None:
375
 
        end_revno = len(which_revs)
 
829
        end_revno = branch_revno
376
830
    else:
377
 
        if isinstance(end_revision,RevisionInfo):
 
831
        if isinstance(end_revision, revisionspec.RevisionInfo):
378
832
            end_rev_id = end_revision.rev_id
379
 
            end_revno = end_revision.revno or len(which_revs)
 
833
            end_revno = end_revision.revno or branch_revno
380
834
        else:
381
835
            branch.check_real_revno(end_revision)
382
836
            end_revno = end_revision
383
837
 
384
 
    if ((start_rev_id == NULL_REVISION)
385
 
        or (end_rev_id == NULL_REVISION)):
386
 
        raise BzrCommandError('Logging revision 0 is invalid.')
 
838
    if ((start_rev_id == _mod_revision.NULL_REVISION)
 
839
        or (end_rev_id == _mod_revision.NULL_REVISION)):
 
840
        raise errors.BzrCommandError('Logging revision 0 is invalid.')
387
841
    if start_revno > end_revno:
388
 
        raise BzrCommandError("Start revision must be older than "
389
 
                              "the end revision.")
 
842
        raise errors.BzrCommandError("Start revision must be older than "
 
843
                                     "the end revision.")
390
844
 
391
 
    # list indexes are 0-based; revisions are 1-based
392
 
    cut_revs = which_revs[(start_revno-1):(end_revno)]
393
 
    if not cut_revs:
 
845
    if end_revno < start_revno:
394
846
        return None, None, None, None
 
847
    cur_revno = branch_revno
 
848
    rev_nos = {}
 
849
    mainline_revs = []
 
850
    for revision_id in branch.repository.iter_reverse_revision_history(
 
851
                        branch_last_revision):
 
852
        if cur_revno < start_revno:
 
853
            # We have gone far enough, but we always add 1 more revision
 
854
            rev_nos[revision_id] = cur_revno
 
855
            mainline_revs.append(revision_id)
 
856
            break
 
857
        if cur_revno <= end_revno:
 
858
            rev_nos[revision_id] = cur_revno
 
859
            mainline_revs.append(revision_id)
 
860
        cur_revno -= 1
 
861
    else:
 
862
        # We walked off the edge of all revisions, so we add a 'None' marker
 
863
        mainline_revs.append(None)
395
864
 
396
 
    # convert the revision history to a dictionary:
397
 
    rev_nos = dict((k, v) for v, k in cut_revs)
 
865
    mainline_revs.reverse()
398
866
 
399
867
    # override the mainline to look like the revision history.
400
 
    mainline_revs = [revision_id for index, revision_id in cut_revs]
401
 
    if cut_revs[0][0] == 1:
402
 
        mainline_revs.insert(0, None)
403
 
    else:
404
 
        mainline_revs.insert(0, which_revs[start_revno-2][1])
405
868
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
406
869
 
407
870
 
408
871
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
409
872
    """Filter view_revisions based on revision ranges.
410
873
 
411
 
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth) 
 
874
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
412
875
            tuples to be filtered.
413
876
 
414
877
    :param start_rev_id: If not NONE specifies the first revision to be logged.
419
882
 
420
883
    :return: The filtered view_revisions.
421
884
    """
422
 
    if start_rev_id or end_rev_id: 
 
885
    # This method is no longer called by the main code path.
 
886
    # It may be removed soon. IGC 20090127
 
887
    if start_rev_id or end_rev_id:
423
888
        revision_ids = [r for r, n, d in view_revisions]
424
889
        if start_rev_id:
425
890
            start_index = revision_ids.index(start_rev_id)
432
897
                end_index = revision_ids.index(end_rev_id)
433
898
            else:
434
899
                end_index = len(view_revisions) - 1
435
 
        # To include the revisions merged into the last revision, 
 
900
        # To include the revisions merged into the last revision,
436
901
        # extend end_rev_id down to, but not including, the next rev
437
902
        # with the same or lesser merge_depth
438
903
        end_merge_depth = view_revisions[end_index][2]
448
913
    return view_revisions
449
914
 
450
915
 
451
 
def _filter_revisions_touching_file_id(branch, file_id, mainline_revisions,
452
 
                                       view_revs_iter):
453
 
    """Return the list of revision ids which touch a given file id.
 
916
def _filter_revisions_touching_file_id(branch, file_id, view_revisions,
 
917
    include_merges=True):
 
918
    r"""Return the list of revision ids which touch a given file id.
454
919
 
455
920
    The function filters view_revisions and returns a subset.
456
921
    This includes the revisions which directly change the file id,
457
922
    and the revisions which merge these changes. So if the
458
923
    revision graph is::
459
 
        A
460
 
        |\
461
 
        B C
 
924
        A-.
 
925
        |\ \
 
926
        B C E
 
927
        |/ /
 
928
        D |
 
929
        |\|
 
930
        | F
462
931
        |/
463
 
        D
464
 
 
465
 
    And 'C' changes a file, then both C and D will be returned.
466
 
 
467
 
    This will also can be restricted based on a subset of the mainline.
 
932
        G
 
933
 
 
934
    And 'C' changes a file, then both C and D will be returned. F will not be
 
935
    returned even though it brings the changes to C into the branch starting
 
936
    with E. (Note that if we were using F as the tip instead of G, then we
 
937
    would see C, D, F.)
 
938
 
 
939
    This will also be restricted based on a subset of the mainline.
 
940
 
 
941
    :param branch: The branch where we can get text revision information.
 
942
 
 
943
    :param file_id: Filter out revisions that do not touch file_id.
 
944
 
 
945
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
 
946
        tuples. This is the list of revisions which will be filtered. It is
 
947
        assumed that view_revisions is in merge_sort order (i.e. newest
 
948
        revision first ).
 
949
 
 
950
    :param include_merges: include merge revisions in the result or not
468
951
 
469
952
    :return: A list of (revision_id, dotted_revno, merge_depth) tuples.
470
953
    """
471
 
    # find all the revisions that change the specific file
472
 
    file_weave = branch.repository.weave_store.get_weave(file_id,
473
 
                branch.repository.get_transaction())
474
 
    weave_modifed_revisions = set(file_weave.versions())
475
 
    # build the ancestry of each revision in the graph
476
 
    # - only listing the ancestors that change the specific file.
477
 
    rev_graph = branch.repository.get_revision_graph(mainline_revisions[-1])
478
 
    sorted_rev_list = topo_sort(rev_graph)
479
 
    ancestry = {}
480
 
    for rev in sorted_rev_list:
481
 
        parents = rev_graph[rev]
482
 
        if rev not in weave_modifed_revisions and len(parents) == 1:
483
 
            # We will not be adding anything new, so just use a reference to
484
 
            # the parent ancestry.
485
 
            rev_ancestry = ancestry[parents[0]]
 
954
    # Lookup all possible text keys to determine which ones actually modified
 
955
    # the file.
 
956
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
 
957
    # Looking up keys in batches of 1000 can cut the time in half, as well as
 
958
    # memory consumption. GraphIndex *does* like to look for a few keys in
 
959
    # parallel, it just doesn't like looking for *lots* of keys in parallel.
 
960
    # TODO: This code needs to be re-evaluated periodically as we tune the
 
961
    #       indexing layer. We might consider passing in hints as to the known
 
962
    #       access pattern (sparse/clustered, high success rate/low success
 
963
    #       rate). This particular access is clustered with a low success rate.
 
964
    get_parent_map = branch.repository.texts.get_parent_map
 
965
    modified_text_revisions = set()
 
966
    chunk_size = 1000
 
967
    for start in xrange(0, len(text_keys), chunk_size):
 
968
        next_keys = text_keys[start:start + chunk_size]
 
969
        # Only keep the revision_id portion of the key
 
970
        modified_text_revisions.update(
 
971
            [k[1] for k in get_parent_map(next_keys)])
 
972
    del text_keys, next_keys
 
973
 
 
974
    result = []
 
975
    # Track what revisions will merge the current revision, replace entries
 
976
    # with 'None' when they have been added to result
 
977
    current_merge_stack = [None]
 
978
    for info in view_revisions:
 
979
        rev_id, revno, depth = info
 
980
        if depth == len(current_merge_stack):
 
981
            current_merge_stack.append(info)
486
982
        else:
487
 
            rev_ancestry = set()
488
 
            if rev in weave_modifed_revisions:
489
 
                rev_ancestry.add(rev)
490
 
            for parent in parents:
491
 
                rev_ancestry = rev_ancestry.union(ancestry[parent])
492
 
        ancestry[rev] = rev_ancestry
493
 
 
494
 
    def is_merging_rev(r):
495
 
        parents = rev_graph[r]
496
 
        if len(parents) > 1:
497
 
            leftparent = parents[0]
498
 
            for rightparent in parents[1:]:
499
 
                if not ancestry[leftparent].issuperset(
500
 
                        ancestry[rightparent]):
501
 
                    return True
502
 
        return False
503
 
 
504
 
    # filter from the view the revisions that did not change or merge 
505
 
    # the specific file
506
 
    return [(r, n, d) for r, n, d in view_revs_iter
507
 
            if r in weave_modifed_revisions or is_merging_rev(r)]
 
983
            del current_merge_stack[depth + 1:]
 
984
            current_merge_stack[-1] = info
 
985
 
 
986
        if rev_id in modified_text_revisions:
 
987
            # This needs to be logged, along with the extra revisions
 
988
            for idx in xrange(len(current_merge_stack)):
 
989
                node = current_merge_stack[idx]
 
990
                if node is not None:
 
991
                    if include_merges or node[2] == 0:
 
992
                        result.append(node)
 
993
                        current_merge_stack[idx] = None
 
994
    return result
508
995
 
509
996
 
510
997
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
513
1000
    :return: an iterator of (revision_id, revno, merge_depth)
514
1001
    (if there is no revno for a revision, None is supplied)
515
1002
    """
516
 
    if include_merges is False:
 
1003
    # This method is no longer called by the main code path.
 
1004
    # It is retained for API compatibility and may be deprecated
 
1005
    # soon. IGC 20090127
 
1006
    if not include_merges:
517
1007
        revision_ids = mainline_revs[1:]
518
1008
        if direction == 'reverse':
519
1009
            revision_ids.reverse()
520
1010
        for revision_id in revision_ids:
521
1011
            yield revision_id, str(rev_nos[revision_id]), 0
522
1012
        return
523
 
    merge_sorted_revisions = merge_sort(
524
 
        branch.repository.get_revision_graph(mainline_revs[-1]),
 
1013
    graph = branch.repository.get_graph()
 
1014
    # This asks for all mainline revisions, which means we only have to spider
 
1015
    # sideways, rather than depth history. That said, its still size-of-history
 
1016
    # and should be addressed.
 
1017
    # mainline_revisions always includes an extra revision at the beginning, so
 
1018
    # don't request it.
 
1019
    parent_map = dict(((key, value) for key, value in
 
1020
        graph.iter_ancestry(mainline_revs[1:]) if value is not None))
 
1021
    # filter out ghosts; merge_sort errors on ghosts.
 
1022
    rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
 
1023
    merge_sorted_revisions = tsort.merge_sort(
 
1024
        rev_graph,
525
1025
        mainline_revs[-1],
526
1026
        mainline_revs,
527
1027
        generate_revno=True)
532
1032
    elif direction != 'reverse':
533
1033
        raise ValueError('invalid direction %r' % direction)
534
1034
 
535
 
    for sequence, rev_id, merge_depth, revno, end_of_merge in merge_sorted_revisions:
 
1035
    for (sequence, rev_id, merge_depth, revno, end_of_merge
 
1036
         ) in merge_sorted_revisions:
536
1037
        yield rev_id, '.'.join(map(str, revno)), merge_depth
537
1038
 
538
1039
 
543
1044
    revision of that depth.  There may be no topological justification for this,
544
1045
    but it looks much nicer.
545
1046
    """
 
1047
    # Add a fake revision at start so that we can always attach sub revisions
 
1048
    merge_sorted_revisions = [(None, None, _depth)] + merge_sorted_revisions
546
1049
    zd_revisions = []
547
1050
    for val in merge_sorted_revisions:
548
1051
        if val[2] == _depth:
 
1052
            # Each revision at the current depth becomes a chunk grouping all
 
1053
            # higher depth revisions.
549
1054
            zd_revisions.append([val])
550
1055
        else:
551
 
            assert val[2] > _depth
552
1056
            zd_revisions[-1].append(val)
553
1057
    for revisions in zd_revisions:
554
1058
        if len(revisions) > 1:
 
1059
            # We have higher depth revisions, let reverse them locally
555
1060
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
556
1061
    zd_revisions.reverse()
557
1062
    result = []
558
1063
    for chunk in zd_revisions:
559
1064
        result.extend(chunk)
 
1065
    if _depth == 0:
 
1066
        # Top level call, get rid of the fake revisions that have been added
 
1067
        result = [r for r in result if r[0] is not None and r[1] is not None]
560
1068
    return result
561
1069
 
562
1070
 
564
1072
    """A revision to be logged (by LogFormatter.log_revision).
565
1073
 
566
1074
    A simple wrapper for the attributes of a revision to be logged.
567
 
    The attributes may or may not be populated, as determined by the 
 
1075
    The attributes may or may not be populated, as determined by the
568
1076
    logging options and the log formatter capabilities.
569
1077
    """
570
1078
 
571
1079
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
572
 
                 tags=None):
 
1080
                 tags=None, diff=None):
573
1081
        self.rev = rev
574
 
        self.revno = revno
 
1082
        self.revno = str(revno)
575
1083
        self.merge_depth = merge_depth
576
1084
        self.delta = delta
577
1085
        self.tags = tags
 
1086
        self.diff = diff
578
1087
 
579
1088
 
580
1089
class LogFormatter(object):
585
1094
    If the LogFormatter needs to be informed of the beginning or end of
586
1095
    a log it should implement the begin_log and/or end_log hook methods.
587
1096
 
588
 
    A LogFormatter should define the following supports_XXX flags 
 
1097
    A LogFormatter should define the following supports_XXX flags
589
1098
    to indicate which LogRevision attributes it supports:
590
1099
 
591
1100
    - supports_delta must be True if this log formatter supports delta.
592
 
        Otherwise the delta attribute may not be populated.
593
 
    - supports_merge_revisions must be True if this log formatter supports 
594
 
        merge revisions.  If not, and if supports_single_merge_revisions is
595
 
        also not True, then only mainline revisions will be passed to the 
 
1101
        Otherwise the delta attribute may not be populated.  The 'delta_format'
 
1102
        attribute describes whether the 'short_status' format (1) or the long
 
1103
        one (2) should be used.
 
1104
 
 
1105
    - supports_merge_revisions must be True if this log formatter supports
 
1106
        merge revisions.  If not, and if supports_single_merge_revision is
 
1107
        also not True, then only mainline revisions will be passed to the
596
1108
        formatter.
 
1109
 
 
1110
    - preferred_levels is the number of levels this formatter defaults to.
 
1111
        The default value is zero meaning display all levels.
 
1112
        This value is only relevant if supports_merge_revisions is True.
 
1113
 
597
1114
    - supports_single_merge_revision must be True if this log formatter
598
1115
        supports logging only a single merge revision.  This flag is
599
1116
        only relevant if supports_merge_revisions is not True.
 
1117
 
600
1118
    - supports_tags must be True if this log formatter supports tags.
601
1119
        Otherwise the tags attribute may not be populated.
 
1120
 
 
1121
    - supports_diff must be True if this log formatter supports diffs.
 
1122
        Otherwise the diff attribute may not be populated.
 
1123
 
 
1124
    Plugins can register functions to show custom revision properties using
 
1125
    the properties_handler_registry. The registered function
 
1126
    must respect the following interface description:
 
1127
        def my_show_properties(properties_dict):
 
1128
            # code that returns a dict {'name':'value'} of the properties
 
1129
            # to be shown
602
1130
    """
603
 
 
604
 
    def __init__(self, to_file, show_ids=False, show_timezone='original'):
 
1131
    preferred_levels = 0
 
1132
 
 
1133
    def __init__(self, to_file, show_ids=False, show_timezone='original',
 
1134
                 delta_format=None, levels=None):
 
1135
        """Create a LogFormatter.
 
1136
 
 
1137
        :param to_file: the file to output to
 
1138
        :param show_ids: if True, revision-ids are to be displayed
 
1139
        :param show_timezone: the timezone to use
 
1140
        :param delta_format: the level of delta information to display
 
1141
          or None to leave it u to the formatter to decide
 
1142
        :param levels: the number of levels to display; None or -1 to
 
1143
          let the log formatter decide.
 
1144
        """
605
1145
        self.to_file = to_file
 
1146
        # 'exact' stream used to show diff, it should print content 'as is'
 
1147
        # and should not try to decode/encode it to unicode to avoid bug #328007
 
1148
        self.to_exact_file = getattr(to_file, 'stream', to_file)
606
1149
        self.show_ids = show_ids
607
1150
        self.show_timezone = show_timezone
608
 
 
609
 
# TODO: uncomment this block after show() has been removed.
610
 
# Until then defining log_revision would prevent _show_log calling show() 
611
 
# in legacy formatters.
612
 
#    def log_revision(self, revision):
613
 
#        """Log a revision.
614
 
#
615
 
#        :param  revision:   The LogRevision to be logged.
616
 
#        """
617
 
#        raise NotImplementedError('not implemented in abstract base')
618
 
 
619
 
    @deprecated_method(zero_seventeen)
620
 
    def show(self, revno, rev, delta):
 
1151
        if delta_format is None:
 
1152
            # Ensures backward compatibility
 
1153
            delta_format = 2 # long format
 
1154
        self.delta_format = delta_format
 
1155
        self.levels = levels
 
1156
 
 
1157
    def get_levels(self):
 
1158
        """Get the number of levels to display or 0 for all."""
 
1159
        if getattr(self, 'supports_merge_revisions', False):
 
1160
            if self.levels is None or self.levels == -1:
 
1161
                return self.preferred_levels
 
1162
            else:
 
1163
                return self.levels
 
1164
        return 1
 
1165
 
 
1166
    def log_revision(self, revision):
 
1167
        """Log a revision.
 
1168
 
 
1169
        :param  revision:   The LogRevision to be logged.
 
1170
        """
621
1171
        raise NotImplementedError('not implemented in abstract base')
622
1172
 
623
1173
    def short_committer(self, rev):
627
1177
        return address
628
1178
 
629
1179
    def short_author(self, rev):
630
 
        name, address = config.parse_username(rev.get_apparent_author())
 
1180
        name, address = config.parse_username(rev.get_apparent_authors()[0])
631
1181
        if name:
632
1182
            return name
633
1183
        return address
634
1184
 
 
1185
    def show_properties(self, revision, indent):
 
1186
        """Displays the custom properties returned by each registered handler.
 
1187
 
 
1188
        If a registered handler raises an error it is propagated.
 
1189
        """
 
1190
        for key, handler in properties_handler_registry.iteritems():
 
1191
            for key, value in handler(revision).items():
 
1192
                self.to_file.write(indent + key + ': ' + value + '\n')
 
1193
 
 
1194
    def show_diff(self, to_file, diff, indent):
 
1195
        for l in diff.rstrip().split('\n'):
 
1196
            to_file.write(indent + '%s\n' % (l,))
 
1197
 
635
1198
 
636
1199
class LongLogFormatter(LogFormatter):
637
1200
 
638
1201
    supports_merge_revisions = True
639
1202
    supports_delta = True
640
1203
    supports_tags = True
641
 
 
642
 
    @deprecated_method(zero_seventeen)
643
 
    def show(self, revno, rev, delta, tags=None):
644
 
        lr = LogRevision(rev, revno, 0, delta, tags)
645
 
        return self.log_revision(lr)
646
 
 
647
 
    @deprecated_method(zero_seventeen)
648
 
    def show_merge_revno(self, rev, merge_depth, revno, tags=None):
649
 
        """Show a merged revision rev, with merge_depth and a revno."""
650
 
        lr = LogRevision(rev, revno, merge_depth, tags=tags)
651
 
        return self.log_revision(lr)
 
1204
    supports_diff = True
652
1205
 
653
1206
    def log_revision(self, revision):
654
1207
        """Log a revision, either merged or not."""
660
1213
        if revision.tags:
661
1214
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
662
1215
        if self.show_ids:
663
 
            to_file.write(indent + 'revision-id:' + revision.rev.revision_id)
 
1216
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
664
1217
            to_file.write('\n')
665
1218
            for parent_id in revision.rev.parent_ids:
666
1219
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
 
1220
        self.show_properties(revision.rev, indent)
667
1221
 
668
 
        author = revision.rev.properties.get('author', None)
669
 
        if author is not None:
670
 
            to_file.write(indent + 'author: %s\n' % (author,))
671
 
        to_file.write(indent + 'committer: %s\n' % (revision.rev.committer,))
 
1222
        committer = revision.rev.committer
 
1223
        authors = revision.rev.get_apparent_authors()
 
1224
        if authors != [committer]:
 
1225
            to_file.write(indent + 'author: %s\n' % (", ".join(authors),))
 
1226
        to_file.write(indent + 'committer: %s\n' % (committer,))
672
1227
 
673
1228
        branch_nick = revision.rev.properties.get('branch-nick', None)
674
1229
        if branch_nick is not None:
687
1242
            for l in message.split('\n'):
688
1243
                to_file.write(indent + '  %s\n' % (l,))
689
1244
        if revision.delta is not None:
690
 
            revision.delta.show(to_file, self.show_ids, indent=indent)
 
1245
            # We don't respect delta_format for compatibility
 
1246
            revision.delta.show(to_file, self.show_ids, indent=indent,
 
1247
                                short_status=False)
 
1248
        if revision.diff is not None:
 
1249
            to_file.write(indent + 'diff:\n')
 
1250
            # Note: we explicitly don't indent the diff (relative to the
 
1251
            # revision information) so that the output can be fed to patch -p0
 
1252
            self.show_diff(self.to_exact_file, revision.diff, indent)
691
1253
 
692
1254
 
693
1255
class ShortLogFormatter(LogFormatter):
694
1256
 
 
1257
    supports_merge_revisions = True
 
1258
    preferred_levels = 1
695
1259
    supports_delta = True
696
 
    supports_single_merge_revision = True
 
1260
    supports_tags = True
 
1261
    supports_diff = True
697
1262
 
698
 
    @deprecated_method(zero_seventeen)
699
 
    def show(self, revno, rev, delta):
700
 
        lr = LogRevision(rev, revno, 0, delta)
701
 
        return self.log_revision(lr)
 
1263
    def __init__(self, *args, **kwargs):
 
1264
        super(ShortLogFormatter, self).__init__(*args, **kwargs)
 
1265
        self.revno_width_by_depth = {}
702
1266
 
703
1267
    def log_revision(self, revision):
 
1268
        # We need two indents: one per depth and one for the information
 
1269
        # relative to that indent. Most mainline revnos are 5 chars or
 
1270
        # less while dotted revnos are typically 11 chars or less. Once
 
1271
        # calculated, we need to remember the offset for a given depth
 
1272
        # as we might be starting from a dotted revno in the first column
 
1273
        # and we want subsequent mainline revisions to line up.
 
1274
        depth = revision.merge_depth
 
1275
        indent = '    ' * depth
 
1276
        revno_width = self.revno_width_by_depth.get(depth)
 
1277
        if revno_width is None:
 
1278
            if revision.revno.find('.') == -1:
 
1279
                # mainline revno, e.g. 12345
 
1280
                revno_width = 5
 
1281
            else:
 
1282
                # dotted revno, e.g. 12345.10.55
 
1283
                revno_width = 11
 
1284
            self.revno_width_by_depth[depth] = revno_width
 
1285
        offset = ' ' * (revno_width + 1)
 
1286
 
704
1287
        to_file = self.to_file
705
 
        date_str = format_date(revision.rev.timestamp,
706
 
                               revision.rev.timezone or 0,
707
 
                               self.show_timezone)
708
1288
        is_merge = ''
709
1289
        if len(revision.rev.parent_ids) > 1:
710
1290
            is_merge = ' [merge]'
711
 
        to_file.write("%5s %s\t%s%s\n" % (revision.revno,
712
 
                self.short_author(revision.rev),
 
1291
        tags = ''
 
1292
        if revision.tags:
 
1293
            tags = ' {%s}' % (', '.join(revision.tags))
 
1294
        to_file.write(indent + "%*s %s\t%s%s%s\n" % (revno_width,
 
1295
                revision.revno, self.short_author(revision.rev),
713
1296
                format_date(revision.rev.timestamp,
714
1297
                            revision.rev.timezone or 0,
715
1298
                            self.show_timezone, date_fmt="%Y-%m-%d",
716
1299
                            show_offset=False),
717
 
                is_merge))
 
1300
                tags, is_merge))
 
1301
        self.show_properties(revision.rev, indent+offset)
718
1302
        if self.show_ids:
719
 
            to_file.write('      revision-id:%s\n' % (revision.rev.revision_id,))
 
1303
            to_file.write(indent + offset + 'revision-id:%s\n'
 
1304
                          % (revision.rev.revision_id,))
720
1305
        if not revision.rev.message:
721
 
            to_file.write('      (no message)\n')
 
1306
            to_file.write(indent + offset + '(no message)\n')
722
1307
        else:
723
1308
            message = revision.rev.message.rstrip('\r\n')
724
1309
            for l in message.split('\n'):
725
 
                to_file.write('      %s\n' % (l,))
 
1310
                to_file.write(indent + offset + '%s\n' % (l,))
726
1311
 
727
 
        # TODO: Why not show the modified files in a shorter form as
728
 
        # well? rewrap them single lines of appropriate length
729
1312
        if revision.delta is not None:
730
 
            revision.delta.show(to_file, self.show_ids)
 
1313
            revision.delta.show(to_file, self.show_ids, indent=indent + offset,
 
1314
                                short_status=self.delta_format==1)
 
1315
        if revision.diff is not None:
 
1316
            self.show_diff(self.to_exact_file, revision.diff, '      ')
731
1317
        to_file.write('\n')
732
1318
 
733
1319
 
734
1320
class LineLogFormatter(LogFormatter):
735
1321
 
736
 
    supports_single_merge_revision = True
 
1322
    supports_merge_revisions = True
 
1323
    preferred_levels = 1
 
1324
    supports_tags = True
737
1325
 
738
1326
    def __init__(self, *args, **kwargs):
739
1327
        super(LineLogFormatter, self).__init__(*args, **kwargs)
745
1333
        return str[:max_len-3]+'...'
746
1334
 
747
1335
    def date_string(self, rev):
748
 
        return format_date(rev.timestamp, rev.timezone or 0, 
 
1336
        return format_date(rev.timestamp, rev.timezone or 0,
749
1337
                           self.show_timezone, date_fmt="%Y-%m-%d",
750
1338
                           show_offset=False)
751
1339
 
755
1343
        else:
756
1344
            return rev.message
757
1345
 
758
 
    @deprecated_method(zero_seventeen)
759
 
    def show(self, revno, rev, delta):
760
 
        self.to_file.write(self.log_string(revno, rev, terminal_width()-1))
761
 
        self.to_file.write('\n')
762
 
 
763
1346
    def log_revision(self, revision):
 
1347
        indent = '  ' * revision.merge_depth
764
1348
        self.to_file.write(self.log_string(revision.revno, revision.rev,
765
 
                                              self._max_chars))
 
1349
            self._max_chars, revision.tags, indent))
766
1350
        self.to_file.write('\n')
767
1351
 
768
 
    def log_string(self, revno, rev, max_chars):
 
1352
    def log_string(self, revno, rev, max_chars, tags=None, prefix=''):
769
1353
        """Format log info into one string. Truncate tail of string
770
 
        :param  revno:      revision number (int) or None.
 
1354
        :param  revno:      revision number or None.
771
1355
                            Revision numbers counts from 1.
772
 
        :param  rev:        revision info object
 
1356
        :param  rev:        revision object
773
1357
        :param  max_chars:  maximum length of resulting string
 
1358
        :param  tags:       list of tags or None
 
1359
        :param  prefix:     string to prefix each line
774
1360
        :return:            formatted truncated string
775
1361
        """
776
1362
        out = []
779
1365
            out.append("%s:" % revno)
780
1366
        out.append(self.truncate(self.short_author(rev), 20))
781
1367
        out.append(self.date_string(rev))
 
1368
        if len(rev.parent_ids) > 1:
 
1369
            out.append('[merge]')
 
1370
        if tags:
 
1371
            tag_str = '{%s}' % (', '.join(tags))
 
1372
            out.append(tag_str)
782
1373
        out.append(rev.get_summary())
783
 
        return self.truncate(" ".join(out).rstrip('\n'), max_chars)
 
1374
        return self.truncate(prefix + " ".join(out).rstrip('\n'), max_chars)
 
1375
 
 
1376
 
 
1377
class GnuChangelogLogFormatter(LogFormatter):
 
1378
 
 
1379
    supports_merge_revisions = True
 
1380
    supports_delta = True
 
1381
 
 
1382
    def log_revision(self, revision):
 
1383
        """Log a revision, either merged or not."""
 
1384
        to_file = self.to_file
 
1385
 
 
1386
        date_str = format_date(revision.rev.timestamp,
 
1387
                               revision.rev.timezone or 0,
 
1388
                               self.show_timezone,
 
1389
                               date_fmt='%Y-%m-%d',
 
1390
                               show_offset=False)
 
1391
        committer_str = revision.rev.committer.replace (' <', '  <')
 
1392
        to_file.write('%s  %s\n\n' % (date_str,committer_str))
 
1393
 
 
1394
        if revision.delta is not None and revision.delta.has_changed():
 
1395
            for c in revision.delta.added + revision.delta.removed + revision.delta.modified:
 
1396
                path, = c[:1]
 
1397
                to_file.write('\t* %s:\n' % (path,))
 
1398
            for c in revision.delta.renamed:
 
1399
                oldpath,newpath = c[:2]
 
1400
                # For renamed files, show both the old and the new path
 
1401
                to_file.write('\t* %s:\n\t* %s:\n' % (oldpath,newpath))
 
1402
            to_file.write('\n')
 
1403
 
 
1404
        if not revision.rev.message:
 
1405
            to_file.write('\tNo commit message\n')
 
1406
        else:
 
1407
            message = revision.rev.message.rstrip('\r\n')
 
1408
            for l in message.split('\n'):
 
1409
                to_file.write('\t%s\n' % (l.lstrip(),))
 
1410
            to_file.write('\n')
784
1411
 
785
1412
 
786
1413
def line_log(rev, max_chars):
812
1439
                                'Detailed log format')
813
1440
log_formatter_registry.register('line', LineLogFormatter,
814
1441
                                'Log format with one line per revision')
 
1442
log_formatter_registry.register('gnu-changelog', GnuChangelogLogFormatter,
 
1443
                                'Format used by GNU ChangeLog files')
815
1444
 
816
1445
 
817
1446
def register_formatter(name, formatter):
827
1456
    try:
828
1457
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
829
1458
    except KeyError:
830
 
        raise BzrCommandError("unknown log formatter: %r" % name)
 
1459
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
831
1460
 
832
1461
 
833
1462
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
890
1519
                 end_revision=len(new_rh),
891
1520
                 search=None)
892
1521
 
 
1522
 
 
1523
def get_history_change(old_revision_id, new_revision_id, repository):
 
1524
    """Calculate the uncommon lefthand history between two revisions.
 
1525
 
 
1526
    :param old_revision_id: The original revision id.
 
1527
    :param new_revision_id: The new revision id.
 
1528
    :param repository: The repository to use for the calculation.
 
1529
 
 
1530
    return old_history, new_history
 
1531
    """
 
1532
    old_history = []
 
1533
    old_revisions = set()
 
1534
    new_history = []
 
1535
    new_revisions = set()
 
1536
    new_iter = repository.iter_reverse_revision_history(new_revision_id)
 
1537
    old_iter = repository.iter_reverse_revision_history(old_revision_id)
 
1538
    stop_revision = None
 
1539
    do_old = True
 
1540
    do_new = True
 
1541
    while do_new or do_old:
 
1542
        if do_new:
 
1543
            try:
 
1544
                new_revision = new_iter.next()
 
1545
            except StopIteration:
 
1546
                do_new = False
 
1547
            else:
 
1548
                new_history.append(new_revision)
 
1549
                new_revisions.add(new_revision)
 
1550
                if new_revision in old_revisions:
 
1551
                    stop_revision = new_revision
 
1552
                    break
 
1553
        if do_old:
 
1554
            try:
 
1555
                old_revision = old_iter.next()
 
1556
            except StopIteration:
 
1557
                do_old = False
 
1558
            else:
 
1559
                old_history.append(old_revision)
 
1560
                old_revisions.add(old_revision)
 
1561
                if old_revision in new_revisions:
 
1562
                    stop_revision = old_revision
 
1563
                    break
 
1564
    new_history.reverse()
 
1565
    old_history.reverse()
 
1566
    if stop_revision is not None:
 
1567
        new_history = new_history[new_history.index(stop_revision) + 1:]
 
1568
        old_history = old_history[old_history.index(stop_revision) + 1:]
 
1569
    return old_history, new_history
 
1570
 
 
1571
 
 
1572
def show_branch_change(branch, output, old_revno, old_revision_id):
 
1573
    """Show the changes made to a branch.
 
1574
 
 
1575
    :param branch: The branch to show changes about.
 
1576
    :param output: A file-like object to write changes to.
 
1577
    :param old_revno: The revno of the old tip.
 
1578
    :param old_revision_id: The revision_id of the old tip.
 
1579
    """
 
1580
    new_revno, new_revision_id = branch.last_revision_info()
 
1581
    old_history, new_history = get_history_change(old_revision_id,
 
1582
                                                  new_revision_id,
 
1583
                                                  branch.repository)
 
1584
    if old_history == [] and new_history == []:
 
1585
        output.write('Nothing seems to have changed\n')
 
1586
        return
 
1587
 
 
1588
    log_format = log_formatter_registry.get_default(branch)
 
1589
    lf = log_format(show_ids=False, to_file=output, show_timezone='original')
 
1590
    if old_history != []:
 
1591
        output.write('*'*60)
 
1592
        output.write('\nRemoved Revisions:\n')
 
1593
        show_flat_log(branch.repository, old_history, old_revno, lf)
 
1594
        output.write('*'*60)
 
1595
        output.write('\n\n')
 
1596
    if new_history != []:
 
1597
        output.write('Added Revisions:\n')
 
1598
        start_revno = new_revno - len(new_history) + 1
 
1599
        show_log(branch, lf, None, verbose=False, direction='forward',
 
1600
                 start_revision=start_revno,)
 
1601
 
 
1602
 
 
1603
def show_flat_log(repository, history, last_revno, lf):
 
1604
    """Show a simple log of the specified history.
 
1605
 
 
1606
    :param repository: The repository to retrieve revisions from.
 
1607
    :param history: A list of revision_ids indicating the lefthand history.
 
1608
    :param last_revno: The revno of the last revision_id in the history.
 
1609
    :param lf: The log formatter to use.
 
1610
    """
 
1611
    start_revno = last_revno - len(history) + 1
 
1612
    revisions = repository.get_revisions(history)
 
1613
    for i, rev in enumerate(revisions):
 
1614
        lr = LogRevision(rev, i + last_revno, 0, None)
 
1615
        lf.log_revision(lr)
 
1616
 
 
1617
 
 
1618
def _get_fileid_to_log(revision, tree, b, fp):
 
1619
    """Find the file-id to log for a file path in a revision range.
 
1620
 
 
1621
    :param revision: the revision range as parsed on the command line
 
1622
    :param tree: the working tree, if any
 
1623
    :param b: the branch
 
1624
    :param fp: file path
 
1625
    """
 
1626
    if revision is None:
 
1627
        if tree is None:
 
1628
            tree = b.basis_tree()
 
1629
        file_id = tree.path2id(fp)
 
1630
        if file_id is None:
 
1631
            # go back to when time began
 
1632
            try:
 
1633
                rev1 = b.get_rev_id(1)
 
1634
            except errors.NoSuchRevision:
 
1635
                # No history at all
 
1636
                file_id = None
 
1637
            else:
 
1638
                tree = b.repository.revision_tree(rev1)
 
1639
                file_id = tree.path2id(fp)
 
1640
 
 
1641
    elif len(revision) == 1:
 
1642
        # One revision given - file must exist in it
 
1643
        tree = revision[0].as_tree(b)
 
1644
        file_id = tree.path2id(fp)
 
1645
 
 
1646
    elif len(revision) == 2:
 
1647
        # Revision range given. Get the file-id from the end tree.
 
1648
        # If that fails, try the start tree.
 
1649
        rev_id = revision[1].as_revision_id(b)
 
1650
        if rev_id is None:
 
1651
            tree = b.basis_tree()
 
1652
        else:
 
1653
            tree = revision[1].as_tree(b)
 
1654
        file_id = tree.path2id(fp)
 
1655
        if file_id is None:
 
1656
            rev_id = revision[0].as_revision_id(b)
 
1657
            if rev_id is None:
 
1658
                rev1 = b.get_rev_id(1)
 
1659
                tree = b.repository.revision_tree(rev1)
 
1660
            else:
 
1661
                tree = revision[0].as_tree(b)
 
1662
            file_id = tree.path2id(fp)
 
1663
    else:
 
1664
        raise errors.BzrCommandError(
 
1665
            'bzr log --revision takes one or two values.')
 
1666
    return file_id
 
1667
 
 
1668
 
 
1669
properties_handler_registry = registry.Registry()
 
1670
properties_handler_registry.register_lazy("foreign",
 
1671
                                          "bzrlib.foreign",
 
1672
                                          "show_foreign_properties")
 
1673
 
 
1674
 
 
1675
# adapters which revision ids to log are filtered. When log is called, the
 
1676
# log_rev_iterator is adapted through each of these factory methods.
 
1677
# Plugins are welcome to mutate this list in any way they like - as long
 
1678
# as the overall behaviour is preserved. At this point there is no extensible
 
1679
# mechanism for getting parameters to each factory method, and until there is
 
1680
# this won't be considered a stable api.
 
1681
log_adapters = [
 
1682
    # core log logic
 
1683
    _make_batch_filter,
 
1684
    # read revision objects
 
1685
    _make_revision_objects,
 
1686
    # filter on log messages
 
1687
    _make_search_filter,
 
1688
    # generate deltas for things we will show
 
1689
    _make_delta_filter
 
1690
    ]