/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: Ian Clatworthy
  • Date: 2009-03-26 05:44:58 UTC
  • mfrom: (4202.2.5 bzr.log-multiple)
  • mto: This revision was merged to the branch mainline in revision 4206.
  • Revision ID: ian.clatworthy@canonical.com-20090326054458-zxn4dgghy94z45xd
log multiple files and directories (Ian Clatworthy)

Show diffs side-by-side

added added

removed removed

Lines of Context:
65
65
lazy_import(globals(), """
66
66
 
67
67
from bzrlib import (
 
68
    bzrdir,
68
69
    config,
69
70
    diff,
70
71
    errors,
152
153
             show_diff=False):
153
154
    """Write out human-readable log of commits to this branch.
154
155
 
 
156
    This function is being retained for backwards compatibility but
 
157
    should not be extended with new parameters. Use the new Logger class
 
158
    instead, eg. Logger(branch, rqst).show(lf), adding parameters to the
 
159
    make_log_request_dict function.
 
160
 
155
161
    :param lf: The LogFormatter object showing the output.
156
162
 
157
163
    :param specific_fileid: If not None, list only the commits affecting the
174
180
 
175
181
    :param show_diff: If True, output a diff after each revision.
176
182
    """
177
 
    branch.lock_read()
178
 
    try:
179
 
        if getattr(lf, 'begin_log', None):
180
 
            lf.begin_log()
181
 
 
182
 
        _show_log(branch, lf, specific_fileid, verbose, direction,
183
 
                  start_revision, end_revision, search, limit, show_diff)
184
 
 
185
 
        if getattr(lf, 'end_log', None):
186
 
            lf.end_log()
187
 
    finally:
188
 
        branch.unlock()
189
 
 
190
 
 
191
 
def _show_log(branch,
192
 
             lf,
193
 
             specific_fileid=None,
194
 
             verbose=False,
195
 
             direction='reverse',
196
 
             start_revision=None,
197
 
             end_revision=None,
198
 
             search=None,
199
 
             limit=None,
200
 
             show_diff=False):
201
 
    """Worker function for show_log - see show_log."""
202
 
    if not isinstance(lf, LogFormatter):
203
 
        warn("not a LogFormatter instance: %r" % lf)
204
 
    if specific_fileid:
205
 
        trace.mutter('get log for file_id %r', specific_fileid)
206
 
 
207
 
    # Consult the LogFormatter about what it needs and can handle
208
 
    levels_to_display = lf.get_levels()
209
 
    generate_merge_revisions = levels_to_display != 1
210
 
    allow_single_merge_revision = True
211
 
    if not getattr(lf, 'supports_merge_revisions', False):
212
 
        allow_single_merge_revision = getattr(lf,
213
 
            'supports_single_merge_revision', False)
214
 
    generate_tags = getattr(lf, 'supports_tags', False)
215
 
    if generate_tags and branch.supports_tags():
216
 
        rev_tag_dict = branch.tags.get_reverse_tag_dict()
217
 
    else:
218
 
        rev_tag_dict = {}
219
 
    generate_delta = verbose and getattr(lf, 'supports_delta', False)
220
 
    generate_diff = show_diff and getattr(lf, 'supports_diff', False)
221
 
 
222
 
    # Find and print the interesting revisions
223
 
    repo = branch.repository
224
 
    log_count = 0
225
 
    revision_iterator = _create_log_revision_iterator(branch,
226
 
        start_revision, end_revision, direction, specific_fileid, search,
227
 
        generate_merge_revisions, allow_single_merge_revision,
228
 
        generate_delta, limited_output=limit > 0)
229
 
    for revs in revision_iterator:
230
 
        for (rev_id, revno, merge_depth), rev, delta in revs:
231
 
            # Note: 0 levels means show everything; merge_depth counts from 0
232
 
            if levels_to_display != 0 and merge_depth >= levels_to_display:
233
 
                continue
234
 
            if generate_diff:
235
 
                diff = _format_diff(repo, rev, rev_id, specific_fileid)
236
 
            else:
237
 
                diff = None
238
 
            lr = LogRevision(rev, revno, merge_depth, delta,
239
 
                             rev_tag_dict.get(rev_id), diff)
 
183
    # Convert old-style parameters to new-style parameters
 
184
    if specific_fileid is not None:
 
185
        file_ids = [specific_fileid]
 
186
    else:
 
187
        file_ids = None
 
188
    if verbose:
 
189
        if file_ids:
 
190
            delta_type = 'partial'
 
191
        else:
 
192
            delta_type = 'full'
 
193
    else:
 
194
        delta_type = None
 
195
    if show_diff:
 
196
        if file_ids:
 
197
            diff_type = 'partial'
 
198
        else:
 
199
            diff_type = 'full'
 
200
    else:
 
201
        diff_type = None
 
202
 
 
203
    # Build the request and execute it
 
204
    rqst = make_log_request_dict(direction=direction, specific_fileids=file_ids,
 
205
        start_revision=start_revision, end_revision=end_revision,
 
206
        limit=limit, message_search=search,
 
207
        delta_type=delta_type, diff_type=diff_type)
 
208
    Logger(branch, rqst).show(lf)
 
209
 
 
210
 
 
211
# Note: This needs to be kept this in sync with the defaults in
 
212
# make_log_request_dict() below
 
213
_DEFAULT_REQUEST_PARAMS = {
 
214
    'direction': 'reverse',
 
215
    'levels': 1,
 
216
    'generate_tags': True,
 
217
    '_match_using_deltas': True,
 
218
    }
 
219
 
 
220
 
 
221
def make_log_request_dict(direction='reverse', specific_fileids=None,
 
222
    start_revision=None, end_revision=None, limit=None,
 
223
    message_search=None, levels=1, generate_tags=True, delta_type=None,
 
224
    diff_type=None, _match_using_deltas=True):
 
225
    """Convenience function for making a logging request dictionary.
 
226
 
 
227
    Using this function may make code slightly safer by ensuring
 
228
    parameters have the correct names. It also provides a reference
 
229
    point for documenting the supported parameters.
 
230
 
 
231
    :param direction: 'reverse' (default) is latest to earliest;
 
232
      'forward' is earliest to latest.
 
233
 
 
234
    :param specific_fileids: If not None, only include revisions
 
235
      affecting the specified files, rather than all revisions.
 
236
 
 
237
    :param start_revision: If not None, only generate
 
238
      revisions >= start_revision
 
239
 
 
240
    :param end_revision: If not None, only generate
 
241
      revisions <= end_revision
 
242
 
 
243
    :param limit: If set, generate only 'limit' revisions, all revisions
 
244
      are shown if None or 0.
 
245
 
 
246
    :param message_search: If not None, only include revisions with
 
247
      matching commit messages
 
248
 
 
249
    :param levels: the number of levels of revisions to
 
250
      generate; 1 for just the mainline; 0 for all levels.
 
251
 
 
252
    :param generate_tags: If True, include tags for matched revisions.
 
253
 
 
254
    :param delta_type: Either 'full', 'partial' or None.
 
255
      'full' means generate the complete delta - adds/deletes/modifies/etc;
 
256
      'partial' means filter the delta using specific_fileids;
 
257
      None means do not generate any delta.
 
258
 
 
259
    :param diff_type: Either 'full', 'partial' or None.
 
260
      'full' means generate the complete diff - adds/deletes/modifies/etc;
 
261
      'partial' means filter the diff using specific_fileids;
 
262
      None means do not generate any diff.
 
263
 
 
264
    :param _match_using_deltas: a private parameter controlling the
 
265
      algorithm used for matching specific_fileids. This parameter
 
266
      may be removed in the future so bzrlib client code should NOT
 
267
      use it.
 
268
    """
 
269
    return {
 
270
        'direction': direction,
 
271
        'specific_fileids': specific_fileids,
 
272
        'start_revision': start_revision,
 
273
        'end_revision': end_revision,
 
274
        'limit': limit,
 
275
        'message_search': message_search,
 
276
        'levels': levels,
 
277
        'generate_tags': generate_tags,
 
278
        'delta_type': delta_type,
 
279
        'diff_type': diff_type,
 
280
        # Add 'private' attributes for features that may be deprecated
 
281
        '_match_using_deltas': _match_using_deltas,
 
282
        '_allow_single_merge_revision': True,
 
283
    }
 
284
 
 
285
 
 
286
def _apply_log_request_defaults(rqst):
 
287
    """Apply default values to a request dictionary."""
 
288
    result = _DEFAULT_REQUEST_PARAMS
 
289
    if rqst:
 
290
        result.update(rqst)
 
291
    return result
 
292
 
 
293
 
 
294
class LogGenerator(object):
 
295
    """A generator of log revisions."""
 
296
 
 
297
    def iter_log_revisions(self):
 
298
        """Iterate over LogRevision objects.
 
299
 
 
300
        :return: An iterator yielding LogRevision objects.
 
301
        """
 
302
        raise NotImplementedError(self.iter_log_revisions)
 
303
 
 
304
 
 
305
class Logger(object):
 
306
    """An object the generates, formats and displays a log."""
 
307
 
 
308
    def __init__(self, branch, rqst):
 
309
        """Create a Logger.
 
310
 
 
311
        :param branch: the branch to log
 
312
        :param rqst: A dictionary specifying the query parameters.
 
313
          See make_log_request_dict() for supported values.
 
314
        """
 
315
        self.branch = branch
 
316
        self.rqst = _apply_log_request_defaults(rqst)
 
317
 
 
318
    def show(self, lf):
 
319
        """Display the log.
 
320
 
 
321
        :param lf: The LogFormatter object to send the output to.
 
322
        """
 
323
        if not isinstance(lf, LogFormatter):
 
324
            warn("not a LogFormatter instance: %r" % lf)
 
325
 
 
326
        self.branch.lock_read()
 
327
        try:
 
328
            if getattr(lf, 'begin_log', None):
 
329
                lf.begin_log()
 
330
            self._show_body(lf)
 
331
            if getattr(lf, 'end_log', None):
 
332
                lf.end_log()
 
333
        finally:
 
334
            self.branch.unlock()
 
335
 
 
336
    def _show_body(self, lf):
 
337
        """Show the main log output.
 
338
 
 
339
        Subclasses may wish to override this.
 
340
        """
 
341
        # Tweak the LogRequest based on what the LogFormatter can handle.
 
342
        # (There's no point generating stuff if the formatter can't display it.)
 
343
        rqst = self.rqst
 
344
        rqst['levels'] = lf.get_levels()
 
345
        if not getattr(lf, 'supports_tags', False):
 
346
            rqst['generate_tags'] = False
 
347
        if not getattr(lf, 'supports_delta', False):
 
348
            rqst['delta_type'] = None
 
349
        if not getattr(lf, 'supports_diff', False):
 
350
            rqst['diff_type'] = None
 
351
        if not getattr(lf, 'supports_merge_revisions', False):
 
352
            rqst['_allow_single_merge_revision'] = getattr(lf,
 
353
                'supports_single_merge_revision', False)
 
354
 
 
355
        # Find and print the interesting revisions
 
356
        generator = self._generator_factory(self.branch, rqst)
 
357
        for lr in generator.iter_log_revisions():
240
358
            lf.log_revision(lr)
241
 
            if limit:
242
 
                log_count += 1
243
 
                if log_count >= limit:
244
 
                    return
245
 
 
246
 
 
247
 
def _format_diff(repo, rev, rev_id, specific_fileid):
248
 
    if len(rev.parent_ids) == 0:
249
 
        ancestor_id = _mod_revision.NULL_REVISION
250
 
    else:
251
 
        ancestor_id = rev.parent_ids[0]
252
 
    tree_1 = repo.revision_tree(ancestor_id)
253
 
    tree_2 = repo.revision_tree(rev_id)
254
 
    if specific_fileid:
255
 
        specific_files = [tree_2.id2path(specific_fileid)]
256
 
    else:
257
 
        specific_files = None
258
 
    s = StringIO()
259
 
    diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
260
 
        new_label='')
261
 
    return s.getvalue()
 
359
 
 
360
    def _generator_factory(self, branch, rqst):
 
361
        """Make the LogGenerator object to use.
 
362
        
 
363
        Subclasses may wish to override this.
 
364
        """
 
365
        return _DefaultLogGenerator(branch, rqst)
262
366
 
263
367
 
264
368
class _StartNotLinearAncestor(Exception):
265
369
    """Raised when a start revision is not found walking left-hand history."""
266
370
 
267
371
 
268
 
def _create_log_revision_iterator(branch, start_revision, end_revision,
269
 
    direction, specific_fileid, search, generate_merge_revisions,
270
 
    allow_single_merge_revision, generate_delta, limited_output=False):
271
 
    """Create a revision iterator for log.
272
 
 
273
 
    :param branch: The branch being logged.
274
 
    :param start_revision: If not None, only show revisions >= start_revision
275
 
    :param end_revision: If not None, only show revisions <= end_revision
276
 
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
277
 
        earliest to latest.
278
 
    :param specific_fileid: If not None, list only the commits affecting the
279
 
        specified file.
280
 
    :param search: If not None, only show revisions with matching commit
281
 
        messages.
282
 
    :param generate_merge_revisions: If False, show only mainline revisions.
283
 
    :param allow_single_merge_revision: If True, logging of a single
284
 
        revision off the mainline is to be allowed
285
 
    :param generate_delta: Whether to generate a delta for each revision.
286
 
    :param limited_output: if True, the user only wants a limited result
287
 
 
288
 
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
289
 
        delta).
