/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: Robert Collins
  • Date: 2008-08-21 04:27:36 UTC
  • mto: This revision was merged to the branch mainline in revision 3652.
  • Revision ID: robertc@robertcollins.net-20080821042736-742hdcpes9e8p5b5
Make log revision filtering pluggable.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
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
 
16
 
 
17
 
 
18
 
 
19
"""Code to show logs of changes.
 
20
 
 
21
Various flavors of log can be produced:
 
22
 
 
23
* for one file, or the whole tree, and (not done yet) for
 
24
  files in a given directory
 
25
 
 
26
* in "verbose" mode with a description of what changed from one
 
27
  version to the next
 
28
 
 
29
* with file-ids and revision-ids shown
 
30
 
 
31
Logs are actually written out through an abstract LogFormatter
 
32
interface, which allows for different preferred formats.  Plugins can
 
33
register formats too.
 
34
 
 
35
Logs can be produced in either forward (oldest->newest) or reverse
 
36
(newest->oldest) order.
 
37
 
 
38
Logs can be filtered to show only revisions matching a particular
 
39
search string, or within a particular range of revisions.  The range
 
40
can be given as date/times, which are reduced to revisions before
 
41
calling in here.
 
42
 
 
43
In verbose mode we show a summary of what changed in each particular
 
44
revision.  Note that this is the delta for changes in that revision
 
45
relative to its left-most parent, not the delta relative to the last
 
46
logged revision.  So for example if you ask for a verbose log of
 
47
changes touching hello.c you will get a list of those revisions also
 
48
listing other things that were changed in the same revision, but not
 
49
all the changes since the previous revision that touched hello.c.
 
50
"""
 
51
 
 
52
import codecs
 
53
from itertools import (
 
54
    izip,
 
55
    )
 
56
import re
 
57
import sys
 
58
from warnings import (
 
59
    warn,
 
60
    )
 
61
 
 
62
from bzrlib.lazy_import import lazy_import
 
63
lazy_import(globals(), """
 
64
 
 
65
from bzrlib import (
 
66
    config,
 
67
    errors,
 
68
    repository as _mod_repository,
 
69
    revision as _mod_revision,
 
70
    revisionspec,
 
71
    trace,
 
72
    tsort,
 
73
    )
 
74
""")
 
75
 
 
76
from bzrlib import (
 
77
    registry,
 
78
    )
 
79
from bzrlib.osutils import (
 
80
    format_date,
 
81
    get_terminal_encoding,
 
82
    terminal_width,
 
83
    )
 
84
 
 
85
 
 
86
def find_touching_revisions(branch, file_id):
 
87
    """Yield a description of revisions which affect the file_id.
 
88
 
 
89
    Each returned element is (revno, revision_id, description)
 
90
 
 
91
    This is the list of revisions where the file is either added,
 
92
    modified, renamed or deleted.
 
93
 
 
94
    TODO: Perhaps some way to limit this to only particular revisions,
 
95
    or to traverse a non-mainline set of revisions?
 
96
    """
 
97
    last_ie = None
 
98
    last_path = None
 
99
    revno = 1
 
100
    for revision_id in branch.revision_history():
 
101
        this_inv = branch.repository.get_revision_inventory(revision_id)
 
102
        if file_id in this_inv:
 
103
            this_ie = this_inv[file_id]
 
104
            this_path = this_inv.id2path(file_id)
 
105
        else:
 
106
            this_ie = this_path = None
 
107
 
 
108
        # now we know how it was last time, and how it is in this revision.
 
109
        # are those two states effectively the same or not?
 
110
 
 
111
        if not this_ie and not last_ie:
 
112
            # not present in either
 
113
            pass
 
114
        elif this_ie and not last_ie:
 
115
            yield revno, revision_id, "added " + this_path
 
116
        elif not this_ie and last_ie:
 
117
            # deleted here
 
118
            yield revno, revision_id, "deleted " + last_path
 
119
        elif this_path != last_path:
 
120
            yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
 
121
        elif (this_ie.text_size != last_ie.text_size
 
122
              or this_ie.text_sha1 != last_ie.text_sha1):
 
123
            yield revno, revision_id, "modified " + this_path
 
124
 
 
125
        last_ie = this_ie
 
126
        last_path = this_path
 
127
        revno += 1
 
128
 
 
129
 
 
130
def _enumerate_history(branch):
 
131
    rh = []
 
132
    revno = 1
 
133
    for rev_id in branch.revision_history():
 
134
        rh.append((revno, rev_id))
 
135
        revno += 1
 
136
    return rh
 
137
 
 
138
 
 
139
def show_log(branch,
 
140
             lf,
 
141
             specific_fileid=None,
 
142
             verbose=False,
 
143
             direction='reverse',
 
144
             start_revision=None,
 
145
             end_revision=None,
 
146
             search=None,
 
147
             limit=None):
 
