~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/log.py

  • Committer: Matt Nordhoff
  • Date: 2009-04-04 02:50:01 UTC
  • mfrom: (4253 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4256.
  • Revision ID: mnordhoff@mattnordhoff.com-20090404025001-z1403k0tatmc8l91
Merge bzr.dev, fixing conflicts.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
18
18
 
65
65
lazy_import(globals(), """
66
66
 
67
67
from bzrlib import (
 
68
    bzrdir,
68
69
    config,
69
70
    diff,
70
71
    errors,
82
83
from bzrlib.osutils import (
83
84
    format_date,
84
85
    get_terminal_encoding,
 
86
    re_compile_checked,
85
87
    terminal_width,
86
88
    )
87
89
 
151
153
             show_diff=False):
152
154
    """Write out human-readable log of commits to this branch.
153
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
 
154
161
    :param lf: The LogFormatter object showing the output.
155
162
 
156
163
    :param specific_fileid: If not None, list only the commits affecting the
173
180
 
174
181
    :param show_diff: If True, output a diff after each revision.
175
182
    """
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, show_diff)
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
 
             show_diff=False):
200
 
    """Worker function for show_log - see show_log."""
201
 
    if not isinstance(lf, LogFormatter):
202
 
        warn("not a LogFormatter instance: %r" % lf)
203
 
    if specific_fileid:
204
 
        trace.mutter('get log for file_id %r', specific_fileid)
205
 
 
206
 
    # Consult the LogFormatter about what it needs and can handle
207
 
    levels_to_display = lf.get_levels()
208
 
    generate_merge_revisions = levels_to_display != 1
209
 
    allow_single_merge_revision = True
210
 
    if not getattr(lf, 'supports_merge_revisions', False):
211
 
        allow_single_merge_revision = getattr(lf,
212
 
            'supports_single_merge_revision', False)
213
 
    generate_tags = getattr(lf, 'supports_tags', False)
214
 
    if generate_tags and branch.supports_tags():
215
 
        rev_tag_dict = branch.tags.get_reverse_tag_dict()
216
 
    else:
217
 
        rev_tag_dict = {}
218
 
    generate_delta = verbose and getattr(lf, 'supports_delta', False)
219
 
    generate_diff = show_diff and getattr(lf, 'supports_diff', False)
220
 
 
221
 
    # Find and print the interesting revisions
222
 
    repo = branch.repository
223
 
    log_count = 0
224
 
    revision_iterator = _create_log_revision_iterator(branch,
225
 
        start_revision, end_revision, direction, specific_fileid, search,
226
 
        generate_merge_revisions, allow_single_merge_revision,
227
 
        generate_delta, limited_output=limit > 0)
228
 
    for revs in revision_iterator:
229
 
        for (rev_id, revno, merge_depth), rev, delta in revs:
230
 
            # Note: 0 levels means show everything; merge_depth counts from 0
231
 
            if levels_to_display != 0 and merge_depth >= levels_to_display:
232
 
                continue
233
 
            if generate_diff:
234
 
                diff = _format_diff(repo, rev, rev_id, specific_fileid)
235
 
            else:
236
 
                diff = None
237
 
            lr = LogRevision(rev, revno, merge_depth, delta,
238
 
                             rev_tag_dict.get(rev_id), diff)
 
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
    }
 
283
 
 
284
 
 
285
def _apply_log_request_defaults(rqst):
 
286
    """Apply default values to a request dictionary."""
 
287
    result = _DEFAULT_REQUEST_PARAMS
 
288
    if rqst:
 
289
        result.update(rqst)
 
290
    return result
 
291
 
 
292
 
 
293
class LogGenerator(object):
 
294
    """A generator of log revisions."""
 
295
 
 
296
    def iter_log_revisions(self):
 
297
        """Iterate over LogRevision objects.
 
298
 
 
299
        :return: An iterator yielding LogRevision objects.
 
300
        """
 
301
        raise NotImplementedError(self.iter_log_revisions)
 
302
 
 
303
 
 
304
class Logger(object):
 
305
    """An object the generates, formats and displays a log."""
 
306
 
 
307
    def __init__(self, branch, rqst):
 
308
        """Create a Logger.
 
309
 
 
310
        :param branch: the branch to log
 
311
        :param rqst: A dictionary specifying the query parameters.
 
312
          See make_log_request_dict() for supported values.
 
313
        """
 
314
        self.branch = branch
 
315
        self.rqst = _apply_log_request_defaults(rqst)
 
316
 
 
317
    def show(self, lf):
 
318
        """Display the log.
 
319
 
 
320
        :param lf: The LogFormatter object to send the output to.
 
321
        """
 
322
        if not isinstance(lf, LogFormatter):
 
323
            warn("not a LogFormatter instance: %r" % lf)
 
324
 
 
325
        self.branch.lock_read()
 
326
        try:
 
327
            if getattr(lf, 'begin_log', None):
 
328
                lf.begin_log()
 
329
            self._show_body(lf)
 
330
            if getattr(lf, 'end_log', None):
 
331
                lf.end_log()
 
332
        finally:
 
333
            self.branch.unlock()
 
334
 
 
335
    def _show_body(self, lf):
 
336
        """Show the main log output.
 
337
 
 
338
        Subclasses may wish to override this.
 
339
        """
 
340
        # Tweak the LogRequest based on what the LogFormatter can handle.
 
341
        # (There's no point generating stuff if the formatter can't display it.)
 
342
        rqst = self.rqst
 
343
        rqst['levels'] = lf.get_levels()
 
344
        if not getattr(lf, 'supports_tags', False):
 
345
            rqst['generate_tags'] = False
 
346
        if not getattr(lf, 'supports_delta', False):
 
347
            rqst['delta_type'] = None
 
348
        if not getattr(lf, 'supports_diff', False):
 
349
            rqst['diff_type'] = None
 
350
 
 
351
        # Find and print the interesting revisions
 
352
        generator = self._generator_factory(self.branch, rqst)
 
353
        for lr in generator.iter_log_revisions():
239
354
            lf.log_revision(lr)
240
 
            if limit:
241
 
                log_count += 1
242
 
                if log_count >= limit:
243
 
                    return
244
 
 
245
 
 
246
 
def _format_diff(repo, rev, rev_id, specific_fileid):
247
 
    if len(rev.parent_ids) == 0:
248
 
        ancestor_id = _mod_revision.NULL_REVISION
249
 
    else:
250
 
        ancestor_id = rev.parent_ids[0]
251
 
    tree_1 = repo.revision_tree(ancestor_id)
252
 
    tree_2 = repo.revision_tree(rev_id)
253
 
    if specific_fileid:
254
 
        specific_files = [tree_2.id2path(specific_fileid)]
255
 
    else:
256
 
        specific_files = None
257
 
    s = StringIO()
258
 
    diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
259
 
        new_label='')
260
 
    return s.getvalue()
 
355
        lf.show_advice()
 
356
 
 
357
    def _generator_factory(self, branch, rqst):
 
358
        """Make the LogGenerator object to use.
 
359
        
 
360
        Subclasses may wish to override this.
 
361
        """
 
362
        return _DefaultLogGenerator(branch, rqst)
261
363
 
262
364
 
263
365
class _StartNotLinearAncestor(Exception):
264
366
    """Raised when a start revision is not found walking left-hand history."""
265
367
 
266
368
 
267
 
def _create_log_revision_iterator(branch, start_revision, end_revision,
268
 
    direction, specific_fileid, search, generate_merge_revisions,
269
 
    allow_single_merge_revision, generate_delta, limited_output=False):
270
 
    """Create a revision iterator for log.
271
 
 
272
 
    :param branch: The branch being logged.
273
 
    :param start_revision: If not None, only show revisions >= start_revision
274
 
    :param end_revision: If not None, only show revisions <= end_revision
275
 
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
276
 
        earliest to latest.
277
 
    :param specific_fileid: If not None, list only the commits affecting the
278
 
        specified file.
279
 
    :param search: If not None, only show revisions with matching commit
280
 
        messages.
281
 
    :param generate_merge_revisions: If False, show only mainline revisions.
282
 
    :param allow_single_merge_revision: If True, logging of a single
283
 
        revision off the mainline is to be allowed
284
 
    :param generate_delta: Whether to generate a delta for each revision.
285
 
    :param limited_output: if True, the user only wants a limited result
286
 
 
287
 
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
288
 
        delta).
289
 
    """
290
 
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
291
 
        end_revision)
292
 
 
293
 
    # Decide how file-ids are matched: delta-filtering vs per-file graph.
294
 
    # Delta filtering allows revisions to be displayed incrementally
295
 
    # though the total time is much slower for huge repositories: log -v
296
 
    # is the *lower* performance bound. At least until the split
297
 
    # inventory format arrives, per-file-graph needs to remain the
298
 
    # default except in verbose mode. Delta filtering should give more
299
 
    # accurate results (e.g. inclusion of FILE deletions) so arguably
300
 
    # it should always be used in the future.
301
 
    use_deltas_for_matching = specific_fileid and generate_delta
302
 
    delayed_graph_generation = not specific_fileid and (
303
 
            start_rev_id or end_rev_id or limited_output)
304
 
    generate_merges = generate_merge_revisions or (specific_fileid and
305
 
        not use_deltas_for_matching)
306
 
    view_revisions = _calc_view_revisions(branch, start_rev_id, end_rev_id,
307
 
        direction, generate_merges, allow_single_merge_revision,
308
 
        delayed_graph_generation=delayed_graph_generation)
309
 
    search_deltas_for_fileids = None
310
 
    if use_deltas_for_matching:
311
 
        search_deltas_for_fileids = set([specific_fileid])
312
 
    elif specific_fileid:
 
369
class _DefaultLogGenerator(LogGenerator):
 
370
    """The default generator of log revisions."""
 
371
 
 
372
    def __init__(self, branch, rqst):
 
373
        self.branch = branch
 
374
        self.rqst = rqst
 
375
        if rqst.get('generate_tags') and branch.supports_tags():
 
376
            self.rev_tag_dict = branch.tags.get_reverse_tag_dict()
 
377
        else:
 
378
            self.rev_tag_dict = {}
 
379
 
 
380
    def iter_log_revisions(self):
 
381
        """Iterate over LogRevision objects.
 
382
 
 
383
        :return: An iterator yielding LogRevision objects.
 
384
        """
 
385
        rqst = self.rqst
 
386
        log_count = 0
 
387
        revision_iterator = self._create_log_revision_iterator()
 
388
        for revs in revision_iterator:
 
389
            for (rev_id, revno, merge_depth), rev, delta in revs:
 
390
                # 0 levels means show everything; merge_depth counts from 0
 
391
                levels = rqst.get('levels')
 
392
                if levels != 0 and merge_depth >= levels:
 
393
                    continue
 
394
                diff = self._format_diff(rev, rev_id)
 
395
                yield LogRevision(rev, revno, merge_depth, delta,
 
396
                    self.rev_tag_dict.get(rev_id), diff)
 
397
                limit = rqst.get('limit')
 
398
                if limit:
 
399
                    log_count += 1
 
400
                    if log_count >= limit:
 
401
                        return
 
402
 
 
403
    def _format_diff(self, rev, rev_id):
 
404
        diff_type = self.rqst.get('diff_type')
 
405
        if diff_type is None:
 
406
            return None
 
407
        repo = self.branch.repository
 
408
        if len(rev.parent_ids) == 0:
 
409
            ancestor_id = _mod_revision.NULL_REVISION
 
410
        else:
 
411
            ancestor_id = rev.parent_ids[0]
 
412
        tree_1 = repo.revision_tree(ancestor_id)
 
413
        tree_2 = repo.revision_tree(rev_id)
 
414
        file_ids = self.rqst.get('specific_fileids')
 
415
        if diff_type == 'partial' and file_ids is not None:
 
416
            specific_files = [tree_2.id2path(id) for id in file_ids]
 
417
        else:
 
418
            specific_files = None
 
419
        s = StringIO()
 
420
        diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
 
421
            new_label='')
 
422
        return s.getvalue()
 
423
 
 
424
    def _create_log_revision_iterator(self):
 
425
        """Create a revision iterator for log.
 
426
 
 
427
        :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
428
            delta).
 