290
 
    """
291
 
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
292
 
        end_revision)
293
 
 
294
 
    # Decide how file-ids are matched: delta-filtering vs per-file graph.
295
 
    # Delta filtering allows revisions to be displayed incrementally
296
 
    # though the total time is much slower for huge repositories: log -v
297
 
    # is the *lower* performance bound. At least until the split
298
 
    # inventory format arrives, per-file-graph needs to remain the
299
 
    # default except in verbose mode. Delta filtering should give more
300
 
    # accurate results (e.g. inclusion of FILE deletions) so arguably
301
 
    # it should always be used in the future.
302
 
    use_deltas_for_matching = specific_fileid and generate_delta
303
 
    delayed_graph_generation = not specific_fileid and (
304
 
            start_rev_id or end_rev_id or limited_output)
305
 
    generate_merges = generate_merge_revisions or (specific_fileid and
306
 
        not use_deltas_for_matching)
307
 
    view_revisions = _calc_view_revisions(branch, start_rev_id, end_rev_id,
308
 
        direction, generate_merges, allow_single_merge_revision,
309
 
        delayed_graph_generation=delayed_graph_generation)
310
 
    search_deltas_for_fileids = None
311
 
    if use_deltas_for_matching:
312
 
        search_deltas_for_fileids = set([specific_fileid])
313
 
    elif specific_fileid:
 
372
class _DefaultLogGenerator(LogGenerator):
 
373
    """The default generator of log revisions."""
 
374
 
 
375
    def __init__(self, branch, rqst):
 
376
        self.branch = branch
 
377
        self.rqst = rqst
 
378
        if rqst.get('generate_tags') and branch.supports_tags():
 
379
            self.rev_tag_dict = branch.tags.get_reverse_tag_dict()
 
380
        else:
 
381
            self.rev_tag_dict = {}
 
382
 
 
383
    def iter_log_revisions(self):
 
384
        """Iterate over LogRevision objects.
 
