/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: Martin Pool
  • Date: 2005-08-04 22:04:40 UTC
  • Revision ID: mbp@sourcefrog.net-20050804220440-99562df8151d1ac5
- add pending merge from aaron

Show diffs side-by-side

added added

removed removed

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