429
        """
 
430
        self.start_rev_id, self.end_rev_id = _get_revision_limits(
 
431
            self.branch, self.rqst.get('start_revision'),
 
432
            self.rqst.get('end_revision'))
 
433
        if self.rqst.get('_match_using_deltas'):
 
434
            return self._log_revision_iterator_using_delta_matching()
 
435
        else:
 
436
            # We're using the per-file-graph algorithm. This scales really
 
437
            # well but only makes sense if there is a single file and it's
 
438
            # not a directory
 
439
            file_count = len(self.rqst.get('specific_fileids'))
 
440
            if file_count != 1:
 
441
                raise BzrError("illegal LogRequest: must match-using-deltas "
 
442
                    "when logging %d files" % file_count)
 
443
            return self._log_revision_iterator_using_per_file_graph()
 
444
 
 
445
    def _log_revision_iterator_using_delta_matching(self):
 
446
        # Get the base revisions, filtering by the revision range
 
447
        rqst = self.rqst
 
448
        generate_merge_revisions = rqst.get('levels') != 1
 
449
        delayed_graph_generation = not rqst.get('specific_fileids') and (
 
450
                rqst.get('limit') or self.start_rev_id or self.end_rev_id)
 
451
        view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
 
452
            self.end_rev_id, rqst.get('direction'), generate_merge_revisions,
 
453
            delayed_graph_generation=delayed_graph_generation)
 
454
 
 
455
        # Apply the other filters
 
456
        return make_log_rev_iterator(self.branch, view_revisions,
 
457
            rqst.get('delta_type'), rqst.get('message_search'),
 
458
            file_ids=rqst.get('specific_fileids'),
 
459
            direction=rqst.get('direction'))
 
460
 
 
461
    def _log_revision_iterator_using_per_file_graph(self):
 
462
        # Get the base revisions, filtering by the revision range.
 
463
        # Note that we always generate the merge revisions because
 
464
        # filter_revisions_touching_file_id() requires them ...
 
465
        rqst = self.rqst
 
466
        view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
 
467
            self.end_rev_id, rqst.get('direction'), True)
313
468
        if not isinstance(view_revisions, list):
314
469
            view_revisions = list(view_revisions)
315
 
        view_revisions = _filter_revisions_touching_file_id(branch,
316
 
            specific_fileid, view_revisions,
317
 
            include_merges=generate_merge_revisions)
318
 
    return make_log_rev_iterator(branch, view_revisions, generate_delta,
319
 
        search, file_ids=search_deltas_for_fileids, direction=direction)
 
470
        view_revisions = _filter_revisions_touching_file_id(self.branch,
 
471
            rqst.get('specific_fileids')[0], view_revisions,
 
472
            include_merges=rqst.get('levels') != 1)
 
473
        return make_log_rev_iterator(self.branch, view_revisions,
 
474
            rqst.get('delta_type'), rqst.get('message_search'))
320
475
 
321
476
 
322
477
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
323
 
    generate_merge_revisions, allow_single_merge_revision,
324
 
    delayed_graph_generation=False):
 
478
    generate_merge_revisions, delayed_graph_generation=False):
325
479
    """Calculate the revisions to view.