385
 
 
386
        :return: An iterator yielding LogRevision objects.
 
387
        """
 
388
        rqst = self.rqst
 
389
        log_count = 0
 
390
        revision_iterator = self._create_log_revision_iterator()
 
391
        for revs in revision_iterator:
 
392
            for (rev_id, revno, merge_depth), rev, delta in revs:
 
393
                # 0 levels means show everything; merge_depth counts from 0
 
394
                levels = rqst.get('levels')
 
395
                if levels != 0 and merge_depth >= levels:
 
396
                    continue
 
397
                diff = self._format_diff(rev, rev_id)
 
398
                yield LogRevision(rev, revno, merge_depth, delta,
 
399
                    self.rev_tag_dict.get(rev_id), diff)
 
400
                limit = rqst.get('limit')
 
401
                if limit:
 
402
                    log_count += 1
 
403
                    if log_count >= limit:
 
404
                        return
 
405
 
 
406
    def _format_diff(self, rev, rev_id):
 
407
        diff_type = self.rqst.get('diff_type')
 
408
        if diff_type is None:
 
409
            return None
 
410
        repo = self.branch.repository
 
411
        if len(rev.parent_ids) == 0:
 
412
            ancestor_id = _mod_revision.NULL_REVISION
 
413
        else:
 
414
            ancestor_id = rev.parent_ids[0]
 
415
        tree_1 = repo.revision_tree(ancestor_id)
 
416
        tree_2 = repo.revision_tree(rev_id)
 
417
        file_ids = self.rqst.get('specific_fileids')
 
418
        if diff_type == 'partial' and file_ids is not None:
 
419
            specific_files = [tree_2.id2path(id) for id in file_ids]
 
420
        else:
 
421
            specific_files = None
 
422
        s = StringIO()
 
423
        diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
 
424
            new_label='')
 
425
        return s.getvalue()
 
426
 
 
427
    def _create_log_revision_iterator(self):
 
428
        """Create a revision iterator for log.
 
