~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/log.py

(mbp) tolerate empty limbo and pending-deletion directories (bug 427773)
 (Martin Pool)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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,
 
72
    foreign,
71
73
    repository as _mod_repository,
72
74
    revision as _mod_revision,
73
75
    revisionspec,
74
 
    trace,
75
76
    tsort,
 
77
    i18n,
76
78
    )
77
79
""")
78
80
 
79
81
from bzrlib import (
 
82
    lazy_regex,
80
83
    registry,
81
84
    )
82
85
from bzrlib.osutils import (
83
86
    format_date,
 
87
    format_date_with_offset_in_original_timezone,
 
88
    get_diff_header_encoding,
84
89
    get_terminal_encoding,
85
90
    terminal_width,
86
91
    )
 
92
from bzrlib.symbol_versioning import (
 
93
    deprecated_function,
 
94
    deprecated_in,
 
95
    )
87
96
 
88
97
 
89
98
def find_touching_revisions(branch, file_id):
101
110
    last_path = None
102
111
    revno = 1
103
112
    for revision_id in branch.revision_history():
104
 
        this_inv = branch.repository.get_revision_inventory(revision_id)
105
 
        if file_id in this_inv:
 
113
        this_inv = branch.repository.get_inventory(revision_id)
 
114
        if this_inv.has_id(file_id):
106
115
            this_ie = this_inv[file_id]
107
116
            this_path = this_inv.id2path(file_id)
108
117
        else:
151
160
             show_diff=False):
152
161
    """Write out human-readable log of commits to this branch.
153
162
 
 
163
    This function is being retained for backwards compatibility but
 
164
    should not be extended with new parameters. Use the new Logger class
 
165
    instead, eg. Logger(branch, rqst).show(lf), adding parameters to the
 
166
    make_log_request_dict function.
 
167
 
154
168
    :param lf: The LogFormatter object showing the output.
155
169
 
156
170
    :param specific_fileid: If not None, list only the commits affecting the
173
187
 
174
188
    :param show_diff: If True, output a diff after each revision.
175
189
    """
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)
 
190
    # Convert old-style parameters to new-style parameters
 
191
    if specific_fileid is not None:
 
192
        file_ids = [specific_fileid]
 
193
    else:
 
194
        file_ids = None
 
195
    if verbose:
 
196
        if file_ids:
 
197
            delta_type = 'partial'
 
198
        else:
 
199
            delta_type = 'full'
 
200
    else:
 
201
        delta_type = None
 
202
    if show_diff:
 
203
        if file_ids:
 
204
            diff_type = 'partial'
 
205
        else:
 
206
            diff_type = 'full'
 
207
    else:
 
208
        diff_type = None
 
209
 
 
210
    # Build the request and execute it
 
211
    rqst = make_log_request_dict(direction=direction, specific_fileids=file_ids,
 
212
        start_revision=start_revision, end_revision=end_revision,
 
213
        limit=limit, message_search=search,
 
214
        delta_type=delta_type, diff_type=diff_type)
 
215
    Logger(branch, rqst).show(lf)
 
216
 
 
217
 
 
218
# Note: This needs to be kept this in sync with the defaults in
 
219
# make_log_request_dict() below
 
220
_DEFAULT_REQUEST_PARAMS = {
 
221
    'direction': 'reverse',
 
222
    'levels': 1,
 
223
    'generate_tags': True,
 
224
    'exclude_common_ancestry': False,
 
225
    '_match_using_deltas': True,
 
226
    }
 
227
 
 
228
 
 
229
def make_log_request_dict(direction='reverse', specific_fileids=None,
 
230
                          start_revision=None, end_revision=None, limit=None,
 
231
                          message_search=None, levels=1, generate_tags=True,
 
232
                          delta_type=None,
 
233
                          diff_type=None, _match_using_deltas=True,
 
234
                          exclude_common_ancestry=False,
 
235
                          signature=False,
 
236
                          ):
 
237
    """Convenience function for making a logging request dictionary.
 
238
 
 
239
    Using this function may make code slightly safer by ensuring
 
240
    parameters have the correct names. It also provides a reference
 
241
    point for documenting the supported parameters.
 
242
 
 
243
    :param direction: 'reverse' (default) is latest to earliest;
 
244
      'forward' is earliest to latest.
 
245
 
 
246
    :param specific_fileids: If not None, only include revisions
 
247
      affecting the specified files, rather than all revisions.
 
248
 
 
249
    :param start_revision: If not None, only generate
 
250
      revisions >= start_revision
 
251
 
 
252
    :param end_revision: If not None, only generate
 
253
      revisions <= end_revision
 
254
 
 
255
    :param limit: If set, generate only 'limit' revisions, all revisions
 
256
      are shown if None or 0.
 
257
 
 
258
    :param message_search: If not None, only include revisions with
 
259
      matching commit messages
 
260
 
 
261
    :param levels: the number of levels of revisions to
 
262
      generate; 1 for just the mainline; 0 for all levels.
 
263
 
 
264
    :param generate_tags: If True, include tags for matched revisions.
 