326
480
 
327
481
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
335
489
    generate_single_revision = (end_rev_id and start_rev_id == end_rev_id and
336
490
        (not generate_merge_revisions or not _has_merges(branch, end_rev_id)))
337
491
    if generate_single_revision:
338
 
        if end_rev_id == br_rev_id:
339
 
            # It's the tip
340
 
            return [(br_rev_id, br_revno, 0)]
341
 
        else:
342
 
            revno = branch.revision_id_to_dotted_revno(end_rev_id)
343
 
            if len(revno) > 1 and not allow_single_merge_revision:
344
 
                # It's a merge revision and the log formatter is
345
 
                # completely brain dead. This "feature" of allowing
346
 
                # log formatters incapable of displaying dotted revnos
347
 
                # ought to be deprecated IMNSHO. IGC 20091022
348
 
                raise errors.BzrCommandError('Selected log formatter only'
349
 
                    ' supports mainline revisions.')
350
 
            revno_str = '.'.join(str(n) for n in revno)
351
 
            return [(end_rev_id, revno_str, 0)]
 
492
        return _generate_one_revision(branch, end_rev_id, br_rev_id, br_revno)
352
493
 
353
494
    # If we only want to see linear revisions, we can iterate ...
354
495
    if not generate_merge_revisions:
355
 
        result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
356
 
        # If a start limit was given and it's not obviously an
357
 
        # ancestor of the end limit, check it before outputting anything