429
 
 
430
        :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
431
            delta).
 
432
        """
 
433
        self.start_rev_id, self.end_rev_id = _get_revision_limits(
 
434
            self.branch, self.rqst.get('start_revision'),
 
435
            self.rqst.get('end_revision'))
 
436
        if self.rqst.get('_match_using_deltas'):
 
437
            return self._log_revision_iterator_using_delta_matching()
 
438
        else:
 
439
            # We're using the per-file-graph algorithm. This scales really
 
440
            # well but only makes sense if there is a single file and it's
 
441
            # not a directory
 
442
            file_count = len(self.rqst.get('specific_fileids'))
 
443
            if file_count != 1:
 
444
                raise BzrError("illegal LogRequest: must match-using-deltas "
 
445
                    "when logging %d files" % file_count)
 
446
            return self._log_revision_iterator_using_per_file_graph()
 
447
 
 
448
    def _log_revision_iterator_using_delta_matching(self):
 
449
        # Get the base revisions, filtering by the revision range
 
450
        rqst = self.rqst
 
451
        generate_merge_revisions = rqst.get('levels') != 1
 
452
        delayed_graph_generation = not rqst.get('specific_fileids') and (
 
453
                rqst.get('limit') or self.start_rev_id or self.end_rev_id)
 
454
        view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
 
455
            self.end_rev_id, rqst.get('direction'), generate_merge_revisions,
 
456
            rqst.get('_allow_single_merge_revision'),
 
457
            delayed_graph_generation=delayed_graph_generation)
 
458
 
 
459
        # Apply the other filters
 
460
        return make_log_rev_iterator(self.branch, view_revisions,
 
461
            rqst.get('delta_type'), rqst.get('message_search'),
 
462
            file_ids=rqst.get('specific_fileids'),
 
463
            direction=rqst.get('direction'))
 
464
 
 
465
    def _log_revision_iterator_using_per_file_graph(self):
 
466
        # Get the base revisions, filtering by the revision range.
 
467
        # Note that we always generate the merge revisions because
 
468
        # filter_revisions_touching_file_id() requires them ...
 
469
        rqst = self.rqst
 
470
        view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
 
471
            self.end_rev_id, rqst.get('direction'), True,
 
472
            rqst.get('_allow_single_merge_revision'))
314
473
        if not isinstance(view_revisions, list):
315
474
            view_revisions = list(view_revisions)
316
 
        view_revisions = _filter_revisions_touching_file_id(branch,
317
 
            specific_fileid, view_revisions,
318
 
            include_merges=generate_merge_revisions)
319
 
    return make_log_rev_iterator(branch, view_revisions, generate_delta,
320
 
        search, file_ids=search_deltas_for_fileids, direction=direction)
 
475
        view_revisions = _filter_revisions_touching_file_id(self.branch,
 
476
            rqst.get('specific_fileids')[0], view_revisions,
 
477
            include_merges=rqst.get('levels') != 1)
 
478
        return make_log_rev_iterator(self.branch, view_revisions,
 
479
            rqst.get('delta_type'), rqst.get('message_search'))
321
480
 
322
481
 
323
482
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
336
495
    generate_single_revision = (end_rev_id and start_rev_id == end_rev_id and
337
496
        (not generate_merge_revisions or not _has_merges(branch, end_rev_id)))
338
497
    if generate_single_revision:
339
 
        if end_rev_id == br_rev_id:
340
 
            # It's the tip
341
 
            return [(br_rev_id, br_revno, 0)]
342
 
        else:
343
 
            revno = branch.revision_id_to_dotted_revno(end_rev_id)
344
 
            if len(revno) > 1 and not allow_single_merge_revision:
345
 
                # It's a merge revision and the log formatter is
346
 
                # completely brain dead. This "feature" of allowing
347
 
                # log formatters incapable of displaying dotted revnos
348
 
                # ought to be deprecated IMNSHO. IGC 20091022
349
 
                raise errors.BzrCommandError('Selected log formatter only'
350
 
                    ' supports mainline revisions.')
351
 
            revno_str = '.'.join(str(n) for n in revno)
352
 
            return [(end_rev_id, revno_str, 0)]
 
498
        return _generate_one_revision(branch, end_rev_id, br_rev_id, br_revno,
 
499
            allow_single_merge_revision)
353
500
 
354
501
    # If we only want to see linear revisions, we can iterate ...
355
502
    if not generate_merge_revisions:
356
 
        result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
357
 
        # If a start limit was given and it's not obviously an
358
 
        # ancestor of the end limit, check it before outputting anything
359
 
        if direction == 'forward' or (start_rev_id
360
 
            and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
361
 
            try:
362
 
                result = list(result)
363
 
            except _StartNotLinearAncestor:
364
 
                raise errors.BzrCommandError('Start revision not found in'
365
 
                    ' left-hand history of end revision.')
366
 
        if direction == 'forward':
367
 
            result = reversed(list(result))
368
 
        return result
369
 
 
 
503
        return _generate_flat_revisions(branch, start_rev_id, end_rev_id,
 
504
            direction)
 
505
    else:
 
506
        return _generate_all_revisions(branch, start_rev_id, end_rev_id,
 
507
            direction, delayed_graph_generation)
 
508
 
 
509
 
 
510
def _generate_one_revision(branch, rev_id, br_rev_id, br_revno,
 
511
    allow_single_merge_revision):
 
512
    if rev_id == br_rev_id:
 
513
        # It's the tip
 
514
        return [(br_rev_id, br_revno, 0)]
 
515
    else:
 
516
        revno = branch.revision_id_to_dotted_revno(rev_id)
 
517
        if len(revno) > 1 and not allow_single_merge_revision:
 
518
            # It's a merge revision and the log formatter is
 
519
            # completely brain dead. This "feature" of allowing
 
520
            # log formatters incapable of displaying dotted revnos
 
521
            # ought to be deprecated IMNSHO. IGC 20091022
 
522
            raise errors.BzrCommandError('Selected log formatter only'
 
523
                ' supports mainline revisions.')
 
524
        revno_str = '.'.join(str(n) for n in revno)
 
525
        return [(rev_id, revno_str, 0)]
 
526
 
 
527
 
 
528
def _generate_flat_revisions(branch, start_rev_id, end_rev_id, direction):
 
529
    result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
 
530
    # If a start limit was given and it's not obviously an
 
531
    # ancestor of the end limit, check it before outputting anything
 
532
    if direction == 'forward' or (start_rev_id
 
533
        and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
 
534
        try:
 
535
            result = list(result)
 
536
        except _StartNotLinearAncestor:
 
537
            raise errors.BzrCommandError('Start revision not found in'
 
538
                ' left-hand history of end revision.')
 
539
    if direction == 'forward':
 
540
        result = reversed(result)
 
541
    return result
 
542
 
 
543
 
 
544
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
 
545
    delayed_graph_generation):
370
546
    # On large trees, generating the merge graph can take 30-60 seconds
371
547
    # so we delay doing it until a merge is detected, incrementally
372
548
    # returning initial (non-merge) revisions while we can.
544
720
    :param branch: The branch being logged.
545
721
    :param view_revisions: The revisions being viewed.
546
722
    :param generate_delta: Whether to generate a delta for each revision.
 
723
      Permitted values are None, 'full' and 'partial'.
547
724
    :param search: A user text search string.
548
725
    :param file_ids: If non empty, only revisions matching one or more of
549
726
      the file-ids are to be kept.
608
785
 
609
786
    :param branch: The branch being logged.
610
787
    :param generate_delta: Whether to generate a delta for each revision.
 
788
      Permitted values are None, 'full' and 'partial'.
611
789
    :param search: A user text search string.
612
790
    :param log_rev_iterator: An input iterator containing all revisions that
613
791
        could be displayed, in lists.
623
801
        generate_delta, fileids, direction)
624
802
 
625
803
 
626
 
def _generate_deltas(repository, log_rev_iterator, always_delta, fileids,
 
804
def _generate_deltas(repository, log_rev_iterator, delta_type, fileids,
627
805
    direction):
628
806
    """Create deltas for each batch of revisions in log_rev_iterator.
