/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/log.py

  • Committer: Robert Collins
  • Date: 2009-03-27 04:36:58 UTC
  • mto: This revision was merged to the branch mainline in revision 4216.
  • Revision ID: robertc@robertcollins.net-20090327043658-vzfmwbuhd7pam1m7
Correct logic for detecting when to use record_iter_changes in commit.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2009 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
 
 
19
"""Code to show logs of changes.
 
20
 
 
21
Various flavors of log can be produced:
 
22
 
 
23
* for one file, or the whole tree, and (not done yet) for
 
24
  files in a given directory
 
25
 
 
26
* in "verbose" mode with a description of what changed from one
 
27
  version to the next
 
28
 
 
29
* with file-ids and revision-ids shown
 
30
 
 
31
Logs are actually written out through an abstract LogFormatter
 
32
interface, which allows for different preferred formats.  Plugins can
 
33
register formats too.
 
34
 
 
35
Logs can be produced in either forward (oldest->newest) or reverse
 
36
(newest->oldest) order.
 
37
 
 
38
Logs can be filtered to show only revisions matching a particular
 
39
search string, or within a particular range of revisions.  The range
 
40
can be given as date/times, which are reduced to revisions before
 
41
calling in here.
 
42
 
 
43
In verbose mode we show a summary of what changed in each particular
 
44
revision.  Note that this is the delta for changes in that revision
 
45
relative to its left-most parent, not the delta relative to the last
 
46
logged revision.  So for example if you ask for a verbose log of
 
47
changes touching hello.c you will get a list of those revisions also
 
48
listing other things that were changed in the same revision, but not
 
49
all the changes since the previous revision that touched hello.c.
 
50
"""
 
51
 
 
52
import codecs
 
53
from cStringIO import StringIO
 
54
from itertools import (
 
55
    chain,
 
56
    izip,
 
57
    )
 
58
import re
 
59
import sys
 
60
from warnings import (
 
61
    warn,
 
62
    )
 
63
 
 
64
from bzrlib.lazy_import import lazy_import
 
65
lazy_import(globals(), """
 
66
 
 
67
from bzrlib import (
 
68
    bzrdir,
 
69
    config,
 
70
    diff,
 
71
    errors,
 
72
    repository as _mod_repository,
 
73
    revision as _mod_revision,
 
74
    revisionspec,
 
75
    trace,
 
76
    tsort,
 
77
    )
 
78
""")
 
79
 
 
80
from bzrlib import (
 
81
    registry,
 
82
    )
 
83
from bzrlib.osutils import (
 
84
    format_date,
 
85
    get_terminal_encoding,
 
86
    re_compile_checked,
 
87
    terminal_width,
 
88
    )
 
89
 
 
90
 
 
91
def find_touching_revisions(branch, file_id):
 
92
    """Yield a description of revisions which affect the file_id.
 
93
 
 
94
    Each returned element is (revno, revision_id, description)
 
95
 
 
96
    This is the list of revisions where the file is either added,
 
97
    modified, renamed or deleted.
 
98
 
 
99
    TODO: Perhaps some way to limit this to only particular revisions,
 
100
    or to traverse a non-mainline set of revisions?
 
101
    """
 
102
    last_ie = None
 
103
    last_path = None
 
104
    revno = 1
 
105
    for revision_id in branch.revision_history():
 
106
        this_inv = branch.repository.get_revision_inventory(revision_id)
 
107
        if file_id in this_inv:
 
108
            this_ie = this_inv[file_id]
 
109
            this_path = this_inv.id2path(file_id)
 
110
        else:
 
111
            this_ie = this_path = None
 
112
 
 
113
        # now we know how it was last time, and how it is in this revision.
 
114
        # are those two states effectively the same or not?
 
115
 
 
116
        if not this_ie and not last_ie:
 
117
            # not present in either
 
118
            pass
 
119
        elif this_ie and not last_ie:
 
120
            yield revno, revision_id, "added " + this_path
 
121
        elif not this_ie and last_ie:
 
122
            # deleted here
 
123
            yield revno, revision_id, "deleted " + last_path
 
124
        elif this_path != last_path:
 
125
            yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
 
126
        elif (this_ie.text_size != last_ie.text_size
 
127
              or this_ie.text_sha1 != last_ie.text_sha1):
 
128
            yield revno, revision_id, "modified " + this_path
 
129
 
 
130
        last_ie = this_ie
 
131
        last_path = this_path
 
132
        revno += 1
 
133
 
 
134
 
 
135
def _enumerate_history(branch):
 
136
    rh = []
 
137
    revno = 1
 
138
    for rev_id in branch.revision_history():
 
139
        rh.append((revno, rev_id))
 
140
        revno += 1
 
141
    return rh
 
142
 
 
143
 
 
144
def show_log(branch,
 
145
             lf,
 
146
             specific_fileid=None,
 
147
             verbose=False,
 
148
             direction='reverse',
 
149
             start_revision=None,
 
150
             end_revision=None,
 
151
             search=None,
 
152
             limit=None,
 
153
             show_diff=False):
 
154
    """Write out human-readable log of commits to this branch.
 
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
 
 
161
    :param lf: The LogFormatter object showing the output.
 
162
 
 
163
    :param specific_fileid: If not None, list only the commits affecting the
 
164
        specified file, rather than all commits.
 
165
 
 
166
    :param verbose: If True show added/changed/deleted/renamed files.
 
167
 
 
168
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
 
169
        earliest to latest.
 
170
 
 
171
    :param start_revision: If not None, only show revisions >= start_revision
 
172
 
 
173
    :param end_revision: If not None, only show revisions <= end_revision
 
174
 
 
175
    :param search: If not None, only show revisions with matching commit
 
176
        messages
 
177
 
 
178
    :param limit: If set, shows only 'limit' revisions, all revisions are shown
 
179
        if None or 0.
 
180
 
 
181
    :param show_diff: If True, output a diff after each revision.
 
182
    """
 
183
    # Convert old-style parameters to new-style parameters
 
184
    if specific_fileid is not None:
 
185
        file_ids = [specific_fileid]
 
186
    else:
 
187
        file_ids = None
 
188
    if verbose:
 
189
        if file_ids:
 
190
            delta_type = 'partial'
 
191
        else:
 
192
            delta_type = 'full'
 
193
    else:
 
194
        delta_type = None
 
195
    if show_diff:
 
196
        if file_ids:
 
197
            diff_type = 'partial'
 
198
        else:
 
199
            diff_type = 'full'
 
200
    else:
 
201
        diff_type = None
 
202
 
 
203
    # Build the request and execute it
 
204
    rqst = make_log_request_dict(direction=direction, specific_fileids=file_ids,
 
205
        start_revision=start_revision, end_revision=end_revision,
 
206
        limit=limit, message_search=search,
 
207
        delta_type=delta_type, diff_type=diff_type)
 
208
    Logger(branch, rqst).show(lf)
 
209
 
 
210
 
 
211
# Note: This needs to be kept this in sync with the defaults in
 
212
# make_log_request_dict() below
 
213
_DEFAULT_REQUEST_PARAMS = {
 
214
    'direction': 'reverse',
 
215
    'levels': 1,
 
216
    'generate_tags': True,
 
217
    '_match_using_deltas': True,
 
218
    }
 
219
 
 
220
 
 
221
def make_log_request_dict(direction='reverse', specific_fileids=None,
 
222
    start_revision=None, end_revision=None, limit=None,
 
223
    message_search=None, levels=1, generate_tags=True, delta_type=None,
 
224
    diff_type=None, _match_using_deltas=True):
 
225
    """Convenience function for making a logging request dictionary.
 
226
 
 
227
    Using this function may make code slightly safer by ensuring
 
228
    parameters have the correct names. It also provides a reference
 
229
    point for documenting the supported parameters.
 
230
 
 
231
    :param direction: 'reverse' (default) is latest to earliest;
 
232
      'forward' is earliest to latest.
 
233
 
 
234
    :param specific_fileids: If not None, only include revisions
 
235
      affecting the specified files, rather than all revisions.
 
236
 
 
237
    :param start_revision: If not None, only generate
 
238
      revisions >= start_revision
 
239
 
 
240
    :param end_revision: If not None, only generate
 
241
      revisions <= end_revision
 
242
 
 
243
    :param limit: If set, generate only 'limit' revisions, all revisions
 
244
      are shown if None or 0.
 
245
 
 
246
    :param message_search: If not None, only include revisions with
 
247
      matching commit messages
 
248
 
 
249
    :param levels: the number of levels of revisions to
 
250
      generate; 1 for just the mainline; 0 for all levels.
 
251
 
 
252
    :param generate_tags: If True, include tags for matched revisions.
 
253
 
 
254
    :param delta_type: Either 'full', 'partial' or None.
 
255
      'full' means generate the complete delta - adds/deletes/modifies/etc;
 
256
      'partial' means filter the delta using specific_fileids;
 
257
      None means do not generate any delta.
 
258
 
 
259
    :param diff_type: Either 'full', 'partial' or None.
 
260
      'full' means generate the complete diff - adds/deletes/modifies/etc;
 
261
      'partial' means filter the diff using specific_fileids;
 
262
      None means do not generate any diff.
 
263
 
 
264
    :param _match_using_deltas: a private parameter controlling the
 
265
      algorithm used for matching specific_fileids. This parameter
 
266
      may be removed in the future so bzrlib client code should NOT
 
267
      use it.
 
268
    """
 
269
    return {
 
270
        'direction': direction,
 
271
        'specific_fileids': specific_fileids,
 
272
        'start_revision': start_revision,
 
273
        'end_revision': end_revision,
 
274
        'limit': limit,
 
275
        'message_search': message_search,
 
276
        'levels': levels,
 
277
        'generate_tags': generate_tags,
 
278
        'delta_type': delta_type,
 
279
        'diff_type': diff_type,
 
280
        # Add 'private' attributes for features that may be deprecated
 
281
        '_match_using_deltas': _match_using_deltas,
 
282
        '_allow_single_merge_revision': True,
 
283
    }
 
284
 
 
285
 
 
286
def _apply_log_request_defaults(rqst):
 
287
    """Apply default values to a request dictionary."""
 
288
    result = _DEFAULT_REQUEST_PARAMS
 
289
    if rqst:
 
290
        result.update(rqst)
 
291
    return result
 
292
 
 
293
 
 
294
class LogGenerator(object):
 