148
    """Write out human-readable log of commits to this branch.
 
149
 
 
150
    lf
 
151
        LogFormatter object to show the output.
 
152
 
 
153
    specific_fileid
 
154
        If true, list only the commits affecting the specified
 
155
        file, rather than all commits.
 
156
 
 
157
    verbose
 
158
        If true show added/changed/deleted/renamed files.
 
159
 
 
160
    direction
 
161
        'reverse' (default) is latest to earliest;
 
162
        'forward' is earliest to latest.
 
163
 
 
164
    start_revision
 
165
        If not None, only show revisions >= start_revision
 
166
 
 
167
    end_revision
 
168
        If not None, only show revisions <= end_revision
 
169
 
 
170
    search
 
171
        If not None, only show revisions with matching commit messages
 
172
 
 
173
    limit
 
174
        If not None or 0, only show limit revisions
 
175
    """
 
176
    branch.lock_read()
 
177
    try:
 
178
        if getattr(lf, 'begin_log', None):
 
179
            lf.begin_log()
 
180
 
 
181
        _show_log(branch, lf, specific_fileid, verbose, direction,
 
182
                  start_revision, end_revision, search, limit)
 
183
 
 
184
        if getattr(lf, 'end_log', None):
 
185
            lf.end_log()
 
186
    finally:
 
187
        branch.unlock()
 
188
 
 
189
 
 
190
def _show_log(branch,
 
191
             lf,
 
192
             specific_fileid=None,
 
193
             verbose=False,
 
194
             direction='reverse',
 
195
             start_revision=None,
 
196
             end_revision=None,
 
197
             search=None,
 
198
             limit=None):
 
199
    """Worker function for show_log - see show_log."""
 
200
    if not isinstance(lf, LogFormatter):
 
201
        warn("not a LogFormatter instance: %r" % lf)
 
202
 
 
203
    if specific_fileid:
 
204
        trace.mutter('get log for file_id %r', specific_fileid)
 
205
    generate_merge_revisions = getattr(lf, 'supports_merge_revisions', False)
 
206
    allow_single_merge_revision = getattr(lf,
 
207
        'supports_single_merge_revision', False)
 
208
    view_revisions = calculate_view_revisions(branch, start_revision,
 
209
                                              end_revision, direction,
 
210
                                              specific_fileid,
 
211
                                              generate_merge_revisions,
 
212
                                              allow_single_merge_revision)
 
213
    rev_tag_dict = {}
 
214
    generate_tags = getattr(lf, 'supports_tags', False)
 
215
    if generate_tags:
 
216
        if branch.supports_tags():
 
217
            rev_tag_dict = branch.tags.get_reverse_tag_dict()
 
218
 
 
219
    generate_delta = verbose and getattr(lf, 'supports_delta', False)
 
220
 
 
221
    # now we just print all the revisions
 
222
    log_count = 0
 
223
    revision_iterator = make_log_rev_iterator(branch, view_revisions,
 
224
        generate_delta, search)
 
225
    for revs in revision_iterator:
 
226
        for (rev_id, revno, merge_depth), rev, delta in revs:
 
227
            lr = LogRevision(rev, revno, merge_depth, delta,
 
228
                             rev_tag_dict.get(rev_id))
 
229
            lf.log_revision(lr)
 
230
            if limit:
 
231
                log_count += 1
 
232
                if log_count >= limit:
 
233
                    break
 
234
 
 
235
 
 
236
def calculate_view_revisions(branch, start_revision, end_revision, direction,
 
237
                             specific_fileid, generate_merge_revisions,
 
238
                             allow_single_merge_revision):
 
239
    if (not generate_merge_revisions and start_revision is end_revision is
 
240
        None and direction == 'reverse' and specific_fileid is None):
 
241
        return _linear_view_revisions(branch)
 
242
 
 
243
    mainline_revs, rev_nos, start_rev_id, end_rev_id = \
 
244
        _get_mainline_revs(branch, start_revision, end_revision)
 
245
    if not mainline_revs:
 
246
        return []
 
247
 
 
248
    if direction == 'reverse':
 
249
        start_rev_id, end_rev_id = end_rev_id, start_rev_id
 
250
 
 
251
    generate_single_revision = False
 
252
    if ((not generate_merge_revisions)
 
253
        and ((start_rev_id and (start_rev_id not in rev_nos))
 
254
            or (end_rev_id and (end_rev_id not in rev_nos)))):
 
255
        generate_single_revision = ((start_rev_id == end_rev_id)
 
256
            and allow_single_merge_revision)
 
257
        if not generate_single_revision:
 
258
            raise errors.BzrCommandError('Selected log formatter only supports'
 
259
                ' mainline revisions.')
 
260
        generate_merge_revisions = generate_single_revision
 
261
    view_revs_iter = get_view_revisions(mainline_revs, rev_nos, branch,
 
262
                          direction, include_merges=generate_merge_revisions)
 
263
    view_revisions = _filter_revision_range(list(view_revs_iter),
 
264
                                            start_rev_id,
 
265
                                            end_rev_id)
 
266
    if view_revisions and generate_single_revision:
 
267
        view_revisions = view_revisions[0:1]
 
268
    if specific_fileid:
 
269
        view_revisions = _filter_revisions_touching_file_id(branch,
 
270
                                                         specific_fileid,
 
271
                                                         mainline_revs,
 
272
                                                         view_revisions)
 
273
 
 
274
    # rebase merge_depth - unless there are no revisions or 
 
275
    # either the first or last revision have merge_depth = 0.
 