629
807
 
647
825
        if check_fileids and not fileid_set:
648
826
            return
649
827
        revisions = [rev[1] for rev in revs]
650
 
        deltas = repository.get_deltas_for_revisions(revisions)
651
828
        new_revs = []
652
 
        for rev, delta in izip(revs, deltas):
653
 
            if check_fileids:
654
 
                if not _delta_matches_fileids(delta, fileid_set, stop_on):
655
 
                    continue
656
 
                elif not always_delta:
657
 
                    # Delta was created just for matching - ditch it
658
 
                    # Note: It would probably be a better UI to return
659
 
                    # a delta filtered by the file-ids, rather than
660
 
                    # None at all. That functional enhancement can
661
 
                    # come later ...
662
 
                    delta = None
663
 
            new_revs.append((rev[0], rev[1], delta))
 
829
        if delta_type == 'full' and not check_fileids:
 
830
            deltas = repository.get_deltas_for_revisions(revisions)
 
831
            for rev, delta in izip(revs, deltas):
 
832
                new_revs.append((rev[0], rev[1], delta))
 
833
        else:
 
834
            deltas = repository.get_deltas_for_revisions(revisions, fileid_set)
 
835
            for rev, delta in izip(revs, deltas):
 
836
                if check_fileids:
 
837
                    if delta is None or not delta.has_changed():
 