295
    """A generator of log revisions."""
 
296
 
 
297
    def iter_log_revisions(self):
 
298
        """Iterate over LogRevision objects.
 
299
 
 
300
        :return: An iterator yielding LogRevision objects.
 
301
        """
 
302
        raise NotImplementedError(self.iter_log_revisions)
 
303
 
 
304
 
 
305
class Logger(object):
 
306
    """An object the generates, formats and displays a log."""
 
307
 
 
308
    def __init__(self, branch, rqst):
 
309
        """Create a Logger.
 
310
 
 
311
        :param branch: the branch to log
 
312
        :param rqst: A dictionary specifying the query parameters.
 
313
          See make_log_request_dict() for supported values.
 
314
        """
 
315
        self.branch = branch
 
316
        self.rqst = _apply_log_request_defaults(rqst)
 
317
 
 
318
    def show(self, lf):
 
319
        """Display the log.
 
320
 
 
321
        :param lf: The LogFormatter object to send the output to.
 
322
        """
 
323
        if not isinstance(lf, LogFormatter):
 
324
            warn("not a LogFormatter instance: %r" % lf)
 
325
 
 
326
        self.branch.lock_read()
 
327
        try:
 
328
            if getattr(lf, 'begin_log', None):
 
329
                lf.begin_log()
 
330
            self._show_body(lf)
 
331
            if getattr(lf, 'end_log', None):
 
332
                lf.end_log()
 
333
        finally:
 
334
            self.branch.unlock()
 
335
 
 
336
    def _show_body(self, lf):
 
337
        """Show the main log output.
 
338
 
 
339
        Subclasses may wish to override this.
 
340
        """
 
341
        # Tweak the LogRequest based on what the LogFormatter can handle.
 
342
        # (There's no point generating stuff if the formatter can't display it.)
 
343
        rqst = self.rqst
 
344
        rqst['levels'] = lf.get_levels()
 
345
        if not getattr(lf, 'supports_tags', False):
 
346
            rqst['generate_tags'] = False
 
347
        if not getattr(lf, 'supports_delta', False):
 
348
            rqst['delta_type'] = None
 
349
        if not getattr(lf, 'supports_diff', False):
 
350
            rqst['diff_type'] = None
 
351
        if not getattr(lf, 'supports_merge_revisions', False):
 
352
            rqst['_allow_single_merge_revision'] = getattr(lf,
 
353
                'supports_single_merge_revision', False)
 
354
 
 
355
        # Find and print the interesting revisions
 
356
        generator = self._generator_factory(self.branch, rqst)
 
357
        for lr in generator.iter_log_revisions():
 
358
            lf.log_revision(lr)
 
359
 
 
360
    def _generator_factory(self, branch, rqst):
 
361
        """Make the LogGenerator object to use.
 
362
        
 
363
        Subclasses may wish to override this.
 
364
        """
 
365
        return _DefaultLogGenerator(branch, rqst)
 
366
 
 
367
 
 
368
class _StartNotLinearAncestor(Exception):
 
369
    """Raised when a start revision is not found walking left-hand history."""
 
370
 
 
371
 
 
372
class _DefaultLogGenerator(LogGenerator):
 
373
    """The default generator of log revisions."""
 
374
 
 
375
    def __init__(self, branch, rqst):
 
376
        self.branch = branch
 
377
        self.rqst = rqst
 
378
        if rqst.get('generate_tags') and branch.supports_tags():
 
379
            self.rev_tag_dict = branch.tags.get_reverse_tag_dict()
 
380
        else:
 
381
            self.rev_tag_dict = {}
 
382
 
 
383
    def iter_log_revisions(self):
 
384
        """Iterate over LogRevision objects.
 
385
 
 
386
        :return: An iterator yielding LogRevision objects.
 
387
        """
 
388
        rqst = self.rqst
 
389
        log_count = 0
 
390
        revision_iterator = self._create_log_revision_iterator()
 
391
        for revs in revision_iterator:
 
392
            for (rev_id, revno, merge_depth), rev, delta in revs:
 
393
                # 0 levels means show everything; merge_depth counts from 0
 
394
                levels = rqst.get('levels')
 
395
                if levels != 0 and merge_depth >= levels:
 
396
                    continue
 
397
                diff = self._format_diff(rev, rev_id)
 
398
                yield LogRevision(rev, revno, merge_depth, delta,
 
399
                    self.rev_tag_dict.get(rev_id), diff)
 
400
                limit = rqst.get('limit')
 
401
                if limit:
 
402
                    log_count += 1
 
403
                    if log_count >= limit:
 
404
                        return
 
405
 
 
406
    def _format_diff(self, rev, rev_id):
 
407
        diff_type = self.rqst.get('diff_type')
 
408
        if diff_type is None:
 
409
            return None
 
410
        repo = self.branch.repository
 
411
        if len(rev.parent_ids) == 0:
 
412
            ancestor_id = _mod_revision.NULL_REVISION
 
413
        else:
 
414
            ancestor_id = rev.parent_ids[0]
 
415
        tree_1 = repo.revision_tree(ancestor_id)
 
416
        tree_2 = repo.revision_tree(rev_id)
 
417
        file_ids = self.rqst.get('specific_fileids')
 
418
        if diff_type == 'partial' and file_ids is not None:
 
419
            specific_files = [tree_2.id2path(id) for id in file_ids]
 
420
        else:
 
421
            specific_files = None
 
422
        s = StringIO()
 
423
        diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
 
424
            new_label='')
 
425
        return s.getvalue()
 
426
 
 
427
    def _create_log_revision_iterator(self):
 
428
        """Create a revision iterator for log.
 
429
 
 
430
        :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
431
            delta).
 
432
        """
 
433
        self.start_rev_id, self.end_rev_id = _get_revision_limits(
 
434
            self.branch, self.rqst.get('start_revision'),
 
435
            self.rqst.get('end_revision'))
 
436
        if self.rqst.get('_match_using_deltas'):
 
437
            return self._log_revision_iterator_using_delta_matching()
 
438
        else:
 
439
            # We're using the per-file-graph algorithm. This scales really
 
440
            # well but only makes sense if there is a single file and it's
 
441
            # not a directory
 
442
            file_count = len(self.rqst.get('specific_fileids'))
 
443
            if file_count != 1:
 
444
                raise BzrError("illegal LogRequest: must match-using-deltas "
 
445
                    "when logging %d files" % file_count)
 
446
            return self._log_revision_iterator_using_per_file_graph()
 
447
 
 
448
    def _log_revision_iterator_using_delta_matching(self):
 
449
        # Get the base revisions, filtering by the revision range
 
450
        rqst = self.rqst
 
451
        generate_merge_revisions = rqst.get('levels') != 1
 
452
        delayed_graph_generation = not rqst.get('specific_fileids') and (
 
453
                rqst.get('limit') or self.start_rev_id or self.end_rev_id)
 
454
        view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
 
455
            self.end_rev_id, rqst.get('direction'), generate_merge_revisions,
 
456
            rqst.get('_allow_single_merge_revision'),
 
457
            delayed_graph_generation=delayed_graph_generation)
 
458
 
 
459
        # Apply the other filters
 
460
        return make_log_rev_iterator(self.branch, view_revisions,
 
461
            rqst.get('delta_type'), rqst.get('message_search'),
 
462
            file_ids=rqst.get('specific_fileids'),
 
463
            direction=rqst.get('direction'))
 
464
 
 
465
    def _log_revision_iterator_using_per_file_graph(self):
 
466
        # Get the base revisions, filtering by the revision range.
 
467
        # Note that we always generate the merge revisions because
 
468
        # filter_revisions_touching_file_id() requires them ...
 
469
        rqst = self.rqst
 
470
        view_revisions = _calc_view_revisions(self.branch, self.start_rev_id,
 
471
            self.end_rev_id, rqst.get('direction'), True,
 
472
            rqst.get('_allow_single_merge_revision'))
 
473
        if not isinstance(view_revisions, list):
 
474
            view_revisions = list(view_revisions)
 
475
        view_revisions = _filter_revisions_touching_file_id(self.branch,
 
476
            rqst.get('specific_fileids')[0], view_revisions,
 
477
            include_merges=rqst.get('levels') != 1)
 
478
        return make_log_rev_iterator(self.branch, view_revisions,
 
479
            rqst.get('delta_type'), rqst.get('message_search'))
 
480
 
 
481
 
 
482
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
 
483
    generate_merge_revisions, allow_single_merge_revision,
 
484
    delayed_graph_generation=False):
 
485
    """Calculate the revisions to view.
 
486
 
 
487
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
 
488
             a list of the same tuples.
 
489
    """
 
490
    br_revno, br_rev_id = branch.last_revision_info()
 
491
    if br_revno == 0:
 
492
        return []
 
493
 
 
494
    # If a single revision is requested, check we can handle it
 
495
    generate_single_revision = (end_rev_id and start_rev_id == end_rev_id and
 
496
        (not generate_merge_revisions or not _has_merges(branch, end_rev_id)))
 
497
    if generate_single_revision:
 
498
        return _generate_one_revision(branch, end_rev_id, br_rev_id, br_revno,
 
499
            allow_single_merge_revision)
 
500
 
 
501
    # If we only want to see linear revisions, we can iterate ...
 
502
    if not generate_merge_revisions:
 
503
        return _generate_flat_revisions(branch, start_rev_id, end_rev_id,
 
504
            direction)
 
505
    else:
 
506
        return _generate_all_revisions(branch, start_rev_id, end_rev_id,
 
507
            direction, delayed_graph_generation)
 
508
 
 
509
 
 
510
def _generate_one_revision(branch, rev_id, br_rev_id, br_revno,
 
511
    allow_single_merge_revision):
 
512
    if rev_id == br_rev_id:
 
513
        # It's the tip
 
514
        return [(br_rev_id, br_revno, 0)]
 
515
    else:
 
516
        revno = branch.revision_id_to_dotted_revno(rev_id)
 
517
        if len(revno) > 1 and not allow_single_merge_revision:
 
518
            # It's a merge revision and the log formatter is
 
519
            # completely brain dead. This "feature" of allowing
 
520
            # log formatters incapable of displaying dotted revnos
 
521
            # ought to be deprecated IMNSHO. IGC 20091022
 
522
            raise errors.BzrCommandError('Selected log formatter only'
 
523
                ' supports mainline revisions.')
 