276
    if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
 
277
        min_depth = min([d for r,n,d in view_revisions])
 
278
        if min_depth != 0:
 
279
            view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
 
280
    return view_revisions
 
281
 
 
282
 
 
283
def _linear_view_revisions(branch):
 
284
    start_revno, start_revision_id = branch.last_revision_info()
 
285
    repo = branch.repository
 
286
    revision_ids = repo.iter_reverse_revision_history(start_revision_id)
 
287
    for num, revision_id in enumerate(revision_ids):
 
288
        yield revision_id, str(start_revno - num), 0
 
289
 
 
290
 
 
291
def make_log_rev_iterator(branch, view_revisions, generate_delta, search):
 
292
    """Create a revision iterator for log.
 
293
 
 
294
    :param branch: The branch being logged.
 
295
    :param view_revisions: The revisions being viewed.
 
296
    :param generate_delta: Whether to generate a delta for each revision.
 
297
    :param search: A user text search string.
 
298
    :return: An iterator over iterators of ((rev_id, revno, merge_depth), rev,
 
299
        delta).
 
300
    """
 
301
    # Convert view_revisions into (view, None, None) groups to fit with
 
302
    # the standard interface here.
 
303
    if type(view_revisions) == list:
 
304
        nones = [None] * len(view_revisions)
 
305
        log_rev_iterator = iter([zip(view_revisions, nones, nones)])
 
306
    else:
 
307
        def _convert():
 
308
            for view in view_revisions:
 
309
                yield (view, None, None)
 
310
        log_rev_iterator = iter([_convert()])
 
311
    for adapter in log_adapters:
 
312
        log_rev_iterator = adapter(branch, generate_delta, search,
 
313
            log_rev_iterator)
 
314
    return log_rev_iterator
 
315
 
 
316
 
 
317
def make_search_filter(branch, generate_delta, search, log_rev_iterator):
 
318
    """Create a filtered iterator of log_rev_iterator matching on a regex.
 
319
 
 
320
    :param branch: The branch being logged.
 
321
    :param generate_delta: Whether to generate a delta for each revision.
 
322
    :param search: A user text search string.
 
323
    :param log_rev_iterator: An input iterator containing all revisions that
 
324
        could be displayed, in lists.
 
325
    :return: An iterator over iterators of ((rev_id, revno, merge_depth), rev,
 
326
        delta).
 
327
    """
 
328
    if search is None:
 
329
        return log_rev_iterator
 
330
    # Compile the search now to get early errors.
 
331
    searchRE = re.compile(search, re.IGNORECASE)
 
332
    return _filter_message_re(searchRE, log_rev_iterator)
 
333
 
 
334
 
 
335
def _filter_message_re(searchRE, log_rev_iterator):
 
336
    for revs in log_rev_iterator:
 
337
        new_revs = []
 
338
        for (rev_id, revno, merge_depth), rev, delta in revs:
 
339
            if searchRE.search(rev.message):
 
340
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
 
341
        yield new_revs
 
342
 
 
343
 
 
344
def make_delta_filter(branch, generate_delta, search, log_rev_iterator):
 
345
    """Add revision deltas to a log iterator if needed.
 
346
 
 
347
    :param branch: The branch being logged.
 
348
    :param generate_delta: Whether to generate a delta for each revision.
 
349
    :param search: A user text search string.
 
350
    :param log_rev_iterator: An input iterator containing all revisions that
 
351
        could be displayed, in lists.
 
352
    :return: An iterator over iterators of ((rev_id, revno, merge_depth), rev,
 
353
        delta).
 
354
    """
 
355
    if not generate_delta:
 
356
        return log_rev_iterator
 
357
    return _generate_deltas(branch.repository, log_rev_iterator)
 
358
 
 
359
 
 
360
def _generate_deltas(repository, log_rev_iterator):
 
361
    for revs in log_rev_iterator:
 
362
        revisions = [rev[1] for rev in revs]
 
363
        deltas = repository.get_deltas_for_revisions(revisions)
 
364
        revs = [(rev[0], rev[1], delta) for rev, delta in izip(revs, deltas)]
 
365
        yield revs
 
366
 
 
367
 
 
368
def make_revision_objects(branch, generate_delta, search, log_rev_iterator):
 
369
    """Extract revision objects from the repository
 
370
 
 
371
    :param branch: The branch being logged.
 
372
    :param generate_delta: Whether to generate a delta for each revision.
 
373
    :param search: A user text search string.
 
374
    :param log_rev_iterator: An input iterator containing all revisions that
 
375
        could be displayed, in lists.
 
376
    :return: An iterator over iterators of ((rev_id, revno, merge_depth), rev,
 
377
        delta).
 
378
    """
 
379
    repository = branch.repository
 
380
    for revs in log_rev_iterator:
 
381
        # r = revision_id, n = revno, d = merge depth
 
382
        revision_ids = [view[0] for view, _, _ in revs]
 
383
        revisions = repository.get_revisions(revision_ids)
 
384
        revs = [(rev[0], revision, rev[2]) for rev, revision in
 
385
            izip(revs, revisions)]
 
386
        yield revs
 
387
 
 
388
 
 
389
def make_batch_filter(branch, generate_delta, search, log_rev_iterator):
 