838
                        continue
 
839
                    else:
 
840
                        _update_fileids(delta, fileid_set, stop_on)
 
841
                        if delta_type is None:
 
842
                            delta = None
 
843
                        elif delta_type == 'full':
 
844
                            # If the file matches all the time, rebuilding
 
845
                            # a full delta like this in addition to a partial
 
846
                            # one could be slow. However, it's likely that
 
847
                            # most revisions won't get this far, making it
 
848
                            # faster to filter on the partial deltas and
 
849
                            # build the occasional full delta than always
 
850
                            # building full deltas and filtering those.
 
851
                            rev_id = rev[0][0]
 
852
                            delta = repository.get_revision_delta(rev_id)
 
853
                new_revs.append((rev[0], rev[1], delta))
664
854
        yield new_revs
665
855
 
666
856
 
667
 
def _delta_matches_fileids(delta, fileids, stop_on='add'):
668
 
    """Check is a delta matches one of more file-ids.
669
 
 
670
 
    :param fileids: a set of fileids to match against.
 
857
def _update_fileids(delta, fileids, stop_on):
 
858
    """Update the set of file-ids to search based on file lifecycle events.
 
859
    
 
860
    :param fileids: a set of fileids to update
671
861
    :param stop_on: either 'add' or 'remove' - take file-ids out of the