524
        revno_str = '.'.join(str(n) for n in revno)
 
525
        return [(rev_id, revno_str, 0)]
 
526
 
 
527
 
 
528
def _generate_flat_revisions(branch, start_rev_id, end_rev_id, direction):
 
529
    result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
 
530
    # If a start limit was given and it's not obviously an
 
531
    # ancestor of the end limit, check it before outputting anything
 
532
    if direction == 'forward' or (start_rev_id
 
533
        and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
 
534
        try:
 
535
            result = list(result)
 
536
        except _StartNotLinearAncestor:
 
537
            raise errors.BzrCommandError('Start revision not found in'
 
538
                ' left-hand history of end revision.')
 
539
    if direction == 'forward':
 
540
        result = reversed(result)
 
541
    return result
 
542
 
 
543
 
 
544
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
 
545
    delayed_graph_generation):
 
546
    # On large trees, generating the merge graph can take 30-60 seconds
 
547
    # so we delay doing it until a merge is detected, incrementally
 
548
    # returning initial (non-merge) revisions while we can.
 
549
    initial_revisions = []
 
550
    if delayed_graph_generation:
 
551
        try:
 
552
            for rev_id, revno, depth in \
 
553
                _linear_view_revisions(branch, start_rev_id, end_rev_id):
 
554
                if _has_merges(branch, rev_id):
 
555
                    end_rev_id = rev_id
 
556
                    break
 
557
                else:
 
558
                    initial_revisions.append((rev_id, revno, depth))
 
559
            else:
 
560
                # No merged revisions found
 
561
                if direction == 'reverse':
 
562
                    return initial_revisions
 
563
                elif direction == 'forward':
 
564
                    return reversed(initial_revisions)
 
565
                else:
 
566
                    raise ValueError('invalid direction %r' % direction)
 
567
        except _StartNotLinearAncestor:
 
568
            # A merge was never detected so the lower revision limit can't
 
569
            # be nested down somewhere
 
570
            raise errors.BzrCommandError('Start revision not found in'
 
571
                ' history of end revision.')
 
572
 
 
573
    # A log including nested merges is required. If the direction is reverse,
 
574
    # we rebase the initial merge depths so that the development line is
 
575
    # shown naturally, i.e. just like it is for linear logging. We can easily
 
576
    # make forward the exact opposite display, but showing the merge revisions
 
577
    # indented at the end seems slightly nicer in that case.
 
578
    view_revisions = chain(iter(initial_revisions),
 
579
        _graph_view_revisions(branch, start_rev_id, end_rev_id,
 
580
        rebase_initial_depths=direction == 'reverse'))
 
581
    if direction == 'reverse':
 
582
        return view_revisions
 
583
    elif direction == 'forward':
 
584
        # Forward means oldest first, adjusting for depth.
 
585
        view_revisions = reverse_by_depth(list(view_revisions))
 
586
        return _rebase_merge_depth(view_revisions)
 
587
    else:
 
588
        raise ValueError('invalid direction %r' % direction)
 
589
 
 
590
 
 
591
def _has_merges(branch, rev_id):
 
592
    """Does a revision have multiple parents or not?"""
 
593
    parents = branch.repository.get_parent_map([rev_id]).get(rev_id, [])
 
594
    return len(parents) > 1
 
595
 
 
596
 
 
597
def _is_obvious_ancestor(branch, start_rev_id, end_rev_id):
 
598
    """Is start_rev_id an obvious ancestor of end_rev_id?"""
 
599
    if start_rev_id and end_rev_id:
 
600
        start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
 
601
        end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
 
602
        if len(start_dotted) == 1 and len(end_dotted) == 1:
 
603
            # both on mainline
 
604
            return start_dotted[0] <= end_dotted[0]
 
605
        elif (len(start_dotted) == 3 and len(end_dotted) == 3 and
 
606
            start_dotted[0:1] == end_dotted[0:1]):
 
607
            # both on same development line
 
608
            return start_dotted[2] <= end_dotted[2]
 
609
        else:
 
610
            # not obvious
 
611
            return False
 
612
    return True
 
613
 
 
614
 
 
615
def _linear_view_revisions(branch, start_rev_id, end_rev_id):
 
616
    """Calculate a sequence of revisions to view, newest to oldest.
 
617
 
 
618
    :param start_rev_id: the lower revision-id
 
619
    :param end_rev_id: the upper revision-id
 
620
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
 
621
    :raises _StartNotLinearAncestor: if a start_rev_id is specified but
 
622
      is not found walking the left-hand history
 
623
    """
 
624
    br_revno, br_rev_id = branch.last_revision_info()
 
625
    repo = branch.repository
 
626
    if start_rev_id is None and end_rev_id is None:
 
627
        cur_revno = br_revno
 
628
        for revision_id in repo.iter_reverse_revision_history(br_rev_id):
 
629
            yield revision_id, str(cur_revno), 0
 
630
            cur_revno -= 1
 
631
    else:
 
632
        if end_rev_id is None:
 
633
            end_rev_id = br_rev_id
 
634
        found_start = start_rev_id is None
 
635
        for revision_id in repo.iter_reverse_revision_history(end_rev_id):
 
636
            revno = branch.revision_id_to_dotted_revno(revision_id)
 
637
            revno_str = '.'.join(str(n) for n in revno)
 
638
            if not found_start and revision_id == start_rev_id:
 
639
                yield revision_id, revno_str, 0
 
640
                found_start = True
 
641
                break
 
642
            else:
 
643
                yield revision_id, revno_str, 0
 
644
        else:
 
645
            if not found_start:
 
646
                raise _StartNotLinearAncestor()
 
647
 
 
648
 
 
649
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
 
650
    rebase_initial_depths=True):
 
651
    """Calculate revisions to view including merges, newest to oldest.
 
652
 
 
653
    :param branch: the branch
 
654
    :param start_rev_id: the lower revision-id
 
655
    :param end_rev_id: the upper revision-id
 
656
    :param rebase_initial_depth: should depths be rebased until a mainline
 
657
      revision is found?
 
658
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
 
659
    """
 
660
    view_revisions = branch.iter_merge_sorted_revisions(
 
661
        start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
 
662
        stop_rule="with-merges")
 
663
    if not rebase_initial_depths:
 
664
        for (rev_id, merge_depth, revno, end_of_merge
 
665
             ) in view_revisions:
 
666
            yield rev_id, '.'.join(map(str, revno)), merge_depth
 
667
    else:
 
668
        # We're following a development line starting at a merged revision.
 
669
        # We need to adjust depths down by the initial depth until we find
 
670
        # a depth less than it. Then we use that depth as the adjustment.
 
671
        # If and when we reach the mainline, depth adjustment ends.
 
672
        depth_adjustment = None
 
673
        for (rev_id, merge_depth, revno, end_of_merge
 
674
             ) in view_revisions:
 
675
            if depth_adjustment is None:
 
676
                depth_adjustment = merge_depth
 
677
            if depth_adjustment:
 
678
                if merge_depth < depth_adjustment:
 
679
                    depth_adjustment = merge_depth
 
680
                merge_depth -= depth_adjustment
 
681
            yield rev_id, '.'.join(map(str, revno)), merge_depth
 
682
 
 
683
 
 
684
def calculate_view_revisions(branch, start_revision, end_revision, direction,
 
685
        specific_fileid, generate_merge_revisions, allow_single_merge_revision):
 
686
    """Calculate the revisions to view.
 
687
 
 
688
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
 
689
             a list of the same tuples.
 
690
    """
 
691
    # This method is no longer called by the main code path.
 
692
    # It is retained for API compatibility and may be deprecated
 
693
    # soon. IGC 20090116
 
694
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
 
695
        end_revision)
 
696
    view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
 
697
        direction, generate_merge_revisions or specific_fileid,
 
698
        allow_single_merge_revision))
 
699
    if specific_fileid:
 
700
        view_revisions = _filter_revisions_touching_file_id(branch,
 
701
            specific_fileid, view_revisions,
 
702
            include_merges=generate_merge_revisions)
 
703
    return _rebase_merge_depth(view_revisions)
 
704
 
 
705
 
 
706
def _rebase_merge_depth(view_revisions):
 
707
    """Adjust depths upwards so the top level is 0."""
 
708
    # If either the first or last revision have a merge_depth of 0, we're done
 
709
    if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
 
710
        min_depth = min([d for r,n,d in view_revisions])
 
711
        if min_depth != 0:
 
712
            view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
 
713
    return view_revisions
 
714
 
 
715
 
 
716
def make_log_rev_iterator(branch, view_revisions, generate_delta, search,
 
717
        file_ids=None, direction='reverse'):
 
718
    """Create a revision iterator for log.
 
719
 
 
720
    :param branch: The branch being logged.
 
721
    :param view_revisions: The revisions being viewed.
 
722
    :param generate_delta: Whether to generate a delta for each revision.
 
723
      Permitted values are None, 'full' and 'partial'.
 
724
    :param search: A user text search string.
 
725
    :param file_ids: If non empty, only revisions matching one or more of
 
726
      the file-ids are to be kept.
 
727
    :param direction: the direction in which view_revisions is sorted
 
728
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
729
        delta).
 
730
    """
 
731
    # Convert view_revisions into (view, None, None) groups to fit with
 
732
    # the standard interface here.
 
733
    if type(view_revisions) == list:
 
734
        # A single batch conversion is faster than many incremental ones.
 
735
        # As we have all the data, do a batch conversion.
 
736
        nones = [None] * len(view_revisions)
 
737
        log_rev_iterator = iter([zip(view_revisions, nones, nones)])
 
738
    else:
 
739
        def _convert():
 
740
            for view in view_revisions:
 
741
                yield (view, None, None)
 
742
        log_rev_iterator = iter([_convert()])
 
743
    for adapter in log_adapters:
 
744
        # It would be nicer if log adapters were first class objects
 
745
        # with custom parameters. This will do for now. IGC 20090127
 
746
        if adapter == _make_delta_filter:
 
747
            log_rev_iterator = adapter(branch, generate_delta,
 
748
                search, log_rev_iterator, file_ids, direction)
 
749
        else:
 
750
            log_rev_iterator = adapter(branch, generate_delta,
 
751
                search, log_rev_iterator)
 
752
    return log_rev_iterator
 
753
 
 
754
 
 
755
def _make_search_filter(branch, generate_delta, search, log_rev_iterator):
 