390
    """Group up a single large batch into smaller ones.
 
391
 
 
392
    :param branch: The branch being logged.
 
393
    :param generate_delta: Whether to generate a delta for each revision.
 
394
    :param search: A user text search string.
 
395
    :param log_rev_iterator: An input iterator containing all revisions that
 
396
        could be displayed, in lists.
 
397
    :return: An iterator over ((rev_id, revno, merge_depth), rev, delta).
 
398
    """
 
399
    repository = branch.repository
 
400
    num = 9
 
401
    for batch in log_rev_iterator:
 
402
        batch = iter(batch)
 
403
        while True:
 
404
            step = [detail for _, detail in zip(range(num), batch)]
 
405
            if len(step) == 0:
 
406
                break
 
407
            yield step
 
408
            num = min(int(num * 1.5), 200)
 
409
 
 
410
 
 
411
def _get_mainline_revs(branch, start_revision, end_revision):
 
412
    """Get the mainline revisions from the branch.
 
413
    
 
414
    Generates the list of mainline revisions for the branch.
 
415
    
 
416
    :param  branch: The branch containing the revisions. 
 
417
 
 
418
    :param  start_revision: The first revision to be logged.
 
419
            For backwards compatibility this may be a mainline integer revno,
 
420
            but for merge revision support a RevisionInfo is expected.
 
421
 
 
422
    :param  end_revision: The last revision to be logged.
 
423
            For backwards compatibility this may be a mainline integer revno,
 
424
            but for merge revision support a RevisionInfo is expected.
 
425
 
 
426
    :return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
 
427
    """
 
428
    branch_revno, branch_last_revision = branch.last_revision_info()
 
429
    if branch_revno == 0:
 
430
        return None, None, None, None
 
431
 
 
432
    # For mainline generation, map start_revision and end_revision to 
 
433
    # mainline revnos. If the revision is not on the mainline choose the 
 
434
    # appropriate extreme of the mainline instead - the extra will be 
 
435
    # filtered later.
 
436
    # Also map the revisions to rev_ids, to be used in the later filtering
 
437
    # stage.
 
438
    start_rev_id = None 
 
439
    if start_revision is None:
 
440
        start_revno = 1
 
441
    else:
 
442
        if isinstance(start_revision, revisionspec.RevisionInfo):
 
443
            start_rev_id = start_revision.rev_id
 
444
            start_revno = start_revision.revno or 1
 
445
        else:
 
446
            branch.check_real_revno(start_revision)
 
447
            start_revno = start_revision
 
448
    
 
449
    end_rev_id = None
 
450
    if end_revision is None:
 
451
        end_revno = branch_revno
 
452
    else:
 
453
        if isinstance(end_revision, revisionspec.RevisionInfo):
 
454
            end_rev_id = end_revision.rev_id
 
455
            end_revno = end_revision.revno or branch_revno
 
456
        else:
 
457
            branch.check_real_revno(end_revision)
 
458
            end_revno = end_revision
 
459
 
 
460
    if ((start_rev_id == _mod_revision.NULL_REVISION)
 
461
        or (end_rev_id == _mod_revision.NULL_REVISION)):
 
462
        raise errors.BzrCommandError('Logging revision 0 is invalid.')
 
463
    if start_revno > end_revno:
 
464
        raise errors.BzrCommandError("Start revision must be older than "
 
465
                                     "the end revision.")
 
466
 
 
467
    if end_revno < start_revno:
 
468
        return None, None, None, None
 
469
    cur_revno = branch_revno
 
470
    rev_nos = {}
 
471
    mainline_revs = []
 
472
    for revision_id in branch.repository.iter_reverse_revision_history(
 
473
                        branch_last_revision):
 
474
        if cur_revno < start_revno:
 
475
            # We have gone far enough, but we always add 1 more revision
 
476
            rev_nos[revision_id] = cur_revno
 
477
            mainline_revs.append(revision_id)
 
478
            break
 
479
        if cur_revno <= end_revno:
 
480
            rev_nos[revision_id] = cur_revno
 
481
            mainline_revs.append(revision_id)
 
482
        cur_revno -= 1
 
483
    else:
 
484
        # We walked off the edge of all revisions, so we add a 'None' marker
 
485
        mainline_revs.append(None)
 
486
 
 
487
    mainline_revs.reverse()
 
488
 
 
489
    # override the mainline to look like the revision history.
 
490
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
 
491
 
 
492
 
 
493
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
 
494
    """Filter view_revisions based on revision ranges.
 
495
 
 
496
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth) 
 
497
            tuples to be filtered.
 
498
 
 
499
    :param start_rev_id: If not NONE specifies the first revision to be logged.
 
500
            If NONE then all revisions up to the end_rev_id are logged.
 
501
 
 
502
    :param end_rev_id: If not NONE specifies the last revision to be logged.
 
503
            If NONE then all revisions up to the end of the log are logged.
 
504
 
 
505
    :return: The filtered view_revisions.
 
506
    """
 
507
    if start_rev_id or end_rev_id: 
 
508
        revision_ids = [r for r, n, d in view_revisions]
 
509
        if start_rev_id:
 