672
862
      fileids set once their add or remove entry is detected respectively
673
863
    """
674
 
    if not fileids:
675
 
        return False
676
 
    result = False
677
 
    for item in delta.added:
678
 
        if item[1] in fileids:
679
 
            if stop_on == 'add':
680
 
                fileids.remove(item[1])
681
 
            result = True
682
 
    for item in delta.removed:
683
 
        if item[1] in fileids:
684
 
            if stop_on == 'delete':
685
 
                fileids.remove(item[1])
686
 
            result = True
687
 
    if result:
688
 
        return True
689
 
    for l in (delta.modified, delta.renamed, delta.kind_changed):
690
 
        for item in l:
691
 
            if item[1] in fileids:
692
 
                return True
693
 
    return False
 
864
    if stop_on == 'add':
 
865
        for item in delta.added:
 
866
            if item[1] in fileids:
 
867
                fileids.remove(item[1])
 
868
    elif stop_on == 'delete':
 
869
        for item in delta.removed:
 
870
            if item[1] in fileids:
 
871
                fileids.remove(item[1])
694
872
 
695
873
 
696
874
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
1617
1795
        lf.log_revision(lr)
1618
1796
 
1619
1797
 
1620
 
def _get_fileid_to_log(revision, tree, b, fp):
1621
 
    """Find the file-id to log for a file path in a revision range.
1622
 
 
1623
 
    :param revision: the revision range as parsed on the command line
1624
 
    :param tree: the working tree, if any
1625
 
    :param b: the branch
1626
 
    :param fp: file path
 
1798
def _get_info_for_log_files(revisionspec_list, file_list):
 
1799
    """Find file-ids and kinds given a list of files and a revision range.
 
1800
 
 
1801
    We search for files at the end of the range. If not found there,
 
1802
    we try the start of the range.
 
1803
 
 
1804
    :param revisionspec_list: revision range as parsed on the command line
 
1805
    :param file_list: the list of paths given on the command line;
 
1806
      the first of these can be a branch location or a file path,
 
1807
      the remainder must be file paths
 
1808
    :return: (branch, info_list, start_rev_info, end_rev_info) where
 
1809
      info_list is a list of (relative_path, file_id, kind) tuples where
 
1810
      kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
1627
1811
    """
1628
 
    if revision is None:
 
1812
    from builtins import _get_revision_range, safe_relpath_files
 
1813
    tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
 
1814
    # XXX: It's damn messy converting a list of paths to relative paths when
 
1815
    # those paths might be deleted ones, they might be on a case-insensitive
 
1816
    # filesystem and/or they might be in silly locations (like another branch).
 
1817
    # For example, what should "log bzr://branch/dir/file1 file2" do? (Is
 
1818
    # file2 implicitly in the same dir as file1 or should its directory be
 
1819
    # taken from the current tree somehow?) For now, this solves the common
 
1820
    # case of running log in a nested directory, assuming paths beyond the
 
1821
    # first one haven't been deleted ...
 
1822
    if tree:
 
1823
        relpaths = [path] + safe_relpath_files(tree, file_list[1:])
 
1824
    else:
 
1825
        relpaths = [path] + file_list[1:]
 
1826
    info_list = []
 