756
    """Create a filtered iterator of log_rev_iterator matching on a regex.
 
757
 
 
758
    :param branch: The branch being logged.
 
759
    :param generate_delta: Whether to generate a delta for each revision.
 
760
    :param search: A user text search string.
 
761
    :param log_rev_iterator: An input iterator containing all revisions that
 
762
        could be displayed, in lists.
 
763
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
764
        delta).
 
765
    """
 
766
    if search is None:
 
767
        return log_rev_iterator
 
768
    searchRE = re_compile_checked(search, re.IGNORECASE,
 
769
            'log message filter')
 
770
    return _filter_message_re(searchRE, log_rev_iterator)
 
771
 
 
772
 
 
773
def _filter_message_re(searchRE, log_rev_iterator):
 
774
    for revs in log_rev_iterator:
 
775
        new_revs = []
 
776
        for (rev_id, revno, merge_depth), rev, delta in revs:
 
777
            if searchRE.search(rev.message):
 
778
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
 
779
        yield new_revs
 
780
 
 
781
 
 
782
def _make_delta_filter(branch, generate_delta, search, log_rev_iterator,
 
783
    fileids=None, direction='reverse'):
 
784
    """Add revision deltas to a log iterator if needed.
 
785
 
 
786
    :param branch: The branch being logged.
 
787
    :param generate_delta: Whether to generate a delta for each revision.
 
788
      Permitted values are None, 'full' and 'partial'.
 
789
    :param search: A user text search string.
 
790
    :param log_rev_iterator: An input iterator containing all revisions that
 
791
        could be displayed, in lists.
 
792
    :param fileids: If non empty, only revisions matching one or more of
 
793
      the file-ids are to be kept.
 
794
    :param direction: the direction in which view_revisions is sorted
 
795
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
796
        delta).
 
797
    """
 
798
    if not generate_delta and not fileids:
 
799
        return log_rev_iterator
 
800
    return _generate_deltas(branch.repository, log_rev_iterator,
 
801
        generate_delta, fileids, direction)
 
802
 
 
803
 
 
804
def _generate_deltas(repository, log_rev_iterator, delta_type, fileids,
 
805
    direction):
 
806
    """Create deltas for each batch of revisions in log_rev_iterator.
 
807
 
 
808
    If we're only generating deltas for the sake of filtering against
 
809
    file-ids, we stop generating deltas once all file-ids reach the
 
810
    appropriate life-cycle point. If we're receiving data newest to
 
811
    oldest, then that life-cycle point is 'add', otherwise it's 'remove'.
 
812
    """
 
813
    check_fileids = fileids is not None and len(fileids) > 0
 
814
    if check_fileids:
 
815
        fileid_set = set(fileids)
 
816
        if direction == 'reverse':
 
817
            stop_on = 'add'
 
818
        else:
 
819
            stop_on = 'remove'
 
820
    else:
 
821
        fileid_set = None
 
822
    for revs in log_rev_iterator:
 
823
        # If we were matching against fileids and we've run out,
 
824
        # there's nothing left to do
 
825
        if check_fileids and not fileid_set:
 
826
            return
 
827
        revisions = [rev[1] for rev in revs]
 
828
        new_revs = []
 
829
        if delta_type == 'full' and not check_fileids:
 
830
            deltas = repository.get_deltas_for_revisions(revisions)
 
831
            for rev, delta in izip(revs, deltas):
 
832
                new_revs.append((rev[0], rev[1], delta))
 
833
        else:
 
834
            deltas = repository.get_deltas_for_revisions(revisions, fileid_set)
 
835
            for rev, delta in izip(revs, deltas):
 
836
                if check_fileids:
 
837
                    if delta is None or not delta.has_changed():
 
838
                        continue
 
839
                    else:
 
840
                        _update_fileids(delta, fileid_set, stop_on)
 
841
                        if delta_type is None:
 
842
                            delta = None
 
843
                        elif delta_type == 'full':
 
844
                            # If the file matches all the time, rebuilding
 
845
                            # a full delta like this in addition to a partial
 
846
                            # one could be slow. However, it's likely that
 
847
                            # most revisions won't get this far, making it
 
848
                            # faster to filter on the partial deltas and
 
849
                            # build the occasional full delta than always
 
850
                            # building full deltas and filtering those.
 
851
                            rev_id = rev[0][0]
 
852
                            delta = repository.get_revision_delta(rev_id)
 
853
                new_revs.append((rev[0], rev[1], delta))
 
854
        yield new_revs
 
855
 
 
856
 
 
857
def _update_fileids(delta, fileids, stop_on):
 
858
    """Update the set of file-ids to search based on file lifecycle events.
 
859
    
 
860
    :param fileids: a set of fileids to update
 
861
    :param stop_on: either 'add' or 'remove' - take file-ids out of the
 
862
      fileids set once their add or remove entry is detected respectively
 
863
    """
 
864
    if stop_on == 'add':
 
865
        for item in delta.added:
 
866
            if item[1] in fileids:
 
867
                fileids.remove(item[1])
 
868
    elif stop_on == 'delete':
 
869
        for item in delta.removed:
 
870
            if item[1] in fileids:
 
871
                fileids.remove(item[1])
 
872
 
 
873
 
 
874
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
 
875
    """Extract revision objects from the repository
 
876
 
 
877
    :param branch: The branch being logged.
 
878
    :param generate_delta: Whether to generate a delta for each revision.
 
879
    :param search: A user text search string.
 
880
    :param log_rev_iterator: An input iterator containing all revisions that
 
881
        could be displayed, in lists.
 
882
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
883
        delta).
 
884
    """
 
885
    repository = branch.repository
 
886
    for revs in log_rev_iterator:
 
887
        # r = revision_id, n = revno, d = merge depth
 
888
        revision_ids = [view[0] for view, _, _ in revs]
 
889
        revisions = repository.get_revisions(revision_ids)
 
890
        revs = [(rev[0], revision, rev[2]) for rev, revision in
 
891
            izip(revs, revisions)]
 
892
        yield revs
 
893
 
 
894
 
 
895
def _make_batch_filter(branch, generate_delta, search, log_rev_iterator):
 
896
    """Group up a single large batch into smaller ones.
 
897
 
 
898
    :param branch: The branch being logged.
 
899
    :param generate_delta: Whether to generate a delta for each revision.
 
900
    :param search: A user text search string.
 
901
    :param log_rev_iterator: An input iterator containing all revisions that
 
902
        could be displayed, in lists.
 
903
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
 
904
        delta).
 
905
    """
 
906
    repository = branch.repository
 
907
    num = 9
 
908
    for batch in log_rev_iterator:
 
909
        batch = iter(batch)
 
910
        while True:
 
911
            step = [detail for _, detail in zip(range(num), batch)]
 
912
            if len(step) == 0:
 
913
                break
 
914
            yield step
 
915
            num = min(int(num * 1.5), 200)
 
916
 
 
917
 
 
918
def _get_revision_limits(branch, start_revision, end_revision):
 
919
    """Get and check revision limits.
 
920
 
 
921
    :param  branch: The branch containing the revisions.
 
922
 
 
923
    :param  start_revision: The first revision to be logged.
 
924
            For backwards compatibility this may be a mainline integer revno,
 
925
            but for merge revision support a RevisionInfo is expected.
 
926
 
 
927
    :param  end_revision: The last revision to be logged.
 
928
            For backwards compatibility this may be a mainline integer revno,
 
929
            but for merge revision support a RevisionInfo is expected.
 
930
 
 
931
    :return: (start_rev_id, end_rev_id) tuple.
 
932
    """
 
933
    branch_revno, branch_rev_id = branch.last_revision_info()
 
934
    start_rev_id = None
 
935
    if start_revision is None:
 
936
        start_revno = 1
 
937
    else:
 
938
        if isinstance(start_revision, revisionspec.RevisionInfo):
 
939
            start_rev_id = start_revision.rev_id
 
940
            start_revno = start_revision.revno or 1
 
941
        else:
 
942
            branch.check_real_revno(start_revision)
 
943
            start_revno = start_revision
 
944
            start_rev_id = branch.get_rev_id(start_revno)
 
945
 
 
946
    end_rev_id = None
 
947
    if end_revision is None:
 
948
        end_revno = branch_revno
 
949
    else:
 
950
        if isinstance(end_revision, revisionspec.RevisionInfo):
 
951
            end_rev_id = end_revision.rev_id
 
952
            end_revno = end_revision.revno or branch_revno
 
953
        else:
 
954
            branch.check_real_revno(end_revision)
 
955
            end_revno = end_revision
 
956
            end_rev_id = branch.get_rev_id(end_revno)
 
957
 
 
958
    if branch_revno != 0:
 
959
        if (start_rev_id == _mod_revision.NULL_REVISION
 
960
            or end_rev_id == _mod_revision.NULL_REVISION):
 
961
            raise errors.BzrCommandError('Logging revision 0 is invalid.')
 
962
        if start_revno > end_revno:
 
963
            raise errors.BzrCommandError("Start revision must be older than "
 
964
                                         "the end revision.")
 
965
    return (start_rev_id, end_rev_id)
 
966
 
 
967
 
 
968
def _get_mainline_revs(branch, start_revision, end_revision):
 
969
    """Get the mainline revisions from the branch.
 
970
 
 
971
    Generates the list of mainline revisions for the branch.
 
972
 
 
973
    :param  branch: The branch containing the revisions.
 
974
 
 
975
    :param  start_revision: The first revision to be logged.
 
976
            For backwards compatibility this may be a mainline integer revno,
 
977
            but for merge revision support a RevisionInfo is expected.
 
978
 
 
979
    :param  end_revision: The last revision to be logged.
 
980
            For backwards compatibility this may be a mainline integer revno,
 
981
            but for merge revision support a RevisionInfo is expected.
 
982
 
 
983
    :return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
 
984
    """
 
985
    branch_revno, branch_last_revision = branch.last_revision_info()
 
986
    if branch_revno == 0:
 
987
        return None, None, None, None
 
988
 
 
989
    # For mainline generation, map start_revision and end_revision to
 
990
    # mainline revnos. If the revision is not on the mainline choose the
 
991
    # appropriate extreme of the mainline instead - the extra will be
 
992
    # filtered later.
 
993
    # Also map the revisions to rev_ids, to be used in the later filtering
 
994
    # stage.
 
995
    start_rev_id = None
 
996
    if start_revision is None:
 