265
`
 
266
    :param delta_type: Either 'full', 'partial' or None.
 
267
      'full' means generate the complete delta - adds/deletes/modifies/etc;
 
268
      'partial' means filter the delta using specific_fileids;
 
269
      None means do not generate any delta.
 
270
 
 
271
    :param diff_type: Either 'full', 'partial' or None.
 
272
      'full' means generate the complete diff - adds/deletes/modifies/etc;
 
273
      'partial' means filter the diff using specific_fileids;
 
274
      None means do not generate any diff.
 
275
 
 
276
    :param _match_using_deltas: a private parameter controlling the
 
277
      algorithm used for matching specific_fileids. This parameter
 
278
      may be removed in the future so bzrlib client code should NOT
 
279
      use it.
 
280
 
 
281
    :param exclude_common_ancestry: Whether -rX..Y should be interpreted as a
 
282
      range operator or as a graph difference.
 
283
 
 
284
    :param signature: show digital signature information
 
285
    """
 
286
    return {
 
287
        'direction': direction,
 
288
        'specific_fileids': specific_fileids,
 
289
        'start_revision': start_revision,
 
290
        'end_revision': end_revision,
 
291
        'limit': limit,
 
292
        'message_search': message_search,
 
293
        'levels': levels,
 
294
        'generate_tags': generate_tags,
 
295
        'delta_type': delta_type,
 
296
        'diff_type': diff_type,
 
297
        'exclude_common_ancestry': exclude_common_ancestry,
 
298
        'signature': signature,
 
299
        # Add 'private' attributes for features that may be deprecated
 
300
        '_match_using_deltas': _match_using_deltas,
 
301
    }
 
302
 
 
303
 
 
304
def _apply_log_request_defaults(rqst):
 
305
    """Apply default values to a request dictionary."""
 
306
    result = _DEFAULT_REQUEST_PARAMS.copy()
 
307
    if rqst:
 
308
        result.update(rqst)
 
309
    return result
 
310
 
 
311
 
 
312
def format_signature_validity(rev_id, repo):
 
313
    """get the signature validity
 
314
    
 
315
    :param rev_id: revision id to validate
 
316
    :param repo: repository of revision
 
317
    :return: human readable string to print to log
 
318
    """
 
319
    from bzrlib import gpg
 
320
 
 
321
    gpg_strategy = gpg.GPGStrategy(None)
 
322
    result = repo.verify_revision(rev_id, gpg_strategy)
 
323
    if result[0] == gpg.SIGNATURE_VALID:
 
324
        return "valid signature from {0}".format(result[1])
 
325
    if result[0] == gpg.SIGNATURE_KEY_MISSING:
 
326
        return "unknown key {0}".format(result[1])
 
327
    if result[0] == gpg.SIGNATURE_NOT_VALID:
 
328
        return "invalid signature!"
 
329
    if result[0] == gpg.SIGNATURE_NOT_SIGNED:
 
330
        return "no signature"
 
331
 
 
332
 
 
333
class LogGenerator(object):
 
334
    """A generator of log revisions."""
 
335
 
 
336
    def iter_log_revisions(self):
 
337
        """Iterate over LogRevision objects.
 
338
 
 
339
        :return: An iterator yielding LogRevision objects.
 
340
        """
 
341
        raise NotImplementedError(self.iter_log_revisions)
 
342
 
 
343
 
 
344
class Logger(object):
 
345
    """An object that generates, formats and displays a log."""
 
346
 
 
347
    def __init__(self, branch, rqst):
 
348
        """Create a Logger.
 
349
 
 
350
        :param branch: the branch to log
 
351
        :param rqst: A dictionary specifying the query parameters.
 
352
          See make_log_request_dict() for supported values.
 
353
        """
 
354
        self.branch = branch
 
355
        self.rqst = _apply_log_request_defaults(rqst)
 
356
 
 
357
    def show(self, lf):
 
358
        """Display the log.
 
359
 
 
360
        :param lf: The LogFormatter object to send the output to.
 
361
        """
 
362
        if not isinstance(lf, LogFormatter):
 
363
            warn("not a LogFormatter instance: %r" % lf)
 
364
 
 
365
        self.branch.lock_read()
 
366
        try:
 
367
            if getattr(lf, 'begin_log', None):
 
368
                lf.begin_log()
 
369
            self._show_body(lf)
 
370
            if getattr(lf, 'end_log', None):
 
371
                lf.end_log()
 
372
        finally:
 
373
            self.branch.unlock()
 
374
 
 
375
    def _show_body(self, lf):
 
376
        """Show the main log output.
 
377
 
 
378
        Subclasses may wish to override this.
 
379
        """
 
380
        # Tweak the LogRequest based on what the LogFormatter can handle.
 
381
        # (There's no point generating stuff if the formatter can't display it.)
 
382
        rqst = self.rqst
 
383
        rqst['levels'] = lf.get_levels()
 
384
        if not getattr(lf, 'supports_tags', False):
 
385
            rqst['generate_tags'] = False
 
386
        if not getattr(lf, 'supports_delta', False):
 
387
            rqst['delta_type'] = None
 
388
        if not getattr(lf, 'supports_diff', False):
 
389
            rqst['diff_type'] = None
 
390
        if not getattr(lf, 'supports_signatures', False):
 
391
            rqst['signature'] = False
 
392
 
 
393
        # Find and print the interesting revisions
 
394
        generator = self._generator_factory(self.branch, rqst)
 
395
        for lr in generator.iter_log_revisions():
239
396
            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()
 
397
        lf.show_advice()
 
398
 
 
399
    def _generator_factory(self, branch, rqst):
 
400
        """Make the LogGenerator object to use.
 
401
        
 
402
        Subclasses may wish to override this.
 
403
        """
 
404
        return _DefaultLogGenerator(branch, rqst)
261
405
 
262
406
 
263
407
class _StartNotLinearAncestor(Exception):
264
408
    """Raised when a start revision is not found walking left-hand history."""
265
409
 
266
410
 
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:
 
411
class _DefaultLogGenerator(LogGenerator):
 
412
    """The default generator of log revisions."""
 
413
 
 
414
    def __init__(self, branch, rqst):
 
415
        self.branch = branch
 
416
        self.rqst = rqst
 
417
        if rqst.get('generate_tags') and branch.supports_tags():
 
418
            self.rev_tag_dict = branch.tags.get_reverse_tag_dict()
 
419
        else:
 
420
            self.rev_tag_dict = {}
 
421
 
 
422
    def iter_log_revisions(self):
 
423
        """Iterate over LogRevision objects.
 
424
 
 
425
        :return: An iterator yielding LogRevision objects.
 
426
        """
 
427
        rqst = self.rqst
 
428
        levels = rqst.get('levels')
 
429
        limit = rqst.get('limit')
 
430
        diff_type = rqst.get('diff_type')
 
431
        show_signature = rqst.get('signature')
 
432
        log_count = 0
 
433
        revision_iterator = self._create_log_revision_iterator()
 
434
        for revs in revision_iterator:
 
435
            for (rev_id, revno, merge_depth), rev, delta in revs:
 
436
                # 0 levels means show everything; merge_depth counts from 0
 
437
                if levels != 0 and merge_depth >= levels:
 
438
                    continue
 
439
                if diff_type is None:
 
440
                    diff = None
 
441
                else:
 
442
                    diff = self._format_diff(rev, rev_id, diff_type)
 
443
                if show_signature:
 
444
                    signature = format_signature_validity(rev_id,
 
445
                                                self.branch.repository)
 
446
                else:
 
447
                    signature = None
 
448
                yield LogRevision(rev, revno, merge_depth, delta,
 
449
                    self.rev_tag_dict.get(rev_id), diff, signature)
 
450
                if limit:
 
451
                    log_count += 1
 
452
                    if log_count >= limit:
 
453
                        return
 
454
 
 
455
    def _format_diff(self, rev, rev_id, diff_type):
 
456
        repo = self.branch.repository
 
457
        if len(rev.parent_ids) == 0:
 
458
            ancestor_id = _mod_revision.NULL_REVISION
 
459
        else:
 
460
            ancestor_id = rev.parent_ids[0]
 
461
        tree_1 = repo.revision_tree(ancestor_id)
 
462
        tree_2 = repo.revision_tree(rev_id)
 
463
        file_ids = self.rqst.get('specific_fileids')
 
464
        if diff_type == 'partial' and file_ids is not None:
 
465
            specific_files = [tree_2.id2path(id) for id in file_ids]
 
466
        else:
 
467
            specific_files = None
 
468
        s = StringIO()
 
469
        path_encoding = get_diff_header_encoding()
 
470
        diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
 
471
            new_label='', path_encoding=path_encoding)
 
472
        return s.getvalue()
 
473
 
 
474
    def _create_log_revision_iterator(self):
 
475
        """Create a revision iterator for log.
 
476
 
 
477
        :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
478
            delta).
 
479
        """
 
480
        self.start_rev_id, self.end_rev_id = _get_revision_limits(
 
481
            self.branch, self.rqst.get('start_revision'),
 
482
            self.rqst.get('end_revision'))
 
483
        if self.rqst.get('_match_using_deltas'):
 
484
            return self._log_revision_iterator_using_delta_matching()
 
485
        else:
 
486
            # We're using the per-file-graph algorithm. This scales really
 
487
            # well but only makes sense if there is a single file and it's
 
488
            # not a directory
 
489
            file_count = len(self.rqst.get('specific_fileids'))
 
490
            if file_count != 1:
 
491
                raise BzrError("illegal LogRequest: must match-using-deltas "
 
492
                    "when logging %d files" % file_count)
 
493
            return self._log_revision_iterator_using_per_file_graph()
 
494
 
 
495
    def _log_revision_iterator_using_delta_matching(self):
 
496
        # Get the base revisions, filtering by the revision range
 
497
        rqst = self.rqst
 
498
        generate_merge_revisions = rqst.get('levels') != 1
 
499
        delayed_graph_generation = not rqst.get('specific_fileids') and (
 
500
                rqst.get('limit') or self.start_rev_id or self.end_rev_id)
 
501
        view_revisions = _calc_view_revisions(
 
502
            self.branch, self.start_rev_id, self.end_rev_id,
 
503
            rqst.get('direction'),
 
504
            generate_merge_revisions=generate_merge_revisions,
 
505
            delayed_graph_generation=delayed_graph_generation,
 
506
            exclude_common_ancestry=rqst.get('exclude_common_ancestry'))
 
507
 
 
508
        # Apply the other filters
 
509
        return make_log_rev_iterator(self.branch, view_revisions,
 
510
            rqst.get('delta_type'), rqst.get('message_search'),
 
511
            file_ids=rqst.get('specific_fileids'),
 
512
            direction=rqst.get('direction'))
 
513
 
 
514
    def _log_revision_iterator_using_per_file_graph(self):
 
515
        # Get the base revisions, filtering by the revision range.
 
516
        # Note that we always generate the merge revisions because
 
517
        # filter_revisions_touching_file_id() requires them ...
 
518
        rqst = self.rqst
 
519
        view_revisions = _calc_view_revisions(
 
520
            self.branch, self.start_rev_id, self.end_rev_id,
 
521
            rqst.get('direction'), generate_merge_revisions=True,
 
522
            exclude_common_ancestry=rqst.get('exclude_common_ancestry'))
313
523
        if not isinstance(view_revisions, list):
314
524
            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)
 
525
        view_revisions = _filter_revisions_touching_file_id(self.branch,
 
526
            rqst.get('specific_fileids')[0], view_revisions,
 
527
            include_merges=rqst.get('levels') != 1)
 
528
        return make_log_rev_iterator(self.branch, view_revisions,
 
529
            rqst.get('delta_type'), rqst.get('message_search'))
320
530
 
321
531
 
322
532
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):
 
533
                         generate_merge_revisions,
 
534
                         delayed_graph_generation=False,
 
535
                         exclude_common_ancestry=False,
 
536
                         ):
325
537
    """Calculate the revisions to view.
326
538
 
327
539
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
328
540
             a list of the same tuples.
329
541
    """
 
542
    if (exclude_common_ancestry and start_rev_id == end_rev_id):
 
543
        raise errors.BzrCommandError(
 
544
            '--exclude-common-ancestry requires two different revisions')
 
545
    if direction not in ('reverse', 'forward'):
 
546
        raise ValueError('invalid direction %r' % direction)
330
547
    br_revno, br_rev_id = branch.last_revision_info()
331
548
    if br_revno == 0:
332
549
        return []
333
550
 
334
 
    # If a single revision is requested, check we can handle it
335
 
    generate_single_revision = (end_rev_id and start_rev_id == end_rev_id and
336
 
        (not generate_merge_revisions or not _has_merges(branch, end_rev_id)))
337
 
    if generate_single_revision:
338
 
        if end_rev_id == br_rev_id:
339
 
            # It's the tip
340
 
            return [(br_rev_id, br_revno, 0)]
341
 
        else:
342
 
            revno = branch.revision_id_to_dotted_revno(end_rev_id)
343
 
            if len(revno) > 1 and not allow_single_merge_revision:
344
 
                # It's a merge revision and the log formatter is
345
 
                # completely brain dead. This "feature" of allowing
346
 
                # log formatters incapable of displaying dotted revnos
347
 
                # ought to be deprecated IMNSHO. IGC 20091022
348
 
                raise errors.BzrCommandError('Selected log formatter only'
349
 
                    ' supports mainline revisions.')
350
 
            revno_str = '.'.join(str(n) for n in revno)
351
 
            return [(end_rev_id, revno_str, 0)]
352
 
 
353
 
    # If we only want to see linear revisions, we can iterate ...
354
 
    if not generate_merge_revisions:
355
 
        result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
356
 
        # If a start limit was given and it's not obviously an
357
 
        # ancestor of the end limit, check it before outputting anything
358
 
        if direction == 'forward' or (start_rev_id
359
 
            and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
360
 
            try:
361
 
                result = list(result)
362
 
            except _StartNotLinearAncestor:
363
 
                raise errors.BzrCommandError('Start revision not found in'
364
 
                    ' left-hand history of end revision.')
365
 
        if direction == 'forward':
366
 
            result = reversed(list(result))
367
 
        return result
368
 
 
 
551
    if (end_rev_id and start_rev_id == end_rev_id
 
552
        and (not generate_merge_revisions
 
553
             or not _has_merges(branch, end_rev_id))):
 
554
        # If a single revision is requested, check we can handle it
 
555
        iter_revs = _generate_one_revision(branch, end_rev_id, br_rev_id,
 
556
                                           br_revno)
 
557
    elif not generate_merge_revisions:
 
558
        # If we only want to see linear revisions, we can iterate ...
 
559
        iter_revs = _generate_flat_revisions(branch, start_rev_id, end_rev_id,
 
560
                                             direction, exclude_common_ancestry)
 
561
        if direction == 'forward':
 
562
            iter_revs = reversed(iter_revs)
 
563
    else:
 
564
        iter_revs = _generate_all_revisions(branch, start_rev_id, end_rev_id,
 
565
                                            direction, delayed_graph_generation,
 
566
                                            exclude_common_ancestry)
 
567
        if direction == 'forward':
 
568
            iter_revs = _rebase_merge_depth(reverse_by_depth(list(iter_revs)))
 
569
    return iter_revs
 
570
 
 
571
 
 
572
def _generate_one_revision(branch, rev_id, br_rev_id, br_revno):
 
573
    if rev_id == br_rev_id:
 
574
        # It's the tip
 
575
        return [(br_rev_id, br_revno, 0)]
 
576
    else:
 
577
        revno_str = _compute_revno_str(branch, rev_id)
 
578
        return [(rev_id, revno_str, 0)]
 
579
 
 
580
 
 
581
def _generate_flat_revisions(branch, start_rev_id, end_rev_id, direction,
 
582
                             exclude_common_ancestry=False):
 
583
    result = _linear_view_revisions(
 
584
        branch, start_rev_id, end_rev_id,
 
585
        exclude_common_ancestry=exclude_common_ancestry)
 
586
    # If a start limit was given and it's not obviously an
 
587
    # ancestor of the end limit, check it before outputting anything
 
588
    if direction == 'forward' or (start_rev_id
 
589
        and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
 
590
        try:
 
591
            result = list(result)
 
592
        except _StartNotLinearAncestor:
 
593
            raise errors.BzrCommandError('Start revision not found in'
 
594
                ' left-hand history of end revision.')
 
595
    return result
 
596
 
 
597
 
 
598
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
 
599
                            delayed_graph_generation,
 
600
                            exclude_common_ancestry=False):
369
601
    # On large trees, generating the merge graph can take 30-60 seconds
370
602
    # so we delay doing it until a merge is detected, incrementally
371
603
    # returning initial (non-merge) revisions while we can.
 
604
 
 
605
    # The above is only true for old formats (<= 0.92), for newer formats, a
 
606
    # couple of seconds only should be needed to load the whole graph and the
 
607
    # other graph operations needed are even faster than that -- vila 100201
372
608
    initial_revisions = []
373
609
    if delayed_graph_generation:
374
610
        try:
375
 
            for rev_id, revno, depth in \
376
 
                _linear_view_revisions(branch, start_rev_id, end_rev_id):
 
611
            for rev_id, revno, depth in  _linear_view_revisions(
 
612
                branch, start_rev_id, end_rev_id, exclude_common_ancestry):
377
613
                if _has_merges(branch, rev_id):
 
614
                    # The end_rev_id can be nested down somewhere. We need an
 
615
                    # explicit ancestry check. There is an ambiguity here as we
 
616
                    # may not raise _StartNotLinearAncestor for a revision that
 
617
                    # is an ancestor but not a *linear* one. But since we have
 
618
                    # loaded the graph to do the check (or calculate a dotted
 
619
                    # revno), we may as well accept to show the log...  We need
 
620
                    # the check only if start_rev_id is not None as all
 
621
                    # revisions have _mod_revision.NULL_REVISION as an ancestor
 
622
                    # -- vila 20100319
 
623
                    graph = branch.repository.get_graph()
 
624
                    if (start_rev_id is not None
 
625
                        and not graph.is_ancestor(start_rev_id, end_rev_id)):
 
626
                        raise _StartNotLinearAncestor()
 
627
                    # Since we collected the revisions so far, we need to
 
628
                    # adjust end_rev_id.
378
629
                    end_rev_id = rev_id
379
630
                    break
380
631
                else:
381
632
                    initial_revisions.append((rev_id, revno, depth))
382
633
            else:
383
634
                # No merged revisions found
384
 
                if direction == 'reverse':
385
 
                    return initial_revisions
386
 
                elif direction == 'forward':
387
 
                    return reversed(initial_revisions)
388
 
                else:
389
 
                    raise ValueError('invalid direction %r' % direction)
 
635
                return initial_revisions
390
636
        except _StartNotLinearAncestor:
391
637
            # A merge was never detected so the lower revision limit can't
392
638
            # be nested down somewhere
393
639
            raise errors.BzrCommandError('Start revision not found in'
394
640
                ' history of end revision.')
395
641
 
 
642
    # We exit the loop above because we encounter a revision with merges, from
 
643
    # this revision, we need to switch to _graph_view_revisions.
 
644
 
396
645
    # A log including nested merges is required. If the direction is reverse,
397
646
    # we rebase the initial merge depths so that the development line is
398
647
    # shown naturally, i.e. just like it is for linear logging. We can easily
400
649
    # indented at the end seems slightly nicer in that case.
401
650
    view_revisions = chain(iter(initial_revisions),
402
651
        _graph_view_revisions(branch, start_rev_id, end_rev_id,
403
 
        rebase_initial_depths=direction == 'reverse'))
404
 
    if direction == 'reverse':
405
 
        return view_revisions
406
 
    elif direction == 'forward':
407
 
        # Forward means oldest first, adjusting for depth.
408
 
        view_revisions = reverse_by_depth(list(view_revisions))
409
 
        return _rebase_merge_depth(view_revisions)
410
 
    else:
411
 
        raise ValueError('invalid direction %r' % direction)
 
652
                              rebase_initial_depths=(direction == 'reverse'),
 
653
                              exclude_common_ancestry=exclude_common_ancestry))
 
654
    return view_revisions
412
655
 
413
656
 
414
657
def _has_merges(branch, rev_id):
417
660
    return len(parents) > 1
418
661
 
419
662
 
 
663
def _compute_revno_str(branch, rev_id):
 
664
    """Compute the revno string from a rev_id.
 
665
 
 
666
    :return: The revno string, or None if the revision is not in the supplied
 
667
        branch.
 
668
    """
 
669
    try:
 
670
        revno = branch.revision_id_to_dotted_revno(rev_id)
 
671
    except errors.NoSuchRevision:
 
672
        # The revision must be outside of this branch
 
673
        return None
 
674
    else:
 
675
        return '.'.join(str(n) for n in revno)
 
676
 
 
677
 
420
678
def _is_obvious_ancestor(branch, start_rev_id, end_rev_id):
421
679
    """Is start_rev_id an obvious ancestor of end_rev_id?"""
422
680
    if start_rev_id and end_rev_id:
423
 
        start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
424
 
        end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
 
681
        try:
 
682
            start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
 
683
            end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
 
684
        except errors.NoSuchRevision:
 
685
            # one or both is not in the branch; not obvious
 
686
            return False
425
687
        if len(start_dotted) == 1 and len(end_dotted) == 1:
426
688
            # both on mainline
427
689
            return start_dotted[0] <= end_dotted[0]
432
694
        else:
433
695
            # not obvious
434
696
            return False
 
697
    # if either start or end is not specified then we use either the first or
 
698
    # the last revision and *they* are obvious ancestors.
435
699
    return True
436
700
 
437
701
 
438
 
def _linear_view_revisions(branch, start_rev_id, end_rev_id):
 
702
def _linear_view_revisions(branch, start_rev_id, end_rev_id,
 
703
                           exclude_common_ancestry=False):
439
704
    """Calculate a sequence of revisions to view, newest to oldest.
440
705
 
441
706
    :param start_rev_id: the lower revision-id
442
707
    :param end_rev_id: the upper revision-id
 
708
    :param exclude_common_ancestry: Whether the start_rev_id should be part of
 
709
        the iterated revisions.
443
710
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
444
711
    :raises _StartNotLinearAncestor: if a start_rev_id is specified but
445
 
      is not found walking the left-hand history
 
712
        is not found walking the left-hand history
446
713
    """
447
714
    br_revno, br_rev_id = branch.last_revision_info()
448
715
    repo = branch.repository
 
716
    graph = repo.get_graph()
449
717
    if start_rev_id is None and end_rev_id is None:
450
718
        cur_revno = br_revno
451
 
        for revision_id in repo.iter_reverse_revision_history(br_rev_id):
 
719
        for revision_id in graph.iter_lefthand_ancestry(br_rev_id,
 
720
            (_mod_revision.NULL_REVISION,)):
452
721
            yield revision_id, str(cur_revno), 0
453
722
            cur_revno -= 1
454
723
    else:
455
724
        if end_rev_id is None:
456
725
            end_rev_id = br_rev_id
457
726
        found_start = start_rev_id is None
458
 
        for revision_id in repo.iter_reverse_revision_history(end_rev_id):
459
 
            revno = branch.revision_id_to_dotted_revno(revision_id)
460
 
            revno_str = '.'.join(str(n) for n in revno)
 
727
        for revision_id in graph.iter_lefthand_ancestry(end_rev_id,
 
728
                (_mod_revision.NULL_REVISION,)):
 
729
            revno_str = _compute_revno_str(branch, revision_id)
461
730
            if not found_start and revision_id == start_rev_id:
462
 
                yield revision_id, revno_str, 0
 
731
                if not exclude_common_ancestry:
 
732
                    yield revision_id, revno_str, 0
463
733
                found_start = True
464
734
                break
465
735
            else:
470
740
 
471
741
 
472
742
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
473
 
    rebase_initial_depths=True):
 
743
                          rebase_initial_depths=True,
 
744
                          exclude_common_ancestry=False):
474
745
    """Calculate revisions to view including merges, newest to oldest.
475
746
 
476
747
    :param branch: the branch
480
751
      revision is found?
481
752
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
482
753
    """
 
754
    if exclude_common_ancestry:
 
755
        stop_rule = 'with-merges-without-common-ancestry'
 
756
    else:
 
757
        stop_rule = 'with-merges'
483
758
    view_revisions = branch.iter_merge_sorted_revisions(
484
759
        start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
485
 
        stop_rule="with-merges")
 
760
        stop_rule=stop_rule)
486
761
    if not rebase_initial_depths:
487
762
        for (rev_id, merge_depth, revno, end_of_merge
488
763
             ) in view_revisions:
499
774
                depth_adjustment = merge_depth
500
775
            if depth_adjustment:
501
776
                if merge_depth < depth_adjustment:
 
777
                    # From now on we reduce the depth adjustement, this can be
 
778
                    # surprising for users. The alternative requires two passes
 
779
                    # which breaks the fast display of the first revision
 
780
                    # though.
502
781
                    depth_adjustment = merge_depth
503
782
                merge_depth -= depth_adjustment
504
783
            yield rev_id, '.'.join(map(str, revno)), merge_depth
505
784
 
506
785
 
 
786
@deprecated_function(deprecated_in((2, 2, 0)))
507
787
def calculate_view_revisions(branch, start_revision, end_revision, direction,
508
 
        specific_fileid, generate_merge_revisions, allow_single_merge_revision):
 
788
        specific_fileid, generate_merge_revisions):
509
789
    """Calculate the revisions to view.
510
790
 
511
791
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
512
792
             a list of the same tuples.
513
793
    """
514
 
    # This method is no longer called by the main code path.
515
 
    # It is retained for API compatibility and may be deprecated
516
 
    # soon. IGC 20090116
517
794
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
518
795
        end_revision)
519
796
    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))
 
797
        direction, generate_merge_revisions or specific_fileid))
522
798
    if specific_fileid:
523
799
        view_revisions = _filter_revisions_touching_file_id(branch,
524
800
            specific_fileid, view_revisions,
543
819
    :param branch: The branch being logged.
544
820
    :param view_revisions: The revisions being viewed.
545
821
    :param generate_delta: Whether to generate a delta for each revision.
 
822
      Permitted values are None, 'full' and 'partial'.
546
823
    :param search: A user text search string.
547
824
    :param file_ids: If non empty, only revisions matching one or more of
548
825
      the file-ids are to be kept.
587
864
    """
588
865
    if search is None:
589
866
        return log_rev_iterator
590
 
    # Compile the search now to get early errors.
591
 
    searchRE = re.compile(search, re.IGNORECASE)
 
867
    searchRE = lazy_regex.lazy_compile(search, re.IGNORECASE)
592
868
    return _filter_message_re(searchRE, log_rev_iterator)
593
869
 
594
870
 
607
883
 
608
884
    :param branch: The branch being logged.
609
885
    :param generate_delta: Whether to generate a delta for each revision.
 
886
      Permitted values are None, 'full' and 'partial'.
610
887
    :param search: A user text search string.
611
888
    :param log_rev_iterator: An input iterator containing all revisions that
612
889
        could be displayed, in lists.
622
899
        generate_delta, fileids, direction)
623
900
 
624
901
 
625
 
def _generate_deltas(repository, log_rev_iterator, always_delta, fileids,
 
902
def _generate_deltas(repository, log_rev_iterator, delta_type, fileids,
626
903
    direction):
627
904
    """Create deltas for each batch of revisions in log_rev_iterator.
628
905
 
646
923
        if check_fileids and not fileid_set:
647
924
            return
648
925
        revisions = [rev[1] for rev in revs]
649
 
        deltas = repository.get_deltas_for_revisions(revisions)
650
926
        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))
 
927
        if delta_type == 'full' and not check_fileids:
 
928
            deltas = repository.get_deltas_for_revisions(revisions)
 
929
            for rev, delta in izip(revs, deltas):
 
930
                new_revs.append((rev[0], rev[1], delta))
 
931
        else:
 
932
            deltas = repository.get_deltas_for_revisions(revisions, fileid_set)
 
933
            for rev, delta in izip(revs, deltas):
 
934
                if check_fileids:
 
935
                    if delta is None or not delta.has_changed():
 
936
                        continue
 
937
                    else:
 
938
                        _update_fileids(delta, fileid_set, stop_on)
 
939
                        if delta_type is None:
 
940
                            delta = None
 
941
                        elif delta_type == 'full':
 
942
                            # If the file matches all the time, rebuilding
 
943
                            # a full delta like this in addition to a partial
 
944
                            # one could be slow. However, it's likely that
 
945
                            # most revisions won't get this far, making it
 
946
                            # faster to filter on the partial deltas and
 
947
                            # build the occasional full delta than always
 
948
                            # building full deltas and filtering those.
 
949
                            rev_id = rev[0][0]
 
950
                            delta = repository.get_revision_delta(rev_id)
 
951
                new_revs.append((rev[0], rev[1], delta))
663
952
        yield new_revs
664
953
 
665
954
 
666
 
def _delta_matches_fileids(delta, fileids, stop_on='add'):
667
 
    """Check is a delta matches one of more file-ids.
668
 
 
669
 
    :param fileids: a set of fileids to match against.
 
955
def _update_fileids(delta, fileids, stop_on):
 
956
    """Update the set of file-ids to search based on file lifecycle events.
 
957
    
 
958
    :param fileids: a set of fileids to update
670
959
    :param stop_on: either 'add' or 'remove' - take file-ids out of the
671
960
      fileids set once their add or remove entry is detected respectively
672
961
    """
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
 
962
    if stop_on == 'add':
 
963
        for item in delta.added:
 
964
            if item[1] in fileids:
 
965
                fileids.remove(item[1])
 
966
    elif stop_on == 'delete':
 
967
        for item in delta.removed:
 
968
            if item[1] in fileids:
 
969
                fileids.remove(item[1])
693
970
 
694
971
 
695
972
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
847
1124
    cur_revno = branch_revno
848
1125
    rev_nos = {}
849
1126
    mainline_revs = []
850
 
    for revision_id in branch.repository.iter_reverse_revision_history(
851
 
                        branch_last_revision):
 
1127
    graph = branch.repository.get_graph()
 
1128
    for revision_id in graph.iter_lefthand_ancestry(
 
1129
            branch_last_revision, (_mod_revision.NULL_REVISION,)):
852
1130
        if cur_revno < start_revno:
853
1131
            # We have gone far enough, but we always add 1 more revision
854
1132
            rev_nos[revision_id] = cur_revno
868
1146
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
869
1147
 
870
1148
 
 
1149
@deprecated_function(deprecated_in((2, 2, 0)))
871
1150
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
872
1151
    """Filter view_revisions based on revision ranges.
873
1152
 
882
1161
 
883
1162
    :return: The filtered view_revisions.
884
1163
    """
885
 
    # This method is no longer called by the main code path.
886
 
    # It may be removed soon. IGC 20090127
887
1164
    if start_rev_id or end_rev_id:
888
1165
        revision_ids = [r for r, n, d in view_revisions]
889
1166
        if start_rev_id:
921
1198
    This includes the revisions which directly change the file id,
922
1199
    and the revisions which merge these changes. So if the
923
1200
    revision graph is::
 
1201
 
924
1202
        A-.
925
1203
        |\ \
926
1204
        B C E
953
1231
    """
954
1232
    # Lookup all possible text keys to determine which ones actually modified
955
1233
    # the file.
 
1234
    graph = branch.repository.get_file_graph()
 
1235
    get_parent_map = graph.get_parent_map
956
1236
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
 
1237
    next_keys = None
957
1238
    # Looking up keys in batches of 1000 can cut the time in half, as well as
958
1239
    # memory consumption. GraphIndex *does* like to look for a few keys in
959
1240
    # parallel, it just doesn't like looking for *lots* of keys in parallel.
961
1242
    #       indexing layer. We might consider passing in hints as to the known
962
1243
    #       access pattern (sparse/clustered, high success rate/low success
963
1244
    #       rate). This particular access is clustered with a low success rate.
964
 
    get_parent_map = branch.repository.texts.get_parent_map
965
1245
    modified_text_revisions = set()
966
1246
    chunk_size = 1000
967
1247
    for start in xrange(0, len(text_keys), chunk_size):
994
1274
    return result
995
1275
 
996
1276
 
 
1277
@deprecated_function(deprecated_in((2, 2, 0)))
997
1278
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
998
1279
                       include_merges=True):
999
1280
    """Produce an iterator of revisions to show
1000
1281
    :return: an iterator of (revision_id, revno, merge_depth)
1001
1282
    (if there is no revno for a revision, None is supplied)
1002
1283
    """
1003
 
    # This method is no longer called by the main code path.
1004
 
    # It is retained for API compatibility and may be deprecated
1005
 
    # soon. IGC 20090127
1006
1284
    if not include_merges:
1007
1285
        revision_ids = mainline_revs[1:]
1008
1286
        if direction == 'reverse':
1077
1355
    """
1078
1356
 
1079
1357
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
1080
 
                 tags=None, diff=None):
 
1358
                 tags=None, diff=None, signature=None):
1081
1359
        self.rev = rev
1082
 
        self.revno = str(revno)
 
1360
        if revno is None:
 
1361
            self.revno = None
 
1362
        else:
 
1363
            self.revno = str(revno)
1083
1364
        self.merge_depth = merge_depth
1084
1365
        self.delta = delta
1085
1366
        self.tags = tags
1086
1367
        self.diff = diff
 
1368
        self.signature = signature
1087
1369
 
1088
1370
 
1089
1371
class LogFormatter(object):
1098
1380
    to indicate which LogRevision attributes it supports:
1099
1381
 
1100
1382
    - supports_delta must be True if this log formatter supports delta.
1101
 
        Otherwise the delta attribute may not be populated.  The 'delta_format'
1102
 
        attribute describes whether the 'short_status' format (1) or the long
1103
 
        one (2) should be used.
 
1383
      Otherwise the delta attribute may not be populated.  The 'delta_format'
 
1384
      attribute describes whether the 'short_status' format (1) or the long
 
1385
      one (2) should be used.
1104
1386
 
1105
1387
    - 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.
 
1388
      merge revisions.  If not, then only mainline revisions will be passed
 
1389
      to the formatter.
1109
1390
 
1110
1391
    - preferred_levels is the number of levels this formatter defaults to.
1111
 
        The default value is zero meaning display all levels.
1112
 
        This value is only relevant if supports_merge_revisions is True.
1113
 
 
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.
 
1392
      The default value is zero meaning display all levels.
 
1393
      This value is only relevant if supports_merge_revisions is True.
1117
1394
 
1118
1395
    - supports_tags must be True if this log formatter supports tags.
1119
 
        Otherwise the tags attribute may not be populated.
 
1396
      Otherwise the tags attribute may not be populated.
1120
1397
 
1121
1398
    - supports_diff must be True if this log formatter supports diffs.
1122
 
        Otherwise the diff attribute may not be populated.
 
1399
      Otherwise the diff attribute may not be populated.
 
1400
 
 
1401
    - supports_signatures must be True if this log formatter supports GPG
 
1402
      signatures.
1123
1403
 
1124
1404
    Plugins can register functions to show custom revision properties using
1125
1405
    the properties_handler_registry. The registered function
1126
 
    must respect the following interface description:
 
1406
    must respect the following interface description::
 
1407
 
1127
1408
        def my_show_properties(properties_dict):
1128
1409
            # code that returns a dict {'name':'value'} of the properties
1129
1410
            # to be shown
1131
1412
    preferred_levels = 0
1132
1413
 
1133
1414
    def __init__(self, to_file, show_ids=False, show_timezone='original',
1134
 
                 delta_format=None, levels=None):
 
1415
                 delta_format=None, levels=None, show_advice=False,
 
1416
                 to_exact_file=None, author_list_handler=None):
1135
1417
        """Create a LogFormatter.
1136
1418
 
1137
1419
        :param to_file: the file to output to
 
1420
        :param to_exact_file: if set, gives an output stream to which 
 
1421
             non-Unicode diffs are written.
1138
1422
        :param show_ids: if True, revision-ids are to be displayed
1139
1423
        :param show_timezone: the timezone to use
1140
1424
        :param delta_format: the level of delta information to display
1141
 
          or None to leave it u to the formatter to decide
 
1425
          or None to leave it to the formatter to decide
1142
1426
        :param levels: the number of levels to display; None or -1 to
1143
1427
          let the log formatter decide.
 
1428
        :param show_advice: whether to show advice at the end of the
 
1429
          log or not
 
1430
        :param author_list_handler: callable generating a list of
 
1431
          authors to display for a given revision
1144
1432
        """
1145
1433
        self.to_file = to_file
1146
1434
        # 'exact' stream used to show diff, it should print content 'as is'
1147
1435
        # and should not try to decode/encode it to unicode to avoid bug #328007
1148
 
        self.to_exact_file = getattr(to_file, 'stream', to_file)
 
1436
        if to_exact_file is not None:
 
1437
            self.to_exact_file = to_exact_file
 
1438
        else:
 
1439
            # XXX: somewhat hacky; this assumes it's a codec writer; it's better
 
1440
            # for code that expects to get diffs to pass in the exact file
 
1441
            # stream
 
1442
            self.to_exact_file = getattr(to_file, 'stream', to_file)
1149
1443
        self.show_ids = show_ids
1150
1444
        self.show_timezone = show_timezone
1151
1445
        if delta_format is None:
1153
1447
            delta_format = 2 # long format
1154
1448
        self.delta_format = delta_format
1155
1449
        self.levels = levels
 
1450
        self._show_advice = show_advice
 
1451
        self._merge_count = 0
 
1452
        self._author_list_handler = author_list_handler
1156
1453
 
1157
1454
    def get_levels(self):
1158
1455
        """Get the number of levels to display or 0 for all."""
1159
1456
        if getattr(self, 'supports_merge_revisions', False):
1160
1457
            if self.levels is None or self.levels == -1:
1161
 
                return self.preferred_levels
1162
 
            else:
1163
 
                return self.levels
1164
 
        return 1
 
1458
                self.levels = self.preferred_levels
 
1459
        else:
 
1460
            self.levels = 1
 
1461
        return self.levels
1165
1462
 
1166
1463
    def log_revision(self, revision):
1167
1464
        """Log a revision.
1170
1467
        """
1171
1468
        raise NotImplementedError('not implemented in abstract base')
1172
1469
 
 
1470
    def show_advice(self):
 
1471
        """Output user advice, if any, when the log is completed."""
 
1472
        if self._show_advice and self.levels == 1 and self._merge_count > 0:
 
1473
            advice_sep = self.get_advice_separator()
 
1474
            if advice_sep:
 
1475
                self.to_file.write(advice_sep)
 
1476
            self.to_file.write(
 
1477
                "Use --include-merges or -n0 to see merged revisions.\n")
 
1478
 
 
1479
    def get_advice_separator(self):
 
1480
        """Get the text separating the log from the closing advice."""
 
1481
        return ''
 
1482
 
1173
1483
    def short_committer(self, rev):
1174
1484
        name, address = config.parse_username(rev.committer)
1175
1485
        if name:
1177
1487
        return address
1178
1488
 
1179
1489
    def short_author(self, rev):
1180
 
        name, address = config.parse_username(rev.get_apparent_authors()[0])
1181
 
        if name:
1182
 
            return name
1183
 
        return address
 
1490
        return self.authors(rev, 'first', short=True, sep=', ')
 
1491
 
 
1492
    def authors(self, rev, who, short=False, sep=None):
 
1493
        """Generate list of authors, taking --authors option into account.
 
1494
 
 
1495
        The caller has to specify the name of a author list handler,
 
1496
        as provided by the author list registry, using the ``who``
 
1497
        argument.  That name only sets a default, though: when the
 
1498
        user selected a different author list generation using the
 
1499
        ``--authors`` command line switch, as represented by the
 
1500
        ``author_list_handler`` constructor argument, that value takes
 
1501
        precedence.
 
1502
 
 
1503
        :param rev: The revision for which to generate the list of authors.
 
1504
        :param who: Name of the default handler.
 
1505
        :param short: Whether to shorten names to either name or address.
 
1506
        :param sep: What separator to use for automatic concatenation.
 
1507
        """
 
1508
        if self._author_list_handler is not None:
 
1509
            # The user did specify --authors, which overrides the default
 
1510
            author_list_handler = self._author_list_handler
 
1511
        else:
 
1512
            # The user didn't specify --authors, so we use the caller's default
 
1513
            author_list_handler = author_list_registry.get(who)
 
1514
        names = author_list_handler(rev)
 
1515
        if short:
 
1516
            for i in range(len(names)):
 
1517
                name, address = config.parse_username(names[i])
 
1518
                if name:
 
1519
                    names[i] = name
 
1520
                else:
 
1521
                    names[i] = address
 
1522
        if sep is not None:
 
1523
            names = sep.join(names)
 
1524
        return names
 
1525
 
 
1526
    def merge_marker(self, revision):
 
1527
        """Get the merge marker to include in the output or '' if none."""
 
1528
        if len(revision.rev.parent_ids) > 1:
 
1529
            self._merge_count += 1
 
1530
            return ' [merge]'
 
1531
        else:
 
1532
            return ''
1184
1533
 
1185
1534
    def show_properties(self, revision, indent):
1186
1535
        """Displays the custom properties returned by each registered handler.
1187
1536
 
1188
1537
        If a registered handler raises an error it is propagated.
1189
1538
        """
 
1539
        for line in self.custom_properties(revision):
 
1540
            self.to_file.write("%s%s\n" % (indent, line))
 
1541
 
 
1542
    def custom_properties(self, revision):
 
1543
        """Format the custom properties returned by each registered handler.
 
1544
 
 
1545
        If a registered handler raises an error it is propagated.
 
1546
 
 
1547
        :return: a list of formatted lines (excluding trailing newlines)
 
1548
        """
 
1549
        lines = self._foreign_info_properties(revision)
1190
1550
        for key, handler in properties_handler_registry.iteritems():
1191
 
            for key, value in handler(revision).items():
1192
 
                self.to_file.write(indent + key + ': ' + value + '\n')
 
1551
            lines.extend(self._format_properties(handler(revision)))
 
1552
        return lines
 
1553
 
 
1554
    def _foreign_info_properties(self, rev):
 
1555
        """Custom log displayer for foreign revision identifiers.
 
1556
 
 
1557
        :param rev: Revision object.
 
1558
        """
 
1559
        # Revision comes directly from a foreign repository
 
1560
        if isinstance(rev, foreign.ForeignRevision):
 
1561
            return self._format_properties(
 
1562
                rev.mapping.vcs.show_foreign_revid(rev.foreign_revid))
 
1563
 
 
1564
        # Imported foreign revision revision ids always contain :
 
1565
        if not ":" in rev.revision_id:
 
1566
            return []
 
1567
 
 
1568
        # Revision was once imported from a foreign repository
 
1569
        try:
 
1570
            foreign_revid, mapping = \
 
1571
                foreign.foreign_vcs_registry.parse_revision_id(rev.revision_id)
 
1572
        except errors.InvalidRevisionId:
 
1573
            return []
 
1574
 
 
1575
        return self._format_properties(
 
1576
            mapping.vcs.show_foreign_revid(foreign_revid))
 
1577
 
 
1578
    def _format_properties(self, properties):
 
1579
        lines = []
 
1580
        for key, value in properties.items():
 
1581
            lines.append(key + ': ' + value)
 
1582
        return lines
1193
1583
 
1194
1584
    def show_diff(self, to_file, diff, indent):
1195
1585
        for l in diff.rstrip().split('\n'):
1196
1586
            to_file.write(indent + '%s\n' % (l,))
1197
1587
 
1198
1588
 
 
1589
# Separator between revisions in long format
 
1590
_LONG_SEP = '-' * 60
 
1591
 
 
1592
 
1199
1593
class LongLogFormatter(LogFormatter):
1200
1594
 
1201
1595
    supports_merge_revisions = True
 
1596
    preferred_levels = 1
1202
1597
    supports_delta = True
1203
1598
    supports_tags = True
1204
1599
    supports_diff = True
 
1600
    supports_signatures = True
 
1601
 
 
1602
    def __init__(self, *args, **kwargs):
 
1603
        super(LongLogFormatter, self).__init__(*args, **kwargs)
 
1604
        if self.show_timezone == 'original':
 
1605
            self.date_string = self._date_string_original_timezone
 
1606
        else:
 
1607
            self.date_string = self._date_string_with_timezone
 
1608
 
 
1609
    def _date_string_with_timezone(self, rev):
 
1610
        return format_date(rev.timestamp, rev.timezone or 0,
 
1611
                           self.show_timezone)
 
1612
 
 
1613
    def _date_string_original_timezone(self, rev):
 
1614
        return format_date_with_offset_in_original_timezone(rev.timestamp,
 
1615
            rev.timezone or 0)
1205
1616
 
1206
1617
    def log_revision(self, revision):
1207
1618
        """Log a revision, either merged or not."""
1208
1619
        indent = '    ' * revision.merge_depth
1209
 
        to_file = self.to_file
1210
 
        to_file.write(indent + '-' * 60 + '\n')
 
1620
        lines = [_LONG_SEP]
1211
1621
        if revision.revno is not None:
1212
 
            to_file.write(indent + 'revno: %s\n' % (revision.revno,))
 
1622
            lines.append('revno: %s%s' % (revision.revno,
 
1623
                self.merge_marker(revision)))
1213
1624
        if revision.tags:
1214
 
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
 
1625
            lines.append('tags: %s' % (', '.join(revision.tags)))
 
1626
        if self.show_ids or revision.revno is None:
 
1627
            lines.append('revision-id: %s' % (revision.rev.revision_id,))
1215
1628
        if self.show_ids:
1216
 
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
1217
 
            to_file.write('\n')
1218
1629
            for parent_id in revision.rev.parent_ids:
1219
 
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
1220
 
        self.show_properties(revision.rev, indent)
 
1630
                lines.append('parent: %s' % (parent_id,))
 
1631
        lines.extend(self.custom_properties(revision.rev))
1221
1632
 
1222
1633
        committer = revision.rev.committer
1223
 
        authors = revision.rev.get_apparent_authors()
 
1634
        authors = self.authors(revision.rev, 'all')
1224
1635
        if authors != [committer]:
1225
 
            to_file.write(indent + 'author: %s\n' % (", ".join(authors),))
1226
 
        to_file.write(indent + 'committer: %s\n' % (committer,))
 
1636
            lines.append('author: %s' % (", ".join(authors),))
 
1637
        lines.append('committer: %s' % (committer,))
1227
1638
 
1228
1639
        branch_nick = revision.rev.properties.get('branch-nick', None)
1229
1640
        if branch_nick is not None:
1230
 
            to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
1231
 
 
1232
 
        date_str = format_date(revision.rev.timestamp,
1233
 
                               revision.rev.timezone or 0,
1234
 
                               self.show_timezone)
1235
 
        to_file.write(indent + 'timestamp: %s\n' % (date_str,))
1236
 
 
1237
 
        to_file.write(indent + 'message:\n')
 
1641
            lines.append('branch nick: %s' % (branch_nick,))
 
1642
 
 
1643
        lines.append('timestamp: %s' % (self.date_string(revision.rev),))
 
1644
 
 
1645
        if revision.signature is not None:
 
1646
            lines.append('signature: ' + revision.signature)
 
1647
 
 
1648
        lines.append('message:')
1238
1649
        if not revision.rev.message:
1239
 
            to_file.write(indent + '  (no message)\n')
 
1650
            lines.append('  (no message)')
1240
1651
        else:
1241
1652
            message = revision.rev.message.rstrip('\r\n')
1242
1653
            for l in message.split('\n'):
1243
 
                to_file.write(indent + '  %s\n' % (l,))
 
1654
                lines.append('  %s' % (l,))
 
1655
 
 
1656
        # Dump the output, appending the delta and diff if requested
 
1657
        to_file = self.to_file
 
1658
        to_file.write("%s%s\n" % (indent, ('\n' + indent).join(lines)))
1244
1659
        if revision.delta is not None:
1245
 
            # We don't respect delta_format for compatibility
1246
 
            revision.delta.show(to_file, self.show_ids, indent=indent,
1247
 
                                short_status=False)
 
1660
            # Use the standard status output to display changes
 
1661
            from bzrlib.delta import report_delta
 
1662
            report_delta(to_file, revision.delta, short_status=False, 
 
1663
                         show_ids=self.show_ids, indent=indent)
1248
1664
        if revision.diff is not None:
1249
1665
            to_file.write(indent + 'diff:\n')
 
1666
            to_file.flush()
1250
1667
            # Note: we explicitly don't indent the diff (relative to the
1251
1668
            # revision information) so that the output can be fed to patch -p0
1252
1669
            self.show_diff(self.to_exact_file, revision.diff, indent)
 
1670
            self.to_exact_file.flush()
 
1671
 
 
1672
    def get_advice_separator(self):
 
1673
        """Get the text separating the log from the closing advice."""
 
1674
        return '-' * 60 + '\n'
1253
1675
 
1254
1676
 
1255
1677
class ShortLogFormatter(LogFormatter):
1275
1697
        indent = '    ' * depth
1276
1698
        revno_width = self.revno_width_by_depth.get(depth)
1277
1699
        if revno_width is None:
1278
 
            if revision.revno.find('.') == -1:
 
1700
            if revision.revno is None or revision.revno.find('.') == -1:
1279
1701
                # mainline revno, e.g. 12345
1280
1702
                revno_width = 5
1281
1703
            else:
1285
1707
        offset = ' ' * (revno_width + 1)
1286
1708
 
1287
1709
        to_file = self.to_file
1288
 
        is_merge = ''
1289
 
        if len(revision.rev.parent_ids) > 1:
1290
 
            is_merge = ' [merge]'
1291
1710
        tags = ''
1292
1711
        if revision.tags:
1293
1712
            tags = ' {%s}' % (', '.join(revision.tags))
1294
1713
        to_file.write(indent + "%*s %s\t%s%s%s\n" % (revno_width,
1295
 
                revision.revno, self.short_author(revision.rev),
 
1714
                revision.revno or "", self.short_author(revision.rev),
1296
1715
                format_date(revision.rev.timestamp,
1297
1716
                            revision.rev.timezone or 0,
1298
1717
                            self.show_timezone, date_fmt="%Y-%m-%d",
1299
1718
                            show_offset=False),
1300
 
                tags, is_merge))
 
1719
                tags, self.merge_marker(revision)))
1301
1720
        self.show_properties(revision.rev, indent+offset)
1302
 
        if self.show_ids:
 
1721
        if self.show_ids or revision.revno is None:
1303
1722
            to_file.write(indent + offset + 'revision-id:%s\n'
1304
1723
                          % (revision.rev.revision_id,))
1305
1724
        if not revision.rev.message:
1310
1729
                to_file.write(indent + offset + '%s\n' % (l,))
1311
1730
 
1312
1731
        if revision.delta is not None:
1313
 
            revision.delta.show(to_file, self.show_ids, indent=indent + offset,
1314
 
                                short_status=self.delta_format==1)
 
1732
            # Use the standard status output to display changes
 
1733
            from bzrlib.delta import report_delta
 
1734
            report_delta(to_file, revision.delta, 
 
1735
                         short_status=self.delta_format==1, 
 
1736
                         show_ids=self.show_ids, indent=indent + offset)
1315
1737
        if revision.diff is not None:
1316
1738
            self.show_diff(self.to_exact_file, revision.diff, '      ')
1317
1739
        to_file.write('\n')
1325
1747
 
1326
1748
    def __init__(self, *args, **kwargs):
1327
1749
        super(LineLogFormatter, self).__init__(*args, **kwargs)
1328
 
        self._max_chars = terminal_width() - 1
 
1750
        width = terminal_width()
 
1751
        if width is not None:
 
1752
            # we need one extra space for terminals that wrap on last char
 
1753
            width = width - 1
 
1754
        self._max_chars = width
1329
1755
 
1330
1756
    def truncate(self, str, max_len):
1331
 
        if len(str) <= max_len:
 
1757
        if max_len is None or len(str) <= max_len:
1332
1758
            return str
1333
 
        return str[:max_len-3]+'...'
 
1759
        return str[:max_len-3] + '...'
1334
1760
 
1335
1761
    def date_string(self, rev):
1336
1762
        return format_date(rev.timestamp, rev.timezone or 0,
1351
1777
 
1352
1778
    def log_string(self, revno, rev, max_chars, tags=None, prefix=''):
1353
1779
        """Format log info into one string. Truncate tail of string
1354
 
        :param  revno:      revision number or None.
1355
 
                            Revision numbers counts from 1.
1356
 
        :param  rev:        revision object
1357
 
        :param  max_chars:  maximum length of resulting string
1358
 
        :param  tags:       list of tags or None
1359
 
        :param  prefix:     string to prefix each line
1360
 
        :return:            formatted truncated string
 
1780
 
 
1781
        :param revno:      revision number or None.
 
1782
                           Revision numbers counts from 1.
 
1783
        :param rev:        revision object
 
1784
        :param max_chars:  maximum length of resulting string
 
1785
        :param tags:       list of tags or None
 
1786
        :param prefix:     string to prefix each line
 
1787
        :return:           formatted truncated string
1361
1788
        """
1362
1789
        out = []
1363
1790
        if revno:
1364
1791
            # show revno only when is not None
1365
1792
            out.append("%s:" % revno)
1366
 
        out.append(self.truncate(self.short_author(rev), 20))
 
1793
        if max_chars is not None:
 
1794
            out.append(self.truncate(self.short_author(rev), (max_chars+3)/4))
 
1795
        else:
 
1796
            out.append(self.short_author(rev))
1367
1797
        out.append(self.date_string(rev))
1368
1798
        if len(rev.parent_ids) > 1:
1369
1799
            out.append('[merge]')
1388
1818
                               self.show_timezone,
1389
1819
                               date_fmt='%Y-%m-%d',
1390
1820
                               show_offset=False)
1391
 
        committer_str = revision.rev.committer.replace (' <', '  <')
 
1821
        committer_str = self.authors(revision.rev, 'first', sep=', ')
 
1822
        committer_str = committer_str.replace(' <', '  <')
1392
1823
        to_file.write('%s  %s\n\n' % (date_str,committer_str))
1393
1824
 
1394
1825
        if revision.delta is not None and revision.delta.has_changed():
1459
1890
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
1460
1891
 
1461
1892
 
 
1893
def author_list_all(rev):
 
1894
    return rev.get_apparent_authors()[:]
 
1895
 
 
1896
 
 
1897
def author_list_first(rev):
 
1898
    lst = rev.get_apparent_authors()
 
1899
    try:
 
1900
        return [lst[0]]
 
1901
    except IndexError:
 
1902
        return []
 
1903
 
 
1904
 
 
1905
def author_list_committer(rev):
 
1906
    return [rev.committer]
 
1907
 
 
1908
 
 
1909
author_list_registry = registry.Registry()
 
1910
 
 
1911
author_list_registry.register('all', author_list_all,
 
1912
                              'All authors')
 
1913
 
 
1914
author_list_registry.register('first', author_list_first,
 
1915
                              'The first author')
 
1916
 
 
1917
author_list_registry.register('committer', author_list_committer,
 
1918
                              'The committer')
 
1919
 
 
1920
 
1462
1921
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
1463
1922
    # deprecated; for compatibility
1464
1923
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
1533
1992
    old_revisions = set()
1534
1993
    new_history = []
1535
1994
    new_revisions = set()
1536
 
    new_iter = repository.iter_reverse_revision_history(new_revision_id)
1537
 
    old_iter = repository.iter_reverse_revision_history(old_revision_id)
 
1995
    graph = repository.get_graph()
 
1996
    new_iter = graph.iter_lefthand_ancestry(new_revision_id)
 
1997
    old_iter = graph.iter_lefthand_ancestry(old_revision_id)
1538
1998
    stop_revision = None
1539
1999
    do_old = True
1540
2000
    do_new = True
1615
2075
        lf.log_revision(lr)
1616
2076
 
1617
2077
 
1618
 
def _get_fileid_to_log(revision, tree, b, fp):
1619
 
    """Find the file-id to log for a file path in a revision range.
1620
 
 
1621
 
    :param revision: the revision range as parsed on the command line
1622
 
    :param tree: the working tree, if any
1623
 
    :param b: the branch
1624
 
    :param fp: file path
 
2078
def _get_info_for_log_files(revisionspec_list, file_list, add_cleanup):
 
2079
    """Find file-ids and kinds given a list of files and a revision range.
 
2080
 
 
2081
    We search for files at the end of the range. If not found there,
 
2082
    we try the start of the range.
 
2083
 
 
2084
    :param revisionspec_list: revision range as parsed on the command line
 
2085
    :param file_list: the list of paths given on the command line;
 
2086
      the first of these can be a branch location or a file path,
 
2087
      the remainder must be file paths
 
2088
    :param add_cleanup: When the branch returned is read locked,
 
2089
      an unlock call will be queued to the cleanup.
 
2090
    :return: (branch, info_list, start_rev_info, end_rev_info) where
 
2091
      info_list is a list of (relative_path, file_id, kind) tuples where
 
2092
      kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
 
2093
      branch will be read-locked.
1625
2094
    """
1626
 
    if revision is None:
 
2095
    from builtins import _get_revision_range
 
2096
    tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
 
2097
    add_cleanup(b.lock_read().unlock)
 
2098
    # XXX: It's damn messy converting a list of paths to relative paths when
 
2099
    # those paths might be deleted ones, they might be on a case-insensitive
 
2100
    # filesystem and/or they might be in silly locations (like another branch).
 
2101
    # For example, what should "log bzr://branch/dir/file1 file2" do? (Is
 
2102
    # file2 implicitly in the same dir as file1 or should its directory be
 
2103
    # taken from the current tree somehow?) For now, this solves the common
 
2104
    # case of running log in a nested directory, assuming paths beyond the
 
2105
    # first one haven't been deleted ...
 
2106
    if tree:
 
2107
        relpaths = [path] + tree.safe_relpath_files(file_list[1:])
 
2108
    else:
 
2109
        relpaths = [path] + file_list[1:]
 
2110
    info_list = []
 
2111
    start_rev_info, end_rev_info = _get_revision_range(revisionspec_list, b,
 
2112
        "log")
 
2113
    if relpaths in ([], [u'']):
 
2114
        return b, [], start_rev_info, end_rev_info
 
2115
    if start_rev_info is None and end_rev_info is None:
1627
2116
        if tree is None:
1628
2117
            tree = b.basis_tree()
1629
 
        file_id = tree.path2id(fp)
1630
 
        if file_id is None:
1631
 
            # go back to when time began
1632
 
            try:
1633
 
                rev1 = b.get_rev_id(1)
1634
 
            except errors.NoSuchRevision:
1635
 
                # No history at all
1636
 
                file_id = None
1637
 
            else:
1638
 
                tree = b.repository.revision_tree(rev1)
1639
 
                file_id = tree.path2id(fp)
 
2118
        tree1 = None
 
2119
        for fp in relpaths:
 
2120
            file_id = tree.path2id(fp)
 
2121
            kind = _get_kind_for_file_id(tree, file_id)
 
2122
            if file_id is None:
 
2123
                # go back to when time began
 
2124
                if tree1 is None:
 
2125
                    try:
 
2126
                        rev1 = b.get_rev_id(1)
 
2127
                    except errors.NoSuchRevision:
 
2128
                        # No history at all
 
2129
                        file_id = None
 
2130
                        kind = None
 
2131
                    else:
 
2132
                        tree1 = b.repository.revision_tree(rev1)
 
2133
                if tree1:
 
2134
                    file_id = tree1.path2id(fp)
 
2135
                    kind = _get_kind_for_file_id(tree1, file_id)
 
2136
            info_list.append((fp, file_id, kind))
1640
2137
 
1641
 
    elif len(revision) == 1:
 
2138
    elif start_rev_info == end_rev_info:
1642
2139
        # One revision given - file must exist in it
1643
 
        tree = revision[0].as_tree(b)
1644
 
        file_id = tree.path2id(fp)
 
2140
        tree = b.repository.revision_tree(end_rev_info.rev_id)
 
2141
        for fp in relpaths:
 
2142
            file_id = tree.path2id(fp)
 
2143
            kind = _get_kind_for_file_id(tree, file_id)
 
2144
            info_list.append((fp, file_id, kind))
1645
2145
 
1646
 
    elif len(revision) == 2:
 
2146
    else:
1647
2147
        # Revision range given. Get the file-id from the end tree.
1648
2148
        # If that fails, try the start tree.
1649
 
        rev_id = revision[1].as_revision_id(b)
 
2149
        rev_id = end_rev_info.rev_id
1650
2150
        if rev_id is None:
1651
2151
            tree = b.basis_tree()
1652
2152
        else:
1653
 
            tree = revision[1].as_tree(b)
1654
 
        file_id = tree.path2id(fp)
1655
 
        if file_id is None:
1656
 
            rev_id = revision[0].as_revision_id(b)
1657
 
            if rev_id is None:
1658
 
                rev1 = b.get_rev_id(1)
1659
 
                tree = b.repository.revision_tree(rev1)
1660
 
            else:
1661
 
                tree = revision[0].as_tree(b)
 
2153
            tree = b.repository.revision_tree(rev_id)
 
2154
        tree1 = None
 
2155
        for fp in relpaths:
1662
2156
            file_id = tree.path2id(fp)
 
2157
            kind = _get_kind_for_file_id(tree, file_id)
 
2158
            if file_id is None:
 
2159
                if tree1 is None:
 
2160
                    rev_id = start_rev_info.rev_id
 
2161
                    if rev_id is None:
 
2162
                        rev1 = b.get_rev_id(1)
 
2163
                        tree1 = b.repository.revision_tree(rev1)
 
2164
                    else:
 
2165
                        tree1 = b.repository.revision_tree(rev_id)
 
2166
                file_id = tree1.path2id(fp)
 
2167
                kind = _get_kind_for_file_id(tree1, file_id)
 
2168
            info_list.append((fp, file_id, kind))
 
2169
    return b, info_list, start_rev_info, end_rev_info
 
2170
 
 
2171
 
 
2172
def _get_kind_for_file_id(tree, file_id):
 
2173
    """Return the kind of a file-id or None if it doesn't exist."""
 
2174
    if file_id is not None:
 
2175
        return tree.kind(file_id)
1663
2176
    else:
1664
 
        raise errors.BzrCommandError(
1665
 
            'bzr log --revision takes one or two values.')
1666
 
    return file_id
 
2177
        return None
1667
2178
 
1668
2179
 
1669
2180
properties_handler_registry = registry.Registry()
1670
 
properties_handler_registry.register_lazy("foreign",
1671
 
                                          "bzrlib.foreign",
1672
 
                                          "show_foreign_properties")
 
2181
 
 
2182
# Use the properties handlers to print out bug information if available
 
2183
def _bugs_properties_handler(revision):
 
2184
    if revision.properties.has_key('bugs'):
 
2185
        bug_lines = revision.properties['bugs'].split('\n')
 
2186
        bug_rows = [line.split(' ', 1) for line in bug_lines]
 
2187
        fixed_bug_urls = [row[0] for row in bug_rows if
 
2188
                          len(row) > 1 and row[1] == 'fixed']
 
2189
 
 
2190
        if fixed_bug_urls:
 
2191
            return {'fixes bug(s)': ' '.join(fixed_bug_urls)}
 
2192
    return {}
 
2193
 
 
2194
properties_handler_registry.register('bugs_properties_handler',
 
2195
                                     _bugs_properties_handler)
1673
2196
 
1674
2197
 
1675
2198
# adapters which revision ids to log are filtered. When log is called, the