510
            start_index = revision_ids.index(start_rev_id)
 
511
        else:
 
512
            start_index = 0
 
513
        if start_rev_id == end_rev_id:
 
514
            end_index = start_index
 
515
        else:
 
516
            if end_rev_id:
 
517
                end_index = revision_ids.index(end_rev_id)
 
518
            else:
 
519
                end_index = len(view_revisions) - 1
 
520
        # To include the revisions merged into the last revision, 
 
521
        # extend end_rev_id down to, but not including, the next rev
 
522
        # with the same or lesser merge_depth
 
523
        end_merge_depth = view_revisions[end_index][2]
 
524
        try:
 
525
            for index in xrange(end_index+1, len(view_revisions)+1):
 
526
                if view_revisions[index][2] <= end_merge_depth:
 
527
                    end_index = index - 1
 
528
                    break
 
529
        except IndexError:
 
530
            # if the search falls off the end then log to the end as well
 
531
            end_index = len(view_revisions) - 1
 
532
        view_revisions = view_revisions[start_index:end_index+1]
 
533
    return view_revisions
 
534
 
 
535
 
 
536
def _filter_revisions_touching_file_id(branch, file_id, mainline_revisions,
 
537
                                       view_revs_iter):
 
538
    """Return the list of revision ids which touch a given file id.
 
539
 
 
540
    The function filters view_revisions and returns a subset.
 
541
    This includes the revisions which directly change the file id,
 
542
    and the revisions which merge these changes. So if the
 
543
    revision graph is::
 
544
        A
 
545
        |\
 
546
        B C
 
547
        |/
 
548
        D
 
549
 
 
550
    And 'C' changes a file, then both C and D will be returned.
 
551
 
 
552
    This will also can be restricted based on a subset of the mainline.
 
553
 
 
554
    :return: A list of (revision_id, dotted_revno, merge_depth) tuples.
 
555
    """
 
556
    # find all the revisions that change the specific file
 
557
    # build the ancestry of each revision in the graph
 
558
    # - only listing the ancestors that change the specific file.
 
559
    graph = branch.repository.get_graph()
 
560
    # This asks for all mainline revisions, which means we only have to spider
 
561
    # sideways, rather than depth history. That said, its still size-of-history
 
562
    # and should be addressed.
 
563
    # mainline_revisions always includes an extra revision at the beginning, so
 
564
    # don't request it.
 
565
    parent_map = dict(((key, value) for key, value in
 
566
        graph.iter_ancestry(mainline_revisions[1:]) if value is not None))
 
567
    sorted_rev_list = tsort.topo_sort(parent_map.items())
 
568
    text_keys = [(file_id, rev_id) for rev_id in sorted_rev_list]
 
569
    modified_text_versions = branch.repository.texts.get_parent_map(text_keys)
 
570
    ancestry = {}
 
571
    for rev in sorted_rev_list:
 
572
        text_key = (file_id, rev)
 
573
        parents = parent_map[rev]
 
574
        if text_key not in modified_text_versions and len(parents) == 1:
 
575
            # We will not be adding anything new, so just use a reference to
 
576
            # the parent ancestry.
 
577
            rev_ancestry = ancestry[parents[0]]
 
578
        else:
 
579
            rev_ancestry = set()
 
580
            if text_key in modified_text_versions:
 
581
                rev_ancestry.add(rev)
 
582
            for parent in parents:
 
583
                if parent not in ancestry:
 
584
                    # parent is a Ghost, which won't be present in
 
585
                    # sorted_rev_list, but we may access it later, so create an
 
586
                    # empty node for it
 
587
                    ancestry[parent] = set()
 
588
                rev_ancestry = rev_ancestry.union(ancestry[parent])
 
589
        ancestry[rev] = rev_ancestry
 
590
 
 
591
    def is_merging_rev(r):
 
592
        parents = parent_map[r]
 
593
        if len(parents) > 1:
 
594
            leftparent = parents[0]
 
595
            for rightparent in parents[1:]:
 
596
                if not ancestry[leftparent].issuperset(
 
597
                        ancestry[rightparent]):
 
598
                    return True
 
599
        return False
 
600
 
 
601
    # filter from the view the revisions that did not change or merge 
 
602
    # the specific file
 
603
    return [(r, n, d) for r, n, d in view_revs_iter
 
604
            if (file_id, r) in modified_text_versions or is_merging_rev(r)]
 
605
 
 
606
 
 
607
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
 
608
                       include_merges=True):
 
609
    """Produce an iterator of revisions to show
 
610
    :return: an iterator of (revision_id, revno, merge_depth)
 
611
    (if there is no revno for a revision, None is supplied)
 
612
    """
 
613
    if include_merges is False:
 
614
        revision_ids = mainline_revs[1:]
 
615
        if direction == 'reverse':
 
616
            revision_ids.reverse()
 
617
        for revision_id in revision_ids:
 
618
            yield revision_id, str(rev_nos[revision_id]), 0
 
619
        return
 
620
    graph = branch.repository.get_graph()
 
621
    # This asks for all mainline revisions, which means we only have to spider
 
622
    # sideways, rather than depth history. That said, its still size-of-history
 
623
    # and should be addressed.
 