997
        start_revno = 1
 
998
    else:
 
999
        if isinstance(start_revision, revisionspec.RevisionInfo):
 
1000
            start_rev_id = start_revision.rev_id
 
1001
            start_revno = start_revision.revno or 1
 
1002
        else:
 
1003
            branch.check_real_revno(start_revision)
 
1004
            start_revno = start_revision
 
1005
 
 
1006
    end_rev_id = None
 
1007
    if end_revision is None:
 
1008
        end_revno = branch_revno
 
1009
    else:
 
1010
        if isinstance(end_revision, revisionspec.RevisionInfo):
 
1011
            end_rev_id = end_revision.rev_id
 
1012
            end_revno = end_revision.revno or branch_revno
 
1013
        else:
 
1014
            branch.check_real_revno(end_revision)
 
1015
            end_revno = end_revision
 
1016
 
 
1017
    if ((start_rev_id == _mod_revision.NULL_REVISION)
 
1018
        or (end_rev_id == _mod_revision.NULL_REVISION)):
 
1019
        raise errors.BzrCommandError('Logging revision 0 is invalid.')
 
1020
    if start_revno > end_revno:
 
1021
        raise errors.BzrCommandError("Start revision must be older than "
 
1022
                                     "the end revision.")
 
1023
 
 
1024
    if end_revno < start_revno:
 
1025
        return None, None, None, None
 
1026
    cur_revno = branch_revno
 
1027
    rev_nos = {}
 
1028
    mainline_revs = []
 
1029
    for revision_id in branch.repository.iter_reverse_revision_history(
 
1030
                        branch_last_revision):
 
1031
        if cur_revno < start_revno:
 
1032
            # We have gone far enough, but we always add 1 more revision
 
1033
            rev_nos[revision_id] = cur_revno
 
1034
            mainline_revs.append(revision_id)
 
1035
            break
 
1036
        if cur_revno <= end_revno:
 
1037
            rev_nos[revision_id] = cur_revno
 
1038
            mainline_revs.append(revision_id)
 
1039
        cur_revno -= 1
 
1040
    else:
 
1041
        # We walked off the edge of all revisions, so we add a 'None' marker
 
1042
        mainline_revs.append(None)
 
1043
 
 
1044
    mainline_revs.reverse()
 
1045
 
 
1046
    # override the mainline to look like the revision history.
 
1047
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
 
1048
 
 
1049
 
 
1050
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
 
1051
    """Filter view_revisions based on revision ranges.
 
1052
 
 
1053
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
 
1054
            tuples to be filtered.
 
1055
 
 
1056
    :param start_rev_id: If not NONE specifies the first revision to be logged.
 
1057
            If NONE then all revisions up to the end_rev_id are logged.
 
1058
 
 
1059
    :param end_rev_id: If not NONE specifies the last revision to be logged.
 
1060
            If NONE then all revisions up to the end of the log are logged.
 
1061
 
 
1062
    :return: The filtered view_revisions.
 
1063
    """
 
1064
    # This method is no longer called by the main code path.
 
1065
    # It may be removed soon. IGC 20090127
 
1066
    if start_rev_id or end_rev_id:
 
1067
        revision_ids = [r for r, n, d in view_revisions]
 
1068
        if start_rev_id:
 
1069
            start_index = revision_ids.index(start_rev_id)
 
1070
        else:
 
1071
            start_index = 0
 
1072
        if start_rev_id == end_rev_id:
 
1073
            end_index = start_index
 
1074
        else:
 
1075
            if end_rev_id:
 
1076
                end_index = revision_ids.index(end_rev_id)
 
1077
            else:
 
1078
                end_index = len(view_revisions) - 1
 
1079
        # To include the revisions merged into the last revision,
 
1080
        # extend end_rev_id down to, but not including, the next rev
 
1081
        # with the same or lesser merge_depth
 
1082
        end_merge_depth = view_revisions[end_index][2]
 
1083
        try:
 
1084
            for index in xrange(end_index+1, len(view_revisions)+1):
 
1085
                if view_revisions[index][2] <= end_merge_depth:
 
1086
                    end_index = index - 1
 
1087
                    break
 
1088
        except IndexError:
 
1089
            # if the search falls off the end then log to the end as well
 
1090
            end_index = len(view_revisions) - 1
 
1091
        view_revisions = view_revisions[start_index:end_index+1]
 
1092
    return view_revisions
 
1093
 
 
1094
 
 
1095
def _filter_revisions_touching_file_id(branch, file_id, view_revisions,
 
1096
    include_merges=True):
 
1097
    r"""Return the list of revision ids which touch a given file id.
 
1098
 
 
1099
    The function filters view_revisions and returns a subset.
 
1100
    This includes the revisions which directly change the file id,
 
1101
    and the revisions which merge these changes. So if the
 
1102
    revision graph is::
 
1103
        A-.
 
1104
        |\ \
 
1105
        B C E
 
1106
        |/ /
 
1107
        D |
 
1108
        |\|
 
1109
        | F
 
1110
        |/
 
1111
        G
 
1112
 
 
1113
    And 'C' changes a file, then both C and D will be returned. F will not be
 
1114
    returned even though it brings the changes to C into the branch starting
 
1115
    with E. (Note that if we were using F as the tip instead of G, then we
 
1116
    would see C, D, F.)
 
1117
 
 
1118
    This will also be restricted based on a subset of the mainline.
 
1119
 
 
1120
    :param branch: The branch where we can get text revision information.
 
1121
 
 
1122
    :param file_id: Filter out revisions that do not touch file_id.
 
1123
 
 
1124
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
 
1125
        tuples. This is the list of revisions which will be filtered. It is
 
1126
        assumed that view_revisions is in merge_sort order (i.e. newest
 
1127
        revision first ).
 
1128
 
 
1129
    :param include_merges: include merge revisions in the result or not
 
1130
 
 
1131
    :return: A list of (revision_id, dotted_revno, merge_depth) tuples.
 
1132
    """
 
1133
    # Lookup all possible text keys to determine which ones actually modified
 
1134
    # the file.
 
1135
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
 
1136
    next_keys = None
 
1137
    # Looking up keys in batches of 1000 can cut the time in half, as well as
 
1138
    # memory consumption. GraphIndex *does* like to look for a few keys in
 
1139
    # parallel, it just doesn't like looking for *lots* of keys in parallel.
 
1140
    # TODO: This code needs to be re-evaluated periodically as we tune the
 
1141
    #       indexing layer. We might consider passing in hints as to the known
 
1142
    #       access pattern (sparse/clustered, high success rate/low success
 
1143
    #       rate). This particular access is clustered with a low success rate.
 
1144
    get_parent_map = branch.repository.texts.get_parent_map
 
1145
    modified_text_revisions = set()
 
1146
    chunk_size = 1000
 
1147
    for start in xrange(0, len(text_keys), chunk_size):
 
1148
        next_keys = text_keys[start:start + chunk_size]
 
1149
        # Only keep the revision_id portion of the key
 
1150
        modified_text_revisions.update(
 
1151
            [k[1] for k in get_parent_map(next_keys)])
 
1152
    del text_keys, next_keys
 
1153
 
 
1154
    result = []
 
1155
    # Track what revisions will merge the current revision, replace entries
 
1156
    # with 'None' when they have been added to result
 
1157
    current_merge_stack = [None]
 
1158
    for info in view_revisions:
 
1159
        rev_id, revno, depth = info
 
1160
        if depth == len(current_merge_stack):
 
1161
            current_merge_stack.append(info)
 
1162
        else:
 
1163
            del current_merge_stack[depth + 1:]
 
1164
            current_merge_stack[-1] = info
 
1165
 
 
1166
        if rev_id in modified_text_revisions:
 
1167
            # This needs to be logged, along with the extra revisions
 
1168
            for idx in xrange(len(current_merge_stack)):
 
1169
                node = current_merge_stack[idx]
 
1170
                if node is not None:
 
1171
                    if include_merges or node[2] == 0:
 
1172
                        result.append(node)
 
1173
                        current_merge_stack[idx] = None
 
1174
    return result
 
1175
 
 
1176
 
 
1177
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
 
1178
                       include_merges=True):
 
1179
    """Produce an iterator of revisions to show
 
1180
    :return: an iterator of (revision_id, revno, merge_depth)
 
1181
    (if there is no revno for a revision, None is supplied)
 
1182
    """
 
1183
    # This method is no longer called by the main code path.
 
1184
    # It is retained for API compatibility and may be deprecated
 
1185
    # soon. IGC 20090127
 
1186
    if not include_merges:
 
1187
        revision_ids = mainline_revs[1:]
 
1188
        if direction == 'reverse':
 
1189
            revision_ids.reverse()
 
1190
        for revision_id in revision_ids:
 
1191
            yield revision_id, str(rev_nos[revision_id]), 0
 
1192
        return
 
1193
    graph = branch.repository.get_graph()
 
1194
    # This asks for all mainline revisions, which means we only have to spider
 
1195
    # sideways, rather than depth history. That said, its still size-of-history
 
1196
    # and should be addressed.
 
1197
    # mainline_revisions always includes an extra revision at the beginning, so
 
1198
    # don't request it.
 
1199
    parent_map = dict(((key, value) for key, value in
 
1200
        graph.iter_ancestry(mainline_revs[1:]) if value is not None))
 
1201
    # filter out ghosts; merge_sort errors on ghosts.
 
1202
    rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
 
1203
    merge_sorted_revisions = tsort.merge_sort(
 
1204
        rev_graph,
 
1205
        mainline_revs[-1],
 
1206
        mainline_revs,
 
1207
        generate_revno=True)
 
1208
 
 
1209
    if direction == 'forward':
 
1210
        # forward means oldest first.
 
1211
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
 
1212
    elif direction != 'reverse':
 
1213
        raise ValueError('invalid direction %r' % direction)
 
1214
 
 
1215
    for (sequence, rev_id, merge_depth, revno, end_of_merge
 
1216
         ) in merge_sorted_revisions:
 
1217
        yield rev_id, '.'.join(map(str, revno)), merge_depth
 
1218
 
 
1219
 
 
1220
def reverse_by_depth(merge_sorted_revisions, _depth=0):
 
1221
    """Reverse revisions by depth.
 
1222
 
 
1223
    Revisions with a different depth are sorted as a group with the previous
 
1224
    revision of that depth.  There may be no topological justification for this,
 
1225
    but it looks much nicer.
 
1226
    """
 