1827
    start_rev_info, end_rev_info = _get_revision_range(revisionspec_list, b,
 
1828
        "log")
 
1829
    if start_rev_info is None and end_rev_info is None:
1629
1830
        if tree is None:
1630
1831
            tree = b.basis_tree()
1631
 
        file_id = tree.path2id(fp)
1632
 
        if file_id is None:
1633
 
            # go back to when time began
1634
 
            try:
1635
 
                rev1 = b.get_rev_id(1)
1636
 
            except errors.NoSuchRevision:
1637
 
                # No history at all
1638
 
                file_id = None
1639
 
            else:
1640
 
                tree = b.repository.revision_tree(rev1)
1641
 
                file_id = tree.path2id(fp)
 
1832
        tree1 = None
 
1833
        for fp in relpaths:
 
1834
            file_id = tree.path2id(fp)
 
1835
            kind = _get_kind_for_file_id(tree, file_id)
 
1836
            if file_id is None:
 
1837
                # go back to when time began
 
1838
                if tree1 is None:
 
1839
                    try:
 
1840
                        rev1 = b.get_rev_id(1)
 
1841
                    except errors.NoSuchRevision:
 
1842
                        # No history at all
 
1843
                        file_id = None
 
1844
                        kind = None
 
1845
                    else:
 
1846
                        tree1 = b.repository.revision_tree(rev1)
 
1847
                if tree1:
 
1848
                    file_id = tree1.path2id(fp)
 
1849
                    kind = _get_kind_for_file_id(tree1, file_id)
 
1850
            info_list.append((fp, file_id, kind))
1642
1851
 
1643
 
    elif len(revision) == 1:
 
1852
    elif start_rev_info == end_rev_info:
1644
1853
        # One revision given - file must exist in it
1645
 
        tree = revision[0].as_tree(b)
1646
 
        file_id = tree.path2id(fp)
 
1854
        tree = b.repository.revision_tree(end_rev_info.rev_id)
 
1855
        for fp in relpaths:
 
1856
            file_id = tree.path2id(fp)
 
1857
            kind = _get_kind_for_file_id(tree, file_id)
 
1858
            info_list.append((fp, file_id, kind))
1647
1859
 
1648
 
    elif len(revision) == 2:
 
1860
    else:
1649
1861
        # Revision range given. Get the file-id from the end tree.
1650
1862
        # If that fails, try the start tree.
1651
 
        rev_id = revision[1].as_revision_id(b)
 
1863
        rev_id = end_rev_info.rev_id
1652
1864
        if rev_id is None:
1653
1865
            tree = b.basis_tree()
1654
1866
        else:
1655
 
            tree = revision[1].as_tree(b)
1656
 
        file_id = tree.path2id(fp)
1657
 
        if file_id is None:
1658
 
            rev_id = revision[0].as_revision_id(b)
1659
 
            if rev_id is None:
1660
 
                rev1 = b.get_rev_id(1)
1661
 
                tree = b.repository.revision_tree(rev1)
1662
 
            else:
1663
 
                tree = revision[0].as_tree(b)
 
1867
            tree = b.repository.revision_tree(rev_id)
 
1868
        tree1 = None
 
1869
        for fp in relpaths:
1664
1870
            file_id = tree.path2id(fp)
 
1871
            kind = _get_kind_for_file_id(tree, file_id)
 
1872
            if file_id is None:
 
1873
                if tree1 is None:
 
1874
                    rev_id = start_rev_info.rev_id
 
1875
                    if rev_id is None:
 
1876
                        rev1 = b.get_rev_id(1)
 
1877
                        tree1 = b.repository.revision_tree(rev1)
 
1878
                    else:
 
1879
                        tree1 = b.repository.revision_tree(rev_id)
 
1880
                file_id = tree1.path2id(fp)
 
1881
                kind = _get_kind_for_file_id(tree1, file_id)
 
1882
            info_list.append((fp, file_id, kind))
 
1883
    return b, info_list, start_rev_info, end_rev_info
 
1884
 
 
1885
 
 
1886
def _get_kind_for_file_id(tree, file_id):
 
1887
    """Return the kind of a file-id or None if it doesn't exist."""
 
1888
    if file_id is not None:
 
1889
        return tree.kind(file_id)
1665
1890
    else:
1666
 
        raise errors.BzrCommandError(
1667
 
            'bzr log --revision takes one or two values.')
1668
 
    return file_id
 
1891
        return None
1669
1892
 
1670
1893
 
1671
1894
properties_handler_registry = registry.Registry()