624
    # mainline_revisions always includes an extra revision at the beginning, so
 
625
    # don't request it.
 
626
    parent_map = dict(((key, value) for key, value in
 
627
        graph.iter_ancestry(mainline_revs[1:]) if value is not None))
 
628
    # filter out ghosts; merge_sort errors on ghosts.
 
629
    rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
 
630
    merge_sorted_revisions = tsort.merge_sort(
 
631
        rev_graph,
 
632
        mainline_revs[-1],
 
633
        mainline_revs,
 
634
        generate_revno=True)
 
635
 
 
636
    if direction == 'forward':
 
637
        # forward means oldest first.
 
638
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
 
639
    elif direction != 'reverse':
 
640
        raise ValueError('invalid direction %r' % direction)
 
641
 
 
642
    for sequence, rev_id, merge_depth, revno, end_of_merge in merge_sorted_revisions:
 
643
        yield rev_id, '.'.join(map(str, revno)), merge_depth
 
644
 
 
645
 
 
646
def reverse_by_depth(merge_sorted_revisions, _depth=0):
 
647
    """Reverse revisions by depth.
 
648
 
 
649
    Revisions with a different depth are sorted as a group with the previous
 
650
    revision of that depth.  There may be no topological justification for this,
 
651
    but it looks much nicer.
 
652
    """
 
653
    zd_revisions = []
 
654
    for val in merge_sorted_revisions:
 
655
        if val[2] == _depth:
 
656
            zd_revisions.append([val])
 
657
        else:
 
658
            zd_revisions[-1].append(val)
 
659
    for revisions in zd_revisions:
 
660
        if len(revisions) > 1:
 
661
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
 
662
    zd_revisions.reverse()
 
663
    result = []
 
664
    for chunk in zd_revisions:
 
665
        result.extend(chunk)
 
666
    return result
 
667
 
 
668
 
 
669
class LogRevision(object):
 
670
    """A revision to be logged (by LogFormatter.log_revision).
 
671
 
 
672
    A simple wrapper for the attributes of a revision to be logged.
 
673
    The attributes may or may not be populated, as determined by the 
 
674
    logging options and the log formatter capabilities.
 
675
    """
 
676
 
 
677
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
 
678
                 tags=None):
 
679
        self.rev = rev
 
680
        self.revno = revno
 
681
        self.merge_depth = merge_depth
 
682
        self.delta = delta
 
683
        self.tags = tags
 
684
 
 
685
 
 
686
class LogFormatter(object):
 
687
    """Abstract class to display log messages.
 
688
 
 
689
    At a minimum, a derived class must implement the log_revision method.
 
690
 
 
691
    If the LogFormatter needs to be informed of the beginning or end of
 
692
    a log it should implement the begin_log and/or end_log hook methods.
 
693
 
 
694
    A LogFormatter should define the following supports_XXX flags 
 
695
    to indicate which LogRevision attributes it supports:
 
696
 
 
697
    - supports_delta must be True if this log formatter supports delta.
 
698
        Otherwise the delta attribute may not be populated.
 
699
    - supports_merge_revisions must be True if this log formatter supports 
 
700
        merge revisions.  If not, and if supports_single_merge_revisions is
 
701
        also not True, then only mainline revisions will be passed to the 
 
702
        formatter.
 
703
    - supports_single_merge_revision must be True if this log formatter
 
704
        supports logging only a single merge revision.  This flag is
 
705
        only relevant if supports_merge_revisions is not True.
 
706
    - supports_tags must be True if this log formatter supports tags.
 
707
        Otherwise the tags attribute may not be populated.
 
708
 
 
709
    Plugins can register functions to show custom revision properties using
 
710
    the properties_handler_registry. The registered function
 
711
    must respect the following interface description:
 
712
        def my_show_properties(properties_dict):
 
713
            # code that returns a dict {'name':'value'} of the properties 
 
714
            # to be shown
 
715
    """
 
716
 
 
717
    def __init__(self, to_file, show_ids=False, show_timezone='original'):
 
718
        self.to_file = to_file
 
719
        self.show_ids = show_ids
 
720
        self.show_timezone = show_timezone
 
721
 
 
722
# TODO: uncomment this block after show() has been removed.
 
723
# Until then defining log_revision would prevent _show_log calling show() 
 
724
# in legacy formatters.
 
725
#    def log_revision(self, revision):
 
726
#        """Log a revision.
 
727
#
 
728
#        :param  revision:   The LogRevision to be logged.
 
729
#        """
 
730
#        raise NotImplementedError('not implemented in abstract base')
 
731
 
 
732
    def short_committer(self, rev):
 
733
        name, address = config.parse_username(rev.committer)
 
734
        if name:
 
735
            return name
 
736
        return address
 
737
 
 
738
    def short_author(self, rev):
 
739
        name, address = config.parse_username(rev.get_apparent_author())
 
740
        if name:
 
741
            return name
 
742
        return address
 
743
 
 
744
    def show_properties(self, revision, indent):
 
745
        """Displays the custom properties returned by each registered handler.
 
746
        
 
747
        If a registered handler raises an error it is propagated.
 
748
        """
 
749
        for key, handler in properties_handler_registry.iteritems():
 
750
            for key, value in handler(revision).items():
 