1227
    # Add a fake revision at start so that we can always attach sub revisions
 
1228
    merge_sorted_revisions = [(None, None, _depth)] + merge_sorted_revisions
 
1229
    zd_revisions = []
 
1230
    for val in merge_sorted_revisions:
 
1231
        if val[2] == _depth:
 
1232
            # Each revision at the current depth becomes a chunk grouping all
 
1233
            # higher depth revisions.
 
1234
            zd_revisions.append([val])
 
1235
        else:
 
1236
            zd_revisions[-1].append(val)
 
1237
    for revisions in zd_revisions:
 
1238
        if len(revisions) > 1:
 
1239
            # We have higher depth revisions, let reverse them locally
 
1240
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
 
1241
    zd_revisions.reverse()
 
1242
    result = []
 
1243
    for chunk in zd_revisions:
 
1244
        result.extend(chunk)
 
1245
    if _depth == 0:
 
1246
        # Top level call, get rid of the fake revisions that have been added
 
1247
        result = [r for r in result if r[0] is not None and r[1] is not None]
 
1248
    return result
 
1249
 
 
1250
 
 
1251
class LogRevision(object):
 
1252
    """A revision to be logged (by LogFormatter.log_revision).
 
1253
 
 
1254
    A simple wrapper for the attributes of a revision to be logged.
 
1255
    The attributes may or may not be populated, as determined by the
 
1256
    logging options and the log formatter capabilities.
 
1257
    """
 
1258
 
 
1259
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
 
1260
                 tags=None, diff=None):
 
1261
        self.rev = rev
 
1262
        self.revno = str(revno)
 
1263
        self.merge_depth = merge_depth
 
1264
        self.delta = delta
 
1265
        self.tags = tags
 
1266
        self.diff = diff
 
1267
 
 
1268
 
 
1269
class LogFormatter(object):
 
1270
    """Abstract class to display log messages.
 
1271
 
 
1272
    At a minimum, a derived class must implement the log_revision method.
 
1273
 
 
1274
    If the LogFormatter needs to be informed of the beginning or end of
 
1275
    a log it should implement the begin_log and/or end_log hook methods.
 
1276
 
 
1277
    A LogFormatter should define the following supports_XXX flags
 
1278
    to indicate which LogRevision attributes it supports:
 
1279
 
 
1280
    - supports_delta must be True if this log formatter supports delta.
 
1281
        Otherwise the delta attribute may not be populated.  The 'delta_format'
 
1282
        attribute describes whether the 'short_status' format (1) or the long
 
1283
        one (2) should be used.
 
1284
 
 
1285
    - supports_merge_revisions must be True if this log formatter supports
 
1286
        merge revisions.  If not, and if supports_single_merge_revision is
 
1287
        also not True, then only mainline revisions will be passed to the
 
1288
        formatter.
 
1289
 
 
1290
    - preferred_levels is the number of levels this formatter defaults to.
 
1291
        The default value is zero meaning display all levels.
 
1292
        This value is only relevant if supports_merge_revisions is True.
 
1293
 
 
1294
    - supports_single_merge_revision must be True if this log formatter
 
1295
        supports logging only a single merge revision.  This flag is
 
1296
        only relevant if supports_merge_revisions is not True.
 
1297
 
 
1298
    - supports_tags must be True if this log formatter supports tags.
 
1299
        Otherwise the tags attribute may not be populated.
 
1300
 
 
1301
    - supports_diff must be True if this log formatter supports diffs.
 
1302
        Otherwise the diff attribute may not be populated.
 
1303
 
 
1304
    Plugins can register functions to show custom revision properties using
 
1305
    the properties_handler_registry. The registered function
 
1306
    must respect the following interface description:
 
1307
        def my_show_properties(properties_dict):
 
1308
            # code that returns a dict {'name':'value'} of the properties
 
1309
            # to be shown
 
1310
    """
 
1311
    preferred_levels = 0
 
1312
 
 
1313
    def __init__(self, to_file, show_ids=False, show_timezone='original',
 
1314
                 delta_format=None, levels=None):
 
1315
        """Create a LogFormatter.
 
1316
 
 
1317
        :param to_file: the file to output to
 
1318
        :param show_ids: if True, revision-ids are to be displayed
 
1319
        :param show_timezone: the timezone to use
 
1320
        :param delta_format: the level of delta information to display
 
1321
          or None to leave it u to the formatter to decide
 
1322
        :param levels: the number of levels to display; None or -1 to
 
1323
          let the log formatter decide.
 
1324
        """
 
1325
        self.to_file = to_file
 
1326
        # 'exact' stream used to show diff, it should print content 'as is'
 
1327
        # and should not try to decode/encode it to unicode to avoid bug #328007
 
1328
        self.to_exact_file = getattr(to_file, 'stream', to_file)
 
1329
        self.show_ids = show_ids
 
1330
        self.show_timezone = show_timezone
 
1331
        if delta_format is None:
 
1332
            # Ensures backward compatibility
 
1333
            delta_format = 2 # long format
 
1334
        self.delta_format = delta_format
 
1335
        self.levels = levels
 
1336
 
 
1337
    def get_levels(self):
 
1338
        """Get the number of levels to display or 0 for all."""
 
1339
        if getattr(self, 'supports_merge_revisions', False):
 
1340
            if self.levels is None or self.levels == -1:
 
1341
                return self.preferred_levels
 
1342
            else:
 
1343
                return self.levels
 
1344
        return 1
 
1345
 
 
1346
    def log_revision(self, revision):
 
1347
        """Log a revision.
 
1348
 
 
1349
        :param  revision:   The LogRevision to be logged.
 
1350
        """
 
1351
        raise NotImplementedError('not implemented in abstract base')
 
1352
 
 
1353
    def short_committer(self, rev):
 
1354
        name, address = config.parse_username(rev.committer)
 
1355
        if name:
 
1356
            return name
 
1357
        return address
 
1358
 
 
1359
    def short_author(self, rev):
 
1360
        name, address = config.parse_username(rev.get_apparent_authors()[0])
 
1361
        if name:
 
1362
            return name
 
1363
        return address
 
1364
 
 
1365
    def show_properties(self, revision, indent):
 
1366
        """Displays the custom properties returned by each registered handler.
 
1367
 
 
1368
        If a registered handler raises an error it is propagated.
 
1369
        """
 
1370
        for key, handler in properties_handler_registry.iteritems():
 
1371
            for key, value in handler(revision).items():
 
1372
                self.to_file.write(indent + key + ': ' + value + '\n')
 
1373
 
 
1374
    def show_diff(self, to_file, diff, indent):
 
1375
        for l in diff.rstrip().split('\n'):
 
1376
            to_file.write(indent + '%s\n' % (l,))
 
1377
 
 
1378
 
 
1379
class LongLogFormatter(LogFormatter):
 
1380
 
 
1381
    supports_merge_revisions = True
 
1382
    supports_delta = True
 
1383
    supports_tags = True
 
1384
    supports_diff = True
 
1385
 
 
1386
    def log_revision(self, revision):
 
1387
        """Log a revision, either merged or not."""
 
1388
        indent = '    ' * revision.merge_depth
 
1389
        to_file = self.to_file
 
1390
        to_file.write(indent + '-' * 60 + '\n')
 
1391
        if revision.revno is not None:
 
1392
            to_file.write(indent + 'revno: %s\n' % (revision.revno,))
 
1393
        if revision.tags:
 
1394
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
 
1395
        if self.show_ids:
 
1396
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
 
1397
            to_file.write('\n')
 
1398
            for parent_id in revision.rev.parent_ids:
 
1399
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
 
1400
        self.show_properties(revision.rev, indent)
 
1401
 
 
1402
        committer = revision.rev.committer
 
1403
        authors = revision.rev.get_apparent_authors()
 
1404
        if authors != [committer]:
 
1405
            to_file.write(indent + 'author: %s\n' % (", ".join(authors),))
 
1406
        to_file.write(indent + 'committer: %s\n' % (committer,))
 
1407
 
 
1408
        branch_nick = revision.rev.properties.get('branch-nick', None)
 
1409
        if branch_nick is not None:
 
1410
            to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
 
1411
 
 
1412
        date_str = format_date(revision.rev.timestamp,
 
1413
                               revision.rev.timezone or 0,
 
1414
                               self.show_timezone)
 
1415
        to_file.write(indent + 'timestamp: %s\n' % (date_str,))
 
1416
 
 
1417
        to_file.write(indent + 'message:\n')
 
1418
        if not revision.rev.message:
 
1419
            to_file.write(indent + '  (no message)\n')
 
1420
        else:
 
1421
            message = revision.rev.message.rstrip('\r\n')
 
1422
            for l in message.split('\n'):
 
1423
                to_file.write(indent + '  %s\n' % (l,))
 
1424
        if revision.delta is not None:
 
1425
            # We don't respect delta_format for compatibility
 
1426
            revision.delta.show(to_file, self.show_ids, indent=indent,
 
1427
                                short_status=False)
 
1428
        if revision.diff is not None:
 
1429
            to_file.write(indent + 'diff:\n')
 
1430
            # Note: we explicitly don't indent the diff (relative to the
 
1431
            # revision information) so that the output can be fed to patch -p0
 
1432
            self.show_diff(self.to_exact_file, revision.diff, indent)
 
1433
 
 
1434
 
 
1435
class ShortLogFormatter(LogFormatter):
 
1436
 
 
1437
    supports_merge_revisions = True
 
1438
    preferred_levels = 1
 
1439
    supports_delta = True
 
1440
    supports_tags = True
 
1441
    supports_diff = True
 
1442
 
 
1443
    def __init__(self, *args, **kwargs):
 
1444
        super(ShortLogFormatter, self).__init__(*args, **kwargs)
 
1445
        self.revno_width_by_depth = {}
 
1446
 
 
1447
    def log_revision(self, revision):
 
1448
        # We need two indents: one per depth and one for the information
 
1449
        # relative to that indent. Most mainline revnos are 5 chars or
 
1450
        # less while dotted revnos are typically 11 chars or less. Once
 
1451
        # calculated, we need to remember the offset for a given depth
 
1452
        # as we might be starting from a dotted revno in the first column
 
1453
        # and we want subsequent mainline revisions to line up.
 
1454
        depth = revision.merge_depth
 
1455
        indent = '    ' * depth
 