358
 
        if direction == 'forward' or (start_rev_id
359
 
            and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
360
 
            try:
361
 
                result = list(result)
362
 
            except _StartNotLinearAncestor:
363
 
                raise errors.BzrCommandError('Start revision not found in'
364
 
                    ' left-hand history of end revision.')
365
 
        if direction == 'forward':
366
 
            result = reversed(list(result))
367
 
        return result
368
 
 
 
496
        return _generate_flat_revisions(branch, start_rev_id, end_rev_id,
 
497
            direction)
 
498
    else:
 
499
        return _generate_all_revisions(branch, start_rev_id, end_rev_id,
 
500
            direction, delayed_graph_generation)
 
501
 
 
502
 
 
503
def _generate_one_revision(branch, rev_id, br_rev_id, br_revno):
 
504
    if rev_id == br_rev_id:
 
505
        # It's the tip
 
506
        return [(br_rev_id, br_revno, 0)]
 
507
    else:
 
508
        revno = branch.revision_id_to_dotted_revno(rev_id)
 
509
        revno_str = '.'.join(str(n) for n in revno)
 
510
        return [(rev_id, revno_str, 0)]
 
511
 
 
512
 
 
513
def _generate_flat_revisions(branch, start_rev_id, end_rev_id, direction):
 
514
    result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
 
515
    # If a start limit was given and it's not obviously an
 
516
    # ancestor of the end limit, check it before outputting anything
 
517
    if direction == 'forward' or (start_rev_id
 
518
        and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
 
519
        try:
 
520
            result = list(result)
 
521
        except _StartNotLinearAncestor:
 
522
            raise errors.BzrCommandError('Start revision not found in'
 
523
                ' left-hand history of end revision.')
 
524
    if direction == 'forward':
 
525
        result = reversed(result)
 
526
    return result
 
527
 
 
528
 
 
529
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
 
530
    delayed_graph_generation):
369
531
    # On large trees, generating the merge graph can take 30-60 seconds
370
532
    # so we delay doing it until a merge is detected, incrementally
371
533
    # returning initial (non-merge) revisions while we can.
505
667
 
506
668
 
507
669
def calculate_view_revisions(branch, start_revision, end_revision, direction,
508
 
        specific_fileid, generate_merge_revisions, allow_single_merge_revision):
 
670
        specific_fileid, generate_merge_revisions):
509
671
    """Calculate the revisions to view.
510
672
 
511
673
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
517
679
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
518
680
        end_revision)
519
681
    view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
520
 
        direction, generate_merge_revisions or specific_fileid,
521
 
        allow_single_merge_revision))
 
682
        direction, generate_merge_revisions or specific_fileid))
522
683
    if specific_fileid:
523
684
        view_revisions = _filter_revisions_touching_file_id(branch,
524
685
            specific_fileid, view_revisions,
543
704
    :param branch: The branch being logged.
544
705
    :param view_revisions: The revisions being viewed.
545
706
    :param generate_delta: Whether to generate a delta for each revision.
 
707
      Permitted values are None, 'full' and 'partial'.
546
708
    :param search: A user text search string.
547
709
    :param file_ids: If non empty, only revisions matching one or more of
548
710
      the file-ids are to be kept.
587
749
    """
588
750
    if search is None:
589
751
        return log_rev_iterator
590
 
    # Compile the search now to get early errors.
591
 
    searchRE = re.compile(search, re.IGNORECASE)
 
752
    searchRE = re_compile_checked(search, re.IGNORECASE,
 
753
            'log message filter')
592
754
    return _filter_message_re(searchRE, log_rev_iterator)
593
755
 
594
756
 
607
769
 
608
770
    :param branch: The branch being logged.
609
771
    :param generate_delta: Whether to generate a delta for each revision.
 
772
      Permitted values are None, 'full' and 'partial'.
610
773
    :param search: A user text search string.
611
774
    :param log_rev_iterator: An input iterator containing all revisions that
612
775
        could be displayed, in lists.
622
785
        generate_delta, fileids, direction)
623
786
 
624
787
 
625
 