751
                self.to_file.write(indent + key + ': ' + value + '\n')
 
752
 
 
753
 
 
754
class LongLogFormatter(LogFormatter):
 
755
 
 
756
    supports_merge_revisions = True
 
757
    supports_delta = True
 
758
    supports_tags = True
 
759
 
 
760
    def log_revision(self, revision):
 
761
        """Log a revision, either merged or not."""
 
762
        indent = '    ' * revision.merge_depth
 
763
        to_file = self.to_file
 
764
        to_file.write(indent + '-' * 60 + '\n')
 
765
        if revision.revno is not None:
 
766
            to_file.write(indent + 'revno: %s\n' % (revision.revno,))
 
767
        if revision.tags:
 
768
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
 
769
        if self.show_ids:
 
770
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
 
771
            to_file.write('\n')
 
772
            for parent_id in revision.rev.parent_ids:
 
773
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
 
774
        self.show_properties(revision.rev, indent)
 
775
 
 
776
        author = revision.rev.properties.get('author', None)
 
777
        if author is not None:
 
778
            to_file.write(indent + 'author: %s\n' % (author,))
 
779
        to_file.write(indent + 'committer: %s\n' % (revision.rev.committer,))
 
780
 
 
781
        branch_nick = revision.rev.properties.get('branch-nick', None)
 
782
        if branch_nick is not None:
 
783
            to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
 
784
 
 
785
        date_str = format_date(revision.rev.timestamp,
 
786
                               revision.rev.timezone or 0,
 
787
                               self.show_timezone)
 
788
        to_file.write(indent + 'timestamp: %s\n' % (date_str,))
 
789
 
 
790
        to_file.write(indent + 'message:\n')
 
791
        if not revision.rev.message:
 
792
            to_file.write(indent + '  (no message)\n')
 
793
        else:
 
794
            message = revision.rev.message.rstrip('\r\n')
 
795
            for l in message.split('\n'):
 
796
                to_file.write(indent + '  %s\n' % (l,))
 
797
        if revision.delta is not None:
 
798
            revision.delta.show(to_file, self.show_ids, indent=indent)
 
799
 
 
800
 
 
801
class ShortLogFormatter(LogFormatter):
 
802
 
 
803
    supports_delta = True
 
804
    supports_single_merge_revision = True
 
805
 
 
806
    def log_revision(self, revision):
 
807
        to_file = self.to_file
 
808
        is_merge = ''
 
809
        if len(revision.rev.parent_ids) > 1:
 
810
            is_merge = ' [merge]'
 
811
        to_file.write("%5s %s\t%s%s\n" % (revision.revno,
 
812
                self.short_author(revision.rev),
 
813
                format_date(revision.rev.timestamp,
 
814
                            revision.rev.timezone or 0,
 
815
                            self.show_timezone, date_fmt="%Y-%m-%d",
 
816
                            show_offset=False),
 
817
                is_merge))
 
818
        if self.show_ids:
 
819
            to_file.write('      revision-id:%s\n' % (revision.rev.revision_id,))
 
820
        if not revision.rev.message:
 
821
            to_file.write('      (no message)\n')
 
822
        else:
 
823
            message = revision.rev.message.rstrip('\r\n')
 
824
            for l in message.split('\n'):
 
825
                to_file.write('      %s\n' % (l,))
 
826
 
 
827
        # TODO: Why not show the modified files in a shorter form as
 
828
        # well? rewrap them single lines of appropriate length
 
829
        if revision.delta is not None:
 
830
            revision.delta.show(to_file, self.show_ids)
 
831
        to_file.write('\n')
 
832
 
 
833
 
 
834
class LineLogFormatter(LogFormatter):
 
835
 
 
836
    supports_single_merge_revision = True
 
837
 
 
838
    def __init__(self, *args, **kwargs):
 
839
        super(LineLogFormatter, self).__init__(*args, **kwargs)
 
840
        self._max_chars = terminal_width() - 1
 
841
 
 
842
    def truncate(self, str, max_len):
 
843
        if len(str) <= max_len:
 
844
            return str
 
845
        return str[:max_len-3]+'...'
 
846
 
 
847
    def date_string(self, rev):
 
848
        return format_date(rev.timestamp, rev.timezone or 0, 
 
849
                           self.show_timezone, date_fmt="%Y-%m-%d",
 
850
                           show_offset=False)
 
851
 
 
852
    def message(self, rev):
 
853
        if not rev.message:
 
854
            return '(no message)'
 
855
        else:
 
856
            return rev.message
 
857
 
 
858
    def log_revision(self, revision):
 
859
        self.to_file.write(self.log_string(revision.revno, revision.rev,
 
860
                                              self._max_chars))
 
861
        self.to_file.write('\n')
 
862
 
 
863
    def log_string(self, revno, rev, max_chars):
 
864
        """Format log info into one string. Truncate tail of string
 
865
        :param  revno:      revision number (int) or None.
 
866
                            Revision numbers counts from 1.
 
867
        :param  rev:        revision info object
 
868
        :param  max_chars:  maximum length of resulting string
 
869
        :return:            formatted truncated string
 
870
        """
 
871
        out = []
 
872
        if revno:
 