1456
        revno_width = self.revno_width_by_depth.get(depth)
 
1457
        if revno_width is None:
 
1458
            if revision.revno.find('.') == -1:
 
1459
                # mainline revno, e.g. 12345
 
1460
                revno_width = 5
 
1461
            else:
 
1462
                # dotted revno, e.g. 12345.10.55
 
1463
                revno_width = 11
 
1464
            self.revno_width_by_depth[depth] = revno_width
 
1465
        offset = ' ' * (revno_width + 1)
 
1466
 
 
1467
        to_file = self.to_file
 
1468
        is_merge = ''
 
1469
        if len(revision.rev.parent_ids) > 1:
 
1470
            is_merge = ' [merge]'
 
1471
        tags = ''
 
1472
        if revision.tags:
 
1473
            tags = ' {%s}' % (', '.join(revision.tags))
 
1474
        to_file.write(indent + "%*s %s\t%s%s%s\n" % (revno_width,
 
1475
                revision.revno, self.short_author(revision.rev),
 
1476
                format_date(revision.rev.timestamp,
 
1477
                            revision.rev.timezone or 0,
 
1478
                            self.show_timezone, date_fmt="%Y-%m-%d",
 
1479
                            show_offset=False),
 
1480
                tags, is_merge))
 
1481
        self.show_properties(revision.rev, indent+offset)
 
1482
        if self.show_ids:
 
1483
            to_file.write(indent + offset + 'revision-id:%s\n'
 
1484
                          % (revision.rev.revision_id,))
 
1485
        if not revision.rev.message:
 
1486
            to_file.write(indent + offset + '(no message)\n')
 
1487
        else:
 
1488
            message = revision.rev.message.rstrip('\r\n')
 
1489
            for l in message.split('\n'):
 
1490
                to_file.write(indent + offset + '%s\n' % (l,))
 
1491
 
 
1492
        if revision.delta is not None:
 
1493
            revision.delta.show(to_file, self.show_ids, indent=indent + offset,
 
1494
                                short_status=self.delta_format==1)
 
1495
        if revision.diff is not None:
 
1496
            self.show_diff(self.to_exact_file, revision.diff, '      ')
 
1497
        to_file.write('\n')
 
1498
 
 
1499
 
 
1500
class LineLogFormatter(LogFormatter):
 
1501
 
 
1502
    supports_merge_revisions = True
 
1503
    preferred_levels = 1
 
1504
    supports_tags = True
 
1505
 
 
1506
    def __init__(self, *args, **kwargs):
 
1507
        super(LineLogFormatter, self).__init__(*args, **kwargs)
 
1508
        self._max_chars = terminal_width() - 1
 
1509
 
 
1510
    def truncate(self, str, max_len):
 
1511
        if len(str) <= max_len:
 
1512
            return str
 
1513
        return str[:max_len-3]+'...'
 
1514
 
 
1515
    def date_string(self, rev):
 
1516
        return format_date(rev.timestamp, rev.timezone or 0,
 
1517
                           self.show_timezone, date_fmt="%Y-%m-%d",
 
1518
                           show_offset=False)
 
1519
 
 
1520
    def message(self, rev):
 
1521
        if not rev.message:
 
1522
            return '(no message)'
 
1523
        else:
 
1524
            return rev.message
 
1525
 
 
1526
    def log_revision(self, revision):
 
1527
        indent = '  ' * revision.merge_depth
 
1528
        self.to_file.write(self.log_string(revision.revno, revision.rev,
 
1529
            self._max_chars, revision.tags, indent))
 
1530
        self.to_file.write('\n')
 
1531
 
 
1532
    def log_string(self, revno, rev, max_chars, tags=None, prefix=''):
 
1533
        """Format log info into one string. Truncate tail of string
 
1534
        :param  revno:      revision number or None.
 
1535
                            Revision numbers counts from 1.
 
1536
        :param  rev:        revision object
 
1537
        :param  max_chars:  maximum length of resulting string
 
1538
        :param  tags:       list of tags or None
 
1539
        :param  prefix:     string to prefix each line
 
1540
        :return:            formatted truncated string
 
1541
        """
 
1542
        out = []
 
1543
        if revno:
 
1544
            # show revno only when is not None
 
1545
            out.append("%s:" % revno)
 
1546
        out.append(self.truncate(self.short_author(rev), 20))
 
1547
        out.append(self.date_string(rev))
 
1548
        if len(rev.parent_ids) > 1:
 
1549
            out.append('[merge]')
 
1550
        if tags:
 
1551
            tag_str = '{%s}' % (', '.join(tags))
 
1552
            out.append(tag_str)
 
1553
        out.append(rev.get_summary())
 
1554
        return self.truncate(prefix + " ".join(out).rstrip('\n'), max_chars)
 
1555
 
 
1556
 
 
1557
class GnuChangelogLogFormatter(LogFormatter):
 
1558
 
 
1559
    supports_merge_revisions = True
 
1560
    supports_delta = True
 
1561
 
 
1562
    def log_revision(self, revision):
 
1563
        """Log a revision, either merged or not."""
 
1564
        to_file = self.to_file
 
1565
 
 
1566
        date_str = format_date(revision.rev.timestamp,
 
1567
                               revision.rev.timezone or 0,
 
1568
                               self.show_timezone,
 
1569
                               date_fmt='%Y-%m-%d',
 
1570
                               show_offset=False)
 
1571
        committer_str = revision.rev.committer.replace (' <', '  <')
 
1572
        to_file.write('%s  %s\n\n' % (date_str,committer_str))
 
1573
 
 
1574
        if revision.delta is not None and revision.delta.has_changed():
 
1575
            for c in revision.delta.added + revision.delta.removed + revision.delta.modified:
 
1576
                path, = c[:1]
 
1577
                to_file.write('\t* %s:\n' % (path,))
 
1578
            for c in revision.delta.renamed:
 
1579
                oldpath,newpath = c[:2]
 
1580
                # For renamed files, show both the old and the new path
 
1581
                to_file.write('\t* %s:\n\t* %s:\n' % (oldpath,newpath))
 
1582
            to_file.write('\n')
 
1583
 
 
1584
        if not revision.rev.message:
 
1585
            to_file.write('\tNo commit message\n')
 
1586
        else:
 
1587
            message = revision.rev.message.rstrip('\r\n')
 
1588
            for l in message.split('\n'):
 
1589
                to_file.write('\t%s\n' % (l.lstrip(),))
 
1590
            to_file.write('\n')
 
1591
 
 
1592
 
 
1593
def line_log(rev, max_chars):
 
1594
    lf = LineLogFormatter(None)
 
1595
    return lf.log_string(None, rev, max_chars)
 
1596
 
 
1597
 
 
1598
class LogFormatterRegistry(registry.Registry):
 
1599
    """Registry for log formatters"""
 
1600
 
 
1601
    def make_formatter(self, name, *args, **kwargs):
 
1602
        """Construct a formatter from arguments.
 
1603
 
 
1604
        :param name: Name of the formatter to construct.  'short', 'long' and
 
1605
            'line' are built-in.
 
1606
        """
 
1607
        return self.get(name)(*args, **kwargs)
 
1608
 
 
1609
    def get_default(self, branch):
 
1610
        return self.get(branch.get_config().log_format())
 
1611
 
 
1612
 
 
1613
log_formatter_registry = LogFormatterRegistry()
 
1614
 
 
1615
 
 
1616
log_formatter_registry.register('short', ShortLogFormatter,
 
1617
                                'Moderately short log format')
 
1618
log_formatter_registry.register('long', LongLogFormatter,
 
1619
                                'Detailed log format')
 
1620
log_formatter_registry.register('line', LineLogFormatter,
 
1621
                                'Log format with one line per revision')
 
1622
log_formatter_registry.register('gnu-changelog', GnuChangelogLogFormatter,
 
1623
                                'Format used by GNU ChangeLog files')
 
1624
 
 
1625
 
 
1626
def register_formatter(name, formatter):
 
1627
    log_formatter_registry.register(name, formatter)
 
1628
 
 
1629
 
 
1630
def log_formatter(name, *args, **kwargs):
 
1631
    """Construct a formatter from arguments.
 
1632
 
 
1633
    name -- Name of the formatter to construct; currently 'long', 'short' and
 
1634
        'line' are supported.
 
1635
    """
 
1636
    try:
 
1637
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
 
1638
    except KeyError:
 
1639
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
 
1640
 
 
1641
 
 
1642
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
 
1643
    # deprecated; for compatibility
 
1644
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
 
1645
    lf.show(revno, rev, delta)
 
1646
 
 
1647
 
 
1648
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
 
1649
                           log_format='long'):
 
1650
    """Show the change in revision history comparing the old revision history to the new one.
 
1651
 
 
1652
    :param branch: The branch where the revisions exist
 
1653
    :param old_rh: The old revision history
 
1654
    :param new_rh: The new revision history
 
1655
    :param to_file: A file to write the results to. If None, stdout will be used
 
1656
    """
 
1657
    if to_file is None:
 
1658
        to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
 
1659
            errors='replace')
 
1660
    lf = log_formatter(log_format,
 
1661
                       show_ids=False,
 
1662
                       to_file=to_file,
 
1663
                       show_timezone='original')
 
1664
 
 
1665
    # This is the first index which is different between
 
1666
    # old and new
 
1667
    base_idx = None
 
1668
    for i in xrange(max(len(new_rh),
 
1669
                        len(old_rh))):
 
1670
        if (len(new_rh) <= i
 
1671
            or len(old_rh) <= i
 
1672
            or new_rh[i] != old_rh[i]):
 
1673
            base_idx = i
 
1674
            break
 
1675
 
 
1676
    if base_idx is None:
 
1677
        to_file.write('Nothing seems to have changed\n')
 
1678
        return
 
1679
    ## TODO: It might be nice to do something like show_log
 
1680
    ##       and show the merged entries. But since this is the
 
1681
    ##       removed revisions, it shouldn't be as important
 
1682
    if base_idx < len(old_rh):
 
1683
        to_file.write('*'*60)
 
1684
        to_file.write('\nRemoved Revisions:\n')
 
1685
        for i in range(base_idx, len(old_rh)):
 
1686
            rev = branch.repository.get_revision(old_rh[i])
 
1687
            lr = LogRevision(rev, i+1, 0, None)
 
1688
            lf.log_revision(lr)
 