def _generate_deltas(repository, log_rev_iterator, always_delta, fileids,
 
788
def _generate_deltas(repository, log_rev_iterator, delta_type, fileids,
626
789
    direction):
627
790
    """Create deltas for each batch of revisions in log_rev_iterator.
628
 
    
 
791
 
629
792
    If we're only generating deltas for the sake of filtering against
630
793
    file-ids, we stop generating deltas once all file-ids reach the
631
794
    appropriate life-cycle point. If we're receiving data newest to
646
809
        if check_fileids and not fileid_set:
647
810
            return
648
811
        revisions = [rev[1] for rev in revs]
649
 
        deltas = repository.get_deltas_for_revisions(revisions)
650
812
        new_revs = []
651
 
        for rev, delta in izip(revs, deltas):
652
 
            if check_fileids:
653
 
                if not _delta_matches_fileids(delta, fileid_set, stop_on):
654
 
                    continue
655
 
                elif not always_delta:
656
 
                    # Delta was created just for matching - ditch it
657
 
                    # Note: It would probably be a better UI to return
658
 
                    # a delta filtered by the file-ids, rather than
659
 
                    # None at all. That functional enhancement can
660
 
                    # come later ...
661
 
                    delta = None
662
 
            new_revs.append((rev[0], rev[1], delta))
 
813
        if delta_type == 'full' and not check_fileids:
 
814
            deltas = repository.get_deltas_for_revisions(revisions)
 
815
            for rev, delta in izip(revs, deltas):
 
816
                new_revs.append((rev[0], rev[1], delta))
 
817
        else:
 
818
            deltas = repository.get_deltas_for_revisions(revisions, fileid_set)
 
819
            for rev, delta in izip(revs, deltas):
 
820
                if check_fileids:
 
821
                    if delta is None or not delta.has_changed():
 
822
                        continue
 
823
                    else:
 
824
                        _update_fileids(delta, fileid_set, stop_on)
 
825
                        if delta_type is None:
 
826
                            delta = None
 
827
                        elif delta_type == 'full':
 
828
                            # If the file matches all the time, rebuilding
 
829
                            # a full delta like this in addition to a partial
 
830
                            # one could be slow. However, it's likely that
 
831
                            # most revisions won't get this far, making it
 
832
                            # faster to filter on the partial deltas and
 
833
                            # build the occasional full delta than always
 
834
                            # building full deltas and filtering those.
 
835
                            rev_id = rev[0][0]
 
836
                            delta = repository.get_revision_delta(rev_id)
 
837
                new_revs.append((rev[0], rev[1], delta))
663
838
        yield new_revs
664
839
 
665
840
 
666
 
def _delta_matches_fileids(delta, fileids, stop_on='add'):
667
 
    """Check is a delta matches one of more file-ids.
 
841
def _update_fileids(delta, fileids, stop_on):
 
842
    """Update the set of file-ids to search based on file lifecycle events.
668
843
    
669
 
    :param fileids: a set of fileids to match against.
 
844
    :param fileids: a set of fileids to update
670
845
    :param stop_on: either 'add' or 'remove' - take file-ids out of the
671
846
      fileids set once their add or remove entry is detected respectively
672
847
    """
673
 
    if not fileids:
674
 
        return False
675
 
    result = False
676
 
    for item in delta.added:
677
 
        if item[1] in fileids:
678
 
            if stop_on == 'add':
679
 
                fileids.remove(item[1])
680
 
            result = True
681
 
    for item in delta.removed:
682
 
        if item[1] in fileids:
683
 
            if stop_on == 'delete':
684
 
                fileids.remove(item[1])
685
 
            result = True
686
 
    if result:
687
 
        return True
688
 
    for l in (delta.modified, delta.renamed, delta.kind_changed):
689
 
        for item in l:
690
 
            if item[1] in fileids:
691
 
                return True
692
 
    return False
 
848
    if stop_on == 'add':
 
849
        for item in delta.added:
 
850
            if item[1] in fileids:
 
851
                fileids.remove(item[1])
 
852
    elif stop_on == 'delete':
 
853
        for item in delta.removed:
 
854
            if item[1] in fileids:
 
855
                fileids.remove(item[1])
693
856
 
694
857
 
695
858
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
739
902
def _get_revision_limits(branch, start_revision, end_revision):
740
903
    """Get and check revision limits.
741
904
 
742
 
    :param  branch: The branch containing the revisions. 
 
905
    :param  branch: The branch containing the revisions.
743
906
 
744
907
    :param  start_revision: The first revision to be logged.
745
908
            For backwards compatibility this may be a mainline integer revno,
788
951
 
789
952
def _get_mainline_revs(branch, start_revision, end_revision):
790
953
    """Get the mainline revisions from the branch.
791
 
    
 
954
 
792
955
    Generates the list of mainline revisions for the branch.
793
 
    
794
 
    :param  branch: The branch containing the revisions. 
 
956
 
 
957
    :param  branch: The branch containing the revisions.
795
958
 
796
959
    :param  start_revision: The first revision to be logged.
797
960
            For backwards compatibility this may be a mainline integer revno,
807
970
    if branch_revno == 0:
808
971
        return None, None, None, None
809
972
 
810
 
    # For mainline generation, map start_revision and end_revision to 
811
 
    # mainline revnos. If the revision is not on the mainline choose the 
812
 
    # appropriate extreme of the mainline instead - the extra will be 
 
973
    # For mainline generation, map start_revision and end_revision to
 
974
    # mainline revnos. If the revision is not on the mainline choose the
 
975
    # appropriate extreme of the mainline instead - the extra will be
813
976
    # filtered later.
814
977
    # Also map the revisions to rev_ids, to be used in the later filtering
815
978
    # stage.
871
1034
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
872
1035
    """Filter view_revisions based on revision ranges.
873
1036
 
874
 
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth) 
 
1037
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
875
1038
            tuples to be filtered.
876
1039
 
877
1040
    :param start_rev_id: If not NONE specifies the first revision to be logged.
897
1060
                end_index = revision_ids.index(end_rev_id)
898
1061
            else:
899
1062
                end_index = len(view_revisions) - 1
900
 
        # To include the revisions merged into the last revision, 
 
1063
        # To include the revisions merged into the last revision,
901
1064
        # extend end_rev_id down to, but not including, the next rev
902
1065
        # with the same or lesser merge_depth
903
1066
        end_merge_depth = view_revisions[end_index][2]
954
1117
    # Lookup all possible text keys to determine which ones actually modified
955
1118
    # the file.
956
1119
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
 
1120
    next_keys = None
957
1121
    # Looking up keys in batches of 1000 can cut the time in half, as well as
958
1122
    # memory consumption. GraphIndex *does* like to look for a few keys in
959
1123
    # parallel, it just doesn't like looking for *lots* of keys in parallel.
1072
1236
    """A revision to be logged (by LogFormatter.log_revision).
1073
1237
 
1074
1238
    A simple wrapper for the attributes of a revision to be logged.
1075
 
    The attributes may or may not be populated, as determined by the 
 
1239
    The attributes may or may not be populated, as determined by the
1076
1240
    logging options and the log formatter capabilities.
1077
1241
    """
1078
1242
 
1094
1258
    If the LogFormatter needs to be informed of the beginning or end of
1095
1259
    a log it should implement the begin_log and/or end_log hook methods.
1096
1260
 
1097
 
    A LogFormatter should define the following supports_XXX flags 
 
1261
    A LogFormatter should define the following supports_XXX flags
1098
1262
    to indicate which LogRevision attributes it supports:
1099
1263
 
1100
1264
    - supports_delta must be True if this log formatter supports delta.
1101
1265
        Otherwise the delta attribute may not be populated.  The 'delta_format'
1102
1266
        attribute describes whether the 'short_status' format (1) or the long
1103
1267
        one (2) should be used.
1104
 
 
1105
 
    - supports_merge_revisions must be True if this log formatter supports 
1106
 
        merge revisions.  If not, and if supports_single_merge_revision is
1107
 
        also not True, then only mainline revisions will be passed to the 
1108
 
        formatter.
 
1268
 
 
1269
    - supports_merge_revisions must be True if this log formatter supports
 
1270
        merge revisions.  If not, then only mainline revisions will be passed
 
1271
        to the formatter.
1109
1272
 
1110
1273
    - preferred_levels is the number of levels this formatter defaults to.
1111
1274
        The default value is zero meaning display all levels.
1112
1275
        This value is only relevant if supports_merge_revisions is True.
1113
1276
 
1114
 
    - supports_single_merge_revision must be True if this log formatter
1115
 
        supports logging only a single merge revision.  This flag is
1116
 
        only relevant if supports_merge_revisions is not True.
1117
 
 
1118
1277
    - supports_tags must be True if this log formatter supports tags.
1119
1278
        Otherwise the tags attribute may not be populated.
1120
1279
 
1125
1284
    the properties_handler_registry. The registered function
1126
1285
    must respect the following interface description:
1127
1286
        def my_show_properties(properties_dict):
1128
 
            # code that returns a dict {'name':'value'} of the properties 
 
1287
            # code that returns a dict {'name':'value'} of the properties
1129
1288
            # to be shown
1130
1289
    """
1131
1290
    preferred_levels = 0
1143
1302
          let the log formatter decide.
1144
1303
        """
1145
1304
        self.to_file = to_file
 
1305
        # 'exact' stream used to show diff, it should print content 'as is'
 
1306
        # and should not try to decode/encode it to unicode to avoid bug #328007
 
1307
        self.to_exact_file = getattr(to_file, 'stream', to_file)
1146
1308
        self.show_ids = show_ids
1147
1309
        self.show_timezone = show_timezone
1148
1310
        if delta_format is None:
1150
1312
            delta_format = 2 # long format
1151
1313
        self.delta_format = delta_format
1152
1314
        self.levels = levels
 
1315
        self._merge_count = 0
1153
1316
 
1154
1317
    def get_levels(self):
1155
1318
        """Get the number of levels to display or 0 for all."""
1156
1319
        if getattr(self, 'supports_merge_revisions', False):
1157
1320
            if self.levels is None or self.levels == -1:
1158
 
                return self.preferred_levels
1159
 
            else:
1160
 
                return self.levels
1161
 
        return 1
 
1321
                self.levels = self.preferred_levels
 
1322
        else:
 
1323
            self.levels = 1
 
1324
        return self.levels
1162
1325
 
1163
1326
    def log_revision(self, revision):
1164
1327
        """Log a revision.
1167
1330
        """
1168
1331
        raise NotImplementedError('not implemented in abstract base')
1169
1332
 
 
1333
    def show_advice(self):
 
1334
        """Output user advice, if any, when the log is completed."""
 
1335
        if self.levels == 1 and self._merge_count > 0:
 
1336
            advice_sep = self.get_advice_separator()
 
1337
            if advice_sep:
 
1338
                self.to_file.write(advice_sep)
 
1339
            self.to_file.write(
 
1340
                "Use --levels 0 (or -n0) to see merged revisions.\n")
 
1341
 
 
1342
    def get_advice_separator(self):
 
1343
        """Get the text separating the log from the closing advice."""
 
1344
        return ''
 
1345
 
1170
1346
    def short_committer(self, rev):
1171
1347
        name, address = config.parse_username(rev.committer)
1172
1348
        if name:
1174
1350
        return address
1175
1351
 
1176
1352
    def short_author(self, rev):
1177
 
        name, address = config.parse_username(rev.get_apparent_author())
 
1353
        name, address = config.parse_username(rev.get_apparent_authors()[0])
1178
1354
        if name:
1179
1355
            return name
1180
1356
        return address
1181
1357
 
 
1358
    def merge_marker(self, revision):
 
1359
        """Get the merge marker to include in the output or '' if none."""
 
1360
        if len(revision.rev.parent_ids) > 1:
 
1361
            self._merge_count += 1
 
1362
            return ' [merge]'
 
1363
        else:
 
1364
            return ''
 
1365
 
1182
1366
    def show_properties(self, revision, indent):
1183
1367
        """Displays the custom properties returned by each registered handler.
1184
 
        
 
1368
 
1185
1369
        If a registered handler raises an error it is propagated.
1186
1370
        """
1187
1371
        for key, handler in properties_handler_registry.iteritems():
1196
1380
class LongLogFormatter(LogFormatter):
1197
1381
 
1198
1382
    supports_merge_revisions = True
 
1383
    preferred_levels = 1
1199
1384
    supports_delta = True
1200
1385
    supports_tags = True
1201
1386
    supports_diff = True
1206
1391
        to_file = self.to_file
1207
1392
        to_file.write(indent + '-' * 60 + '\n')
1208
1393
        if revision.revno is not None:
1209
 
            to_file.write(indent + 'revno: %s\n' % (revision.revno,))
 
1394
            to_file.write(indent + 'revno: %s%s\n' % (revision.revno,
 
1395
                self.merge_marker(revision)))
1210
1396
        if revision.tags:
1211
1397
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
1212
1398
        if self.show_ids:
1216
1402
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
1217
1403
        self.show_properties(revision.rev, indent)
1218
1404
 
1219
 
        author = revision.rev.properties.get('author', None)
1220
 
        if author is not None:
1221
 
            to_file.write(indent + 'author: %s\n' % (author,))
1222
 
        to_file.write(indent + 'committer: %s\n' % (revision.rev.committer,))
 
1405
        committer = revision.rev.committer
 
1406
        authors = revision.rev.get_apparent_authors()
 
1407
        if authors != [committer]:
 
1408
            to_file.write(indent + 'author: %s\n' % (", ".join(authors),))
 
1409
        to_file.write(indent + 'committer: %s\n' % (committer,))
1223
1410
 
1224
1411
        branch_nick = revision.rev.properties.get('branch-nick', None)
1225
1412
        if branch_nick is not None:
1245
1432
            to_file.write(indent + 'diff:\n')
1246
1433
            # Note: we explicitly don't indent the diff (relative to the
1247
1434
            # revision information) so that the output can be fed to patch -p0
1248
 
            self.show_diff(to_file, revision.diff, indent)
 
1435
            self.show_diff(self.to_exact_file, revision.diff, indent)
 
1436
 
 
1437
    def get_advice_separator(self):
 
1438
        """Get the text separating the log from the closing advice."""
 
1439
        return '-' * 60 + '\n'
1249
1440
 
1250
1441
 
1251
1442
class ShortLogFormatter(LogFormatter):
1281
1472
        offset = ' ' * (revno_width + 1)
1282
1473
 
1283
1474
        to_file = self.to_file
1284
 
        is_merge = ''
1285
 
        if len(revision.rev.parent_ids) > 1:
1286
 
            is_merge = ' [merge]'
1287
1475
        tags = ''
1288
1476
        if revision.tags:
1289
1477
            tags = ' {%s}' % (', '.join(revision.tags))
1293
1481
                            revision.rev.timezone or 0,
1294
1482
                            self.show_timezone, date_fmt="%Y-%m-%d",
1295
1483
                            show_offset=False),
1296
 
                tags, is_merge))
 
1484
                tags, self.merge_marker(revision)))
1297
1485
        self.show_properties(revision.rev, indent+offset)
1298
1486
        if self.show_ids:
1299
1487
            to_file.write(indent + offset + 'revision-id:%s\n'
1309
1497
            revision.delta.show(to_file, self.show_ids, indent=indent + offset,
1310
1498
                                short_status=self.delta_format==1)
1311
1499
        if revision.diff is not None:
1312
 
            self.show_diff(to_file, revision.diff, '      ')
 
1500
            self.show_diff(self.to_exact_file, revision.diff, '      ')
1313
1501
        to_file.write('\n')
1314
1502
 
1315
1503
 
1370
1558
        return self.truncate(prefix + " ".join(out).rstrip('\n'), max_chars)
1371
1559
 
1372
1560
 
 
1561
class GnuChangelogLogFormatter(LogFormatter):
 
1562
 
 
1563
    supports_merge_revisions = True
 
1564
    supports_delta = True
 
1565
 
 
1566
    def log_revision(self, revision):
 
1567
        """Log a revision, either merged or not."""
 
1568
        to_file = self.to_file
 
1569
 
 
1570
        date_str = format_date(revision.rev.timestamp,
 
1571
                               revision.rev.timezone or 0,
 
1572
                               self.show_timezone,
 
1573
                               date_fmt='%Y-%m-%d',
 
1574
                               show_offset=False)
 
1575
        committer_str = revision.rev.committer.replace (' <', '  <')
 
1576
        to_file.write('%s  %s\n\n' % (date_str,committer_str))
 
1577
 
 
1578
        if revision.delta is not None and revision.delta.has_changed():
 
1579
            for c in revision.delta.added + revision.delta.removed + revision.delta.modified:
 
1580
                path, = c[:1]
 
1581
                to_file.write('\t* %s:\n' % (path,))
 
1582
            for c in revision.delta.renamed:
 
1583
                oldpath,newpath = c[:2]
 
1584
                # For renamed files, show both the old and the new path
 
1585
                to_file.write('\t* %s:\n\t* %s:\n' % (oldpath,newpath))
 
1586
            to_file.write('\n')
 
1587
 
 
1588
        if not revision.rev.message:
 
1589
            to_file.write('\tNo commit message\n')
 
1590
        else:
 
1591
            message = revision.rev.message.rstrip('\r\n')
 
1592
            for l in message.split('\n'):
 
1593
                to_file.write('\t%s\n' % (l.lstrip(),))
 
1594
            to_file.write('\n')
 
1595
 
 
1596
 
1373
1597
def line_log(rev, max_chars):
1374
1598
    lf = LineLogFormatter(None)
1375
1599
    return lf.log_string(None, rev, max_chars)
1399
1623
                                'Detailed log format')
1400
1624
log_formatter_registry.register('line', LineLogFormatter,
1401
1625
                                'Log format with one line per revision')
 
1626
log_formatter_registry.register('gnu-changelog', GnuChangelogLogFormatter,
 
1627
                                'Format used by GNU ChangeLog files')
1402
1628
 
1403
1629
 
1404
1630
def register_formatter(name, formatter):
1573
1799
        lf.log_revision(lr)
1574
1800
 
1575
1801
 
1576
 
def _get_fileid_to_log(revision, tree, b, fp):
1577
 
    """Find the file-id to log for a file path in a revision range.
1578
 
 
1579
 
    :param revision: the revision range as parsed on the command line
1580
 
    :param tree: the working tree, if any
1581
 
    :param b: the branch
1582
 
    :param fp: file path
 
1802
def _get_info_for_log_files(revisionspec_list, file_list):
 
1803
    """Find file-ids and kinds given a list of files and a revision range.
 
1804
 
 
1805
    We search for files at the end of the range. If not found there,
 
1806
    we try the start of the range.
 
1807
 
 
1808
    :param revisionspec_list: revision range as parsed on the command line
 
1809
    :param file_list: the list of paths given on the command line;
 
1810
      the first of these can be a branch location or a file path,
 
1811
      the remainder must be file paths
 
1812
    :return: (branch, info_list, start_rev_info, end_rev_info) where
 
1813
      info_list is a list of (relative_path, file_id, kind) tuples where
 
1814
      kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
1583
1815
    """
1584
 
    if revision is None:
 
1816
    from builtins import _get_revision_range, safe_relpath_files
 
1817
    tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
 
1818
    # XXX: It's damn messy converting a list of paths to relative paths when
 
1819
    # those paths might be deleted ones, they might be on a case-insensitive
 
1820
    # filesystem and/or they might be in silly locations (like another branch).
 
1821
    # For example, what should "log bzr://branch/dir/file1 file2" do? (Is
 
1822
    # file2 implicitly in the same dir as file1 or should its directory be
 
1823
    # taken from the current tree somehow?) For now, this solves the common
 
1824
    # case of running log in a nested directory, assuming paths beyond the
 
1825
    # first one haven't been deleted ...
 
1826
    if tree:
 
1827
        relpaths = [path] + safe_relpath_files(tree, file_list[1:])
 
1828
    else:
 
1829
        relpaths = [path] + file_list[1:]
 
1830
    info_list = []
 
1831
    start_rev_info, end_rev_info = _get_revision_range(revisionspec_list, b,
 
1832
        "log")
 
1833
    if start_rev_info is None and end_rev_info is None:
1585
1834
        if tree is None:
1586
1835
            tree = b.basis_tree()
1587
 
        file_id = tree.path2id(fp)
1588
 
        if file_id is None:
1589
 
            # go back to when time began
1590
 
            try:
1591
 
                rev1 = b.get_rev_id(1)
1592
 
            except errors.NoSuchRevision:
1593
 
                # No history at all
1594
 
                file_id = None
1595
 
            else:
1596
 
                tree = b.repository.revision_tree(rev1)
1597
 
                file_id = tree.path2id(fp)
 
1836
        tree1 = None
 
1837
        for fp in relpaths:
 
1838
            file_id = tree.path2id(fp)
 
1839
            kind = _get_kind_for_file_id(tree, file_id)
 
1840
            if file_id is None:
 
1841
                # go back to when time began
 
1842
                if tree1 is None:
 
1843
                    try:
 
1844
                        rev1 = b.get_rev_id(1)
 
1845
                    except errors.NoSuchRevision:
 
1846
                        # No history at all
 
1847
                        file_id = None
 
1848
                        kind = None
 
1849
                    else:
 
1850
                        tree1 = b.repository.revision_tree(rev1)
 
1851
                if tree1:
 
1852
                    file_id = tree1.path2id(fp)
 
1853
                    kind = _get_kind_for_file_id(tree1, file_id)
 
1854
            info_list.append((fp, file_id, kind))
1598
1855
 
1599
 
    elif len(revision) == 1:
 
1856
    elif start_rev_info == end_rev_info:
1600
1857
        # One revision given - file must exist in it
1601
 
        tree = revision[0].as_tree(b)
1602
 
        file_id = tree.path2id(fp)
 
1858
        tree = b.repository.revision_tree(end_rev_info.rev_id)
 
1859
        for fp in relpaths:
 
1860
            file_id = tree.path2id(fp)
 
1861
            kind = _get_kind_for_file_id(tree, file_id)
 
1862
            info_list.append((fp, file_id, kind))
1603
1863
 
1604
 
    elif len(revision) == 2:
 
1864
    else:
1605
1865
        # Revision range given. Get the file-id from the end tree.
1606
1866
        # If that fails, try the start tree.
1607
 
        rev_id = revision[1].as_revision_id(b)
 
1867
        rev_id = end_rev_info.rev_id
1608
1868
        if rev_id is None:
1609
1869
            tree = b.basis_tree()
1610
1870
        else:
1611
 
            tree = revision[1].as_tree(b)
1612
 
        file_id = tree.path2id(fp)
1613
 
        if file_id is None:
1614
 
            rev_id = revision[0].as_revision_id(b)
1615
 
            if rev_id is None:
1616
 
                rev1 = b.get_rev_id(1)
1617
 
                tree = b.repository.revision_tree(rev1)
1618
 
            else:
1619
 
                tree = revision[0].as_tree(b)
 
1871
            tree = b.repository.revision_tree(rev_id)
 
1872
        tree1 = None
 
1873
        for fp in relpaths:
1620
1874
            file_id = tree.path2id(fp)
 
1875
            kind = _get_kind_for_file_id(tree, file_id)
 
1876
            if file_id is None:
 
1877
                if tree1 is None:
 
1878
                    rev_id = start_rev_info.rev_id
 
1879
                    if rev_id is None:
 
1880
                        rev1 = b.get_rev_id(1)
 
1881
                        tree1 = b.repository.revision_tree(rev1)
 
1882
                    else:
 
1883
                        tree1 = b.repository.revision_tree(rev_id)
 
1884
                file_id = tree1.path2id(fp)
 
1885
                kind = _get_kind_for_file_id(tree1, file_id)
 
1886
            info_list.append((fp, file_id, kind))
 
1887
    return b, info_list, start_rev_info, end_rev_info
 
1888
 
 
1889
 
 
1890
def _get_kind_for_file_id(tree, file_id):
 
1891
    """Return the kind of a file-id or None if it doesn't exist."""
 
1892
    if file_id is not None:
 
1893
        return tree.kind(file_id)
1621
1894
    else:
1622
 
        raise errors.BzrCommandError(
1623
 
            'bzr log --revision takes one or two values.')
1624
 
    return file_id
 
1895
        return None
1625
1896
 
1626
1897
 
1627
1898
properties_handler_registry = registry.Registry()