873
            # show revno only when is not None
 
874
            out.append("%s:" % revno)
 
875
        out.append(self.truncate(self.short_author(rev), 20))
 
876
        out.append(self.date_string(rev))
 
877
        out.append(rev.get_summary())
 
878
        return self.truncate(" ".join(out).rstrip('\n'), max_chars)
 
879
 
 
880
 
 
881
def line_log(rev, max_chars):
 
882
    lf = LineLogFormatter(None)
 
883
    return lf.log_string(None, rev, max_chars)
 
884
 
 
885
 
 
886
class LogFormatterRegistry(registry.Registry):
 
887
    """Registry for log formatters"""
 
888
 
 
889
    def make_formatter(self, name, *args, **kwargs):
 
890
        """Construct a formatter from arguments.
 
891
 
 
892
        :param name: Name of the formatter to construct.  'short', 'long' and
 
893
            'line' are built-in.
 
894
        """
 
895
        return self.get(name)(*args, **kwargs)
 
896
 
 
897
    def get_default(self, branch):
 
898
        return self.get(branch.get_config().log_format())
 
899
 
 
900
 
 
901
log_formatter_registry = LogFormatterRegistry()
 
902
 
 
903
 
 
904
log_formatter_registry.register('short', ShortLogFormatter,
 
905
                                'Moderately short log format')
 
906
log_formatter_registry.register('long', LongLogFormatter,
 
907
                                'Detailed log format')
 
908
log_formatter_registry.register('line', LineLogFormatter,
 
909
                                'Log format with one line per revision')
 
910
 
 
911
 
 
912
def register_formatter(name, formatter):
 
913
    log_formatter_registry.register(name, formatter)
 
914
 
 
915
 
 
916
def log_formatter(name, *args, **kwargs):
 
917
    """Construct a formatter from arguments.
 
918
 
 
919
    name -- Name of the formatter to construct; currently 'long', 'short' and
 
920
        'line' are supported.
 
921
    """
 
922
    try:
 
923
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
 
924
    except KeyError:
 
925
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
 
926
 
 
927
 
 
928
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
 
929
    # deprecated; for compatibility
 
930
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
 
931
    lf.show(revno, rev, delta)
 
932
 
 
933
 
 
934
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
 
935
                           log_format='long'):
 
936
    """Show the change in revision history comparing the old revision history to the new one.
 
937
 
 
938
    :param branch: The branch where the revisions exist
 
939
    :param old_rh: The old revision history
 
940
    :param new_rh: The new revision history
 
941
    :param to_file: A file to write the results to. If None, stdout will be used
 
942
    """
 
943
    if to_file is None:
 
944
        to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
 
945
            errors='replace')
 
946
    lf = log_formatter(log_format,
 
947
                       show_ids=False,
 
948
                       to_file=to_file,
 
949
                       show_timezone='original')
 
950
 
 
951
    # This is the first index which is different between
 
952
    # old and new
 
953
    base_idx = None
 
954
    for i in xrange(max(len(new_rh),
 
955
                        len(old_rh))):
 
956
        if (len(new_rh) <= i
 
957
            or len(old_rh) <= i
 
958
            or new_rh[i] != old_rh[i]):
 
959
            base_idx = i
 
960
            break
 
961
 
 
962
    if base_idx is None:
 
963
        to_file.write('Nothing seems to have changed\n')
 
964
        return
 
965
    ## TODO: It might be nice to do something like show_log
 
966
    ##       and show the merged entries. But since this is the
 
967
    ##       removed revisions, it shouldn't be as important
 
968
    if base_idx < len(old_rh):
 
969
        to_file.write('*'*60)
 
970
        to_file.write('\nRemoved Revisions:\n')
 
971
        for i in range(base_idx, len(old_rh)):
 
972
            rev = branch.repository.get_revision(old_rh[i])
 
973
            lr = LogRevision(rev, i+1, 0, None)
 
974
            lf.log_revision(lr)
 
975
        to_file.write('*'*60)
 
976
        to_file.write('\n\n')
 
977
    if base_idx < len(new_rh):
 
978
        to_file.write('Added Revisions:\n')
 
979
        show_log(branch,
 
980
                 lf,
 
981
                 None,
 
982
                 verbose=False,
 
983
                 direction='forward',
 
984
                 start_revision=base_idx+1,
 
985
                 end_revision=len(new_rh),
 
986
                 search=None)
 
987
 
 
988
 
 
989
properties_handler_registry = registry.Registry()
 
990
 
 
991
# adapters which revision ids to log are filtered. When log is called, the
 
992
# log_rev_iterator is adapted through each of these factory methods.
 
993
# Plugins are welcome to mutate this list in any way they like - as long
 
994
# as the overall behaviour is preserved. At this point there is no extensible
 
995
# mechanism for getting parameters to each factory method, and until there is
 
996
# this won't be considered a stable api.
 
997
log_adapters = [
 
998
    # core log logic
 
999
    make_batch_filter,
 
1000
    # read revision objects
 
1001
    make_revision_objects,
 
1002
    # filter on log messages
 
1003
    make_search_filter,
 
1004
    # generate deltas for things we will show
 
1005
    make_delta_filter
 
1006
    ]