1689
        to_file.write('*'*60)
 
1690
        to_file.write('\n\n')
 
1691
    if base_idx < len(new_rh):
 
1692
        to_file.write('Added Revisions:\n')
 
1693
        show_log(branch,
 
1694
                 lf,
 
1695
                 None,
 
1696
                 verbose=False,
 
1697
                 direction='forward',
 
1698
                 start_revision=base_idx+1,
 
1699
                 end_revision=len(new_rh),
 
1700
                 search=None)
 
1701
 
 
1702
 
 
1703
def get_history_change(old_revision_id, new_revision_id, repository):
 
1704
    """Calculate the uncommon lefthand history between two revisions.
 
1705
 
 
1706
    :param old_revision_id: The original revision id.
 
1707
    :param new_revision_id: The new revision id.
 
1708
    :param repository: The repository to use for the calculation.
 
1709
 
 
1710
    return old_history, new_history
 
1711
    """
 
1712
    old_history = []
 
1713
    old_revisions = set()
 
1714
    new_history = []
 
1715
    new_revisions = set()
 
1716
    new_iter = repository.iter_reverse_revision_history(new_revision_id)
 
1717
    old_iter = repository.iter_reverse_revision_history(old_revision_id)
 
1718
    stop_revision = None
 
1719
    do_old = True
 
1720
    do_new = True
 
1721
    while do_new or do_old:
 
1722
        if do_new:
 
1723
            try:
 
1724
                new_revision = new_iter.next()
 
1725
            except StopIteration:
 
1726
                do_new = False
 
1727
            else:
 
1728
                new_history.append(new_revision)
 
1729
                new_revisions.add(new_revision)
 
1730
                if new_revision in old_revisions:
 
1731
                    stop_revision = new_revision
 
1732
                    break
 
1733
        if do_old:
 
1734
            try:
 
1735
                old_revision = old_iter.next()
 
1736
            except StopIteration:
 
1737
                do_old = False
 
1738
            else:
 
1739
                old_history.append(old_revision)
 
1740
                old_revisions.add(old_revision)
 
1741
                if old_revision in new_revisions:
 
1742
                    stop_revision = old_revision
 
1743
                    break
 
1744
    new_history.reverse()
 
1745
    old_history.reverse()
 
1746
    if stop_revision is not None:
 
1747
        new_history = new_history[new_history.index(stop_revision) + 1:]
 
1748
        old_history = old_history[old_history.index(stop_revision) + 1:]
 
1749
    return old_history, new_history
 
1750
 
 
1751
 
 
1752
def show_branch_change(branch, output, old_revno, old_revision_id):
 
1753
    """Show the changes made to a branch.
 
1754
 
 
1755
    :param branch: The branch to show changes about.
 
1756
    :param output: A file-like object to write changes to.
 
1757
    :param old_revno: The revno of the old tip.
 
1758
    :param old_revision_id: The revision_id of the old tip.
 
1759
    """
 
1760
    new_revno, new_revision_id = branch.last_revision_info()
 
1761
    old_history, new_history = get_history_change(old_revision_id,
 
1762
                                                  new_revision_id,
 
1763
                                                  branch.repository)
 
1764
    if old_history == [] and new_history == []:
 
1765
        output.write('Nothing seems to have changed\n')
 
1766
        return
 
1767
 
 
1768
    log_format = log_formatter_registry.get_default(branch)
 
1769
    lf = log_format(show_ids=False, to_file=output, show_timezone='original')
 
1770
    if old_history != []:
 
1771
        output.write('*'*60)
 
1772
        output.write('\nRemoved Revisions:\n')
 
1773
        show_flat_log(branch.repository, old_history, old_revno, lf)
 
1774
        output.write('*'*60)
 
1775
        output.write('\n\n')
 
1776
    if new_history != []:
 
1777
        output.write('Added Revisions:\n')
 
1778
        start_revno = new_revno - len(new_history) + 1
 
1779
        show_log(branch, lf, None, verbose=False, direction='forward',
 
1780
                 start_revision=start_revno,)
 
1781
 
 
1782
 
 
1783
def show_flat_log(repository, history, last_revno, lf):
 
1784
    """Show a simple log of the specified history.
 
1785
 
 
1786
    :param repository: The repository to retrieve revisions from.
 
1787
    :param history: A list of revision_ids indicating the lefthand history.
 
1788
    :param last_revno: The revno of the last revision_id in the history.
 
1789
    :param lf: The log formatter to use.
 
1790
    """
 
1791
    start_revno = last_revno - len(history) + 1
 
1792
    revisions = repository.get_revisions(history)
 
1793
    for i, rev in enumerate(revisions):
 
1794
        lr = LogRevision(rev, i + last_revno, 0, None)
 
1795
        lf.log_revision(lr)
 
1796
 
 
1797
 
 
1798
def _get_info_for_log_files(revisionspec_list, file_list):
 
1799
    """Find file-ids and kinds given a list of files and a revision range.
 
1800
 
 
1801
    We search for files at the end of the range. If not found there,
 
1802
    we try the start of the range.
 
1803
 
 
1804
    :param revisionspec_list: revision range as parsed on the command line
 
1805
    :param file_list: the list of paths given on the command line;
 
1806
      the first of these can be a branch location or a file path,
 
1807
      the remainder must be file paths
 
1808
    :return: (branch, info_list, start_rev_info, end_rev_info) where
 
1809
      info_list is a list of (relative_path, file_id, kind) tuples where
 
1810
      kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
 
1811
    """
 
1812
    from builtins import _get_revision_range, safe_relpath_files
 
1813
    tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
 
1814
    # XXX: It's damn messy converting a list of paths to relative paths when
 
1815
    # those paths might be deleted ones, they might be on a case-insensitive
 
1816
    # filesystem and/or they might be in silly locations (like another branch).
 
1817
    # For example, what should "log bzr://branch/dir/file1 file2" do? (Is
 
1818
    # file2 implicitly in the same dir as file1 or should its directory be
 
1819
    # taken from the current tree somehow?) For now, this solves the common
 
1820
    # case of running log in a nested directory, assuming paths beyond the
 
1821
    # first one haven't been deleted ...
 
1822
    if tree:
 
1823
        relpaths = [path] + safe_relpath_files(tree, file_list[1:])
 
1824
    else:
 
1825
        relpaths = [path] + file_list[1:]
 
1826
    info_list = []
 
1827
    start_rev_info, end_rev_info = _get_revision_range(revisionspec_list, b,
 
1828
        "log")
 
1829
    if start_rev_info is None and end_rev_info is None:
 
1830
        if tree is None:
 
1831
            tree = b.basis_tree()
 
1832
        tree1 = None
 
1833
        for fp in relpaths:
 
1834
            file_id = tree.path2id(fp)
 
1835
            kind = _get_kind_for_file_id(tree, file_id)
 
1836
            if file_id is None:
 
1837
                # go back to when time began
 
1838
                if tree1 is None:
 
1839
                    try:
 
1840
                        rev1 = b.get_rev_id(1)
 
1841
                    except errors.NoSuchRevision:
 
1842
                        # No history at all
 
1843
                        file_id = None
 
1844
                        kind = None
 
1845
                    else:
 
1846
                        tree1 = b.repository.revision_tree(rev1)
 
1847
                if tree1:
 
1848
                    file_id = tree1.path2id(fp)
 
1849
                    kind = _get_kind_for_file_id(tree1, file_id)
 
1850
            info_list.append((fp, file_id, kind))
 
1851
 
 
1852
    elif start_rev_info == end_rev_info:
 
1853
        # One revision given - file must exist in it
 
1854
        tree = b.repository.revision_tree(end_rev_info.rev_id)
 
1855
        for fp in relpaths:
 
1856
            file_id = tree.path2id(fp)
 
1857
            kind = _get_kind_for_file_id(tree, file_id)
 
1858
            info_list.append((fp, file_id, kind))
 
1859
 
 
1860
    else:
 
1861
        # Revision range given. Get the file-id from the end tree.
 
1862
        # If that fails, try the start tree.
 
1863
        rev_id = end_rev_info.rev_id
 
1864
        if rev_id is None:
 
1865
            tree = b.basis_tree()
 
1866
        else:
 
1867
            tree = b.repository.revision_tree(rev_id)
 
1868
        tree1 = None
 
1869
        for fp in relpaths:
 
1870
            file_id = tree.path2id(fp)
 
1871
            kind = _get_kind_for_file_id(tree, file_id)
 
1872
            if file_id is None:
 
1873
                if tree1 is None:
 
1874
                    rev_id = start_rev_info.rev_id
 
1875
                    if rev_id is None:
 
1876
                        rev1 = b.get_rev_id(1)
 
1877
                        tree1 = b.repository.revision_tree(rev1)
 
1878
                    else:
 
1879
                        tree1 = b.repository.revision_tree(rev_id)
 
1880
                file_id = tree1.path2id(fp)
 
1881
                kind = _get_kind_for_file_id(tree1, file_id)
 
1882
            info_list.append((fp, file_id, kind))
 
1883
    return b, info_list, start_rev_info, end_rev_info
 
1884
 
 
1885
 
 
1886
def _get_kind_for_file_id(tree, file_id):
 
1887
    """Return the kind of a file-id or None if it doesn't exist."""
 
1888
    if file_id is not None:
 
1889
        return tree.kind(file_id)
 
1890
    else:
 
1891
        return None
 
1892
 
 
1893
 
 
1894
properties_handler_registry = registry.Registry()
 
1895
properties_handler_registry.register_lazy("foreign",
 
1896
                                          "bzrlib.foreign",
 
1897
                                          "show_foreign_properties")
 
1898
 
 
1899
 
 
1900
# adapters which revision ids to log are filtered. When log is called, the
 
1901
# log_rev_iterator is adapted through each of these factory methods.
 
1902
# Plugins are welcome to mutate this list in any way they like - as long
 
1903
# as the overall behaviour is preserved. At this point there is no extensible
 
1904
# mechanism for getting parameters to each factory method, and until there is
 
1905
# this won't be considered a stable api.
 
1906
log_adapters = [
 
1907
    # core log logic
 
1908
    _make_batch_filter,
 
1909
    # read revision objects
 
1910
    _make_revision_objects,
 
1911
    # filter on log messages
 
1912
    _make_search_filter,
 
1913
    # generate deltas for things we will show
 
1914
    _make_delta_filter
 
1915
    ]