/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
369 by Martin Pool
- Split out log printing into new show_log function
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
369 by Martin Pool
- Split out log printing into new show_log function
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
369 by Martin Pool
- Split out log printing into new show_log function
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
375 by Martin Pool
- New command touching-revisions and function to trace
17
18
527 by Martin Pool
- refactor log command
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
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
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
2466.12.2 by Kent Gibson
shift log output with only merge revisions to the left margin
45
relative to its left-most parent, not the delta relative to the last
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
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.
527 by Martin Pool
- refactor log command
50
"""
51
2997.1.2 by Kent Gibson
Move all imports to top of log.py
52
import codecs
53
from itertools import (
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
54
    chain,
2997.1.2 by Kent Gibson
Move all imports to top of log.py
55
    izip,
56
    )
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
57
import re
2997.1.2 by Kent Gibson
Move all imports to top of log.py
58
import sys
59
from warnings import (
60
    warn,
61
    )
1185.33.41 by Martin Pool
Fix regression of 'bzr log -v' - it wasn't showing changed files at all. (#4676)
62
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
63
from bzrlib.lazy_import import lazy_import
64
lazy_import(globals(), """
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
65
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
66
from bzrlib import (
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
67
    config,
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
68
    errors,
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
69
    repository as _mod_repository,
70
    revision as _mod_revision,
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
71
    revisionspec,
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
72
    trace,
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
73
    tsort,
74
    )
75
""")
76
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
77
from bzrlib import (
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
78
    registry,
2997.1.2 by Kent Gibson
Move all imports to top of log.py
79
    )
80
from bzrlib.osutils import (
81
    format_date,
2997.1.3 by Alexander Belchenko
file wrapper around stdout should use terminal encoding, not user_encoding.
82
    get_terminal_encoding,
2997.1.2 by Kent Gibson
Move all imports to top of log.py
83
    terminal_width,
84
    )
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
85
375 by Martin Pool
- New command touching-revisions and function to trace
86
87
def find_touching_revisions(branch, file_id):
88
    """Yield a description of revisions which affect the file_id.
89
90
    Each returned element is (revno, revision_id, description)
91
92
    This is the list of revisions where the file is either added,
93
    modified, renamed or deleted.
94
95
    TODO: Perhaps some way to limit this to only particular revisions,
522 by Martin Pool
todo
96
    or to traverse a non-mainline set of revisions?
375 by Martin Pool
- New command touching-revisions and function to trace
97
    """
98
    last_ie = None
99
    last_path = None
100
    revno = 1
101
    for revision_id in branch.revision_history():
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
102
        this_inv = branch.repository.get_revision_inventory(revision_id)
375 by Martin Pool
- New command touching-revisions and function to trace
103
        if file_id in this_inv:
104
            this_ie = this_inv[file_id]
105
            this_path = this_inv.id2path(file_id)
106
        else:
107
            this_ie = this_path = None
108
109
        # now we know how it was last time, and how it is in this revision.
110
        # are those two states effectively the same or not?
111
112
        if not this_ie and not last_ie:
113
            # not present in either
114
            pass
115
        elif this_ie and not last_ie:
116
            yield revno, revision_id, "added " + this_path
117
        elif not this_ie and last_ie:
118
            # deleted here
119
            yield revno, revision_id, "deleted " + last_path
120
        elif this_path != last_path:
121
            yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
122
        elif (this_ie.text_size != last_ie.text_size
123
              or this_ie.text_sha1 != last_ie.text_sha1):
124
            yield revno, revision_id, "modified " + this_path
125
126
        last_ie = this_ie
127
        last_path = this_path
128
        revno += 1
129
130
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
131
def _enumerate_history(branch):
132
    rh = []
133
    revno = 1
134
    for rev_id in branch.revision_history():
135
        rh.append((revno, rev_id))
136
        revno += 1
137
    return rh
138
139
378 by Martin Pool
- New usage bzr log FILENAME
140
def show_log(branch,
794 by Martin Pool
- Merge John's nice short-log format.
141
             lf,
527 by Martin Pool
- refactor log command
142
             specific_fileid=None,
378 by Martin Pool
- New usage bzr log FILENAME
143
             verbose=False,
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
144
             direction='reverse',
145
             start_revision=None,
900 by Martin Pool
- patch from john to search for matching commits
146
             end_revision=None,
2466.9.1 by Kent Gibson
add bzr log --limit
147
             search=None,
3936.3.8 by Ian Clatworthy
back-out --strict
148
             limit=None):
369 by Martin Pool
- Split out log printing into new show_log function
149
    """Write out human-readable log of commits to this branch.
150
3874.2.2 by Vincent Ladeuil
Cleanup show_log doc string.
151
    :param lf: The LogFormatter object showing the output.
152
153
    :param specific_fileid: If not None, list only the commits affecting the
154
        specified file, rather than all commits.
155
156
    :param verbose: If True show added/changed/deleted/renamed files.
157
158
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
159
        earliest to latest.
160
161
    :param start_revision: If not None, only show revisions >= start_revision
162
163
    :param end_revision: If not None, only show revisions <= end_revision
164
165
    :param search: If not None, only show revisions with matching commit
166
        messages
167
168
    :param limit: If set, shows only 'limit' revisions, all revisions are shown
169
        if None or 0.
369 by Martin Pool
- Split out log printing into new show_log function
170
    """
1417.1.7 by Robert Collins
teach log it needs a read lock
171
    branch.lock_read()
172
    try:
2466.8.2 by Kent Gibson
Move begin/end calls from _show_log to show_log. Fix long line.
173
        if getattr(lf, 'begin_log', None):
174
            lf.begin_log()
175
1756.1.6 by Aaron Bentley
Revert locking fix
176
        _show_log(branch, lf, specific_fileid, verbose, direction,
3936.3.8 by Ian Clatworthy
back-out --strict
177
                  start_revision, end_revision, search, limit)
2466.8.2 by Kent Gibson
Move begin/end calls from _show_log to show_log. Fix long line.
178
179
        if getattr(lf, 'end_log', None):
180
            lf.end_log()
1417.1.7 by Robert Collins
teach log it needs a read lock
181
    finally:
182
        branch.unlock()
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
183
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
184
1417.1.7 by Robert Collins
teach log it needs a read lock
185
def _show_log(branch,
186
             lf,
187
             specific_fileid=None,
188
             verbose=False,
189
             direction='reverse',
190
             start_revision=None,
191
             end_revision=None,
2466.9.1 by Kent Gibson
add bzr log --limit
192
             search=None,
3936.3.8 by Ian Clatworthy
back-out --strict
193
             limit=None):
1417.1.7 by Robert Collins
teach log it needs a read lock
194
    """Worker function for show_log - see show_log."""
794 by Martin Pool
- Merge John's nice short-log format.
195
    if not isinstance(lf, LogFormatter):
196
        warn("not a LogFormatter instance: %r" % lf)
533 by Martin Pool
- fix up asking for the log for the root of a remote branch
197
    if specific_fileid:
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
198
        trace.mutter('get log for file_id %r', specific_fileid)
3936.3.1 by Ian Clatworthy
refactor _show_log
199
200
    # Consult the LogFormatter about what it needs and can handle
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
201
    generate_merge_revisions = getattr(lf, 'supports_merge_revisions', False)
202
    allow_single_merge_revision = getattr(lf,
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
203
        'supports_single_merge_revision', generate_merge_revisions)
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
204
    generate_tags = getattr(lf, 'supports_tags', False)
3936.3.1 by Ian Clatworthy
refactor _show_log
205
    if generate_tags and branch.supports_tags():
206
        rev_tag_dict = branch.tags.get_reverse_tag_dict()
207
    else:
208
        rev_tag_dict = {}
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
209
    generate_delta = verbose and getattr(lf, 'supports_delta', False)
210
3936.3.1 by Ian Clatworthy
refactor _show_log
211
    # Find and print the interesting revisions
3936.3.13 by Ian Clatworthy
feedback from jameinel
212
    log_count = 0
213
    revision_iterator = _create_log_revision_iterator(branch,
214
        start_revision, end_revision, direction, specific_fileid, search,
215
        generate_merge_revisions, allow_single_merge_revision,
3936.3.22 by Ian Clatworthy
make incremental file logging fast again
216
        generate_delta)
3936.3.13 by Ian Clatworthy
feedback from jameinel
217
    for revs in revision_iterator:
218
        for (rev_id, revno, merge_depth), rev, delta in revs:
219
            lr = LogRevision(rev, revno, merge_depth, delta,
220
                             rev_tag_dict.get(rev_id))
221
            lf.log_revision(lr)
222
            if limit:
223
                log_count += 1
224
                if log_count >= limit:
225
                    return
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
226
227
3936.3.1 by Ian Clatworthy
refactor _show_log
228
def _create_log_revision_iterator(branch, start_revision, end_revision,
229
    direction, specific_fileid, search, generate_merge_revisions,
3936.3.18 by Ian Clatworthy
faster incremental results for FILE logging
230
    allow_single_merge_revision, generate_delta,
3936.3.22 by Ian Clatworthy
make incremental file logging fast again
231
    force_incremental_matching=False):
3936.3.1 by Ian Clatworthy
refactor _show_log
232
    """Create a revision iterator for log.
233
234
    :param branch: The branch being logged.
235
    :param start_revision: If not None, only show revisions >= start_revision
236
    :param end_revision: If not None, only show revisions <= end_revision
237
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
238
        earliest to latest.
239
    :param specific_fileid: If not None, list only the commits affecting the
240
        specified file.
241
    :param search: If not None, only show revisions with matching commit
242
        messages.
243
    :param generate_merge_revisions: If False, show only mainline revisions.
3936.3.2 by Ian Clatworthy
minor cleanups
244
    :param allow_single_merge_revision: If True, logging of a single
245
        revision off the mainline is to be allowed
3936.3.1 by Ian Clatworthy
refactor _show_log
246
    :param generate_delta: Whether to generate a delta for each revision.
3936.3.18 by Ian Clatworthy
faster incremental results for FILE logging
247
    :param force_incremental_matching: if there's a file_id, use deltas
248
        to match it unconditionally
3936.3.1 by Ian Clatworthy
refactor _show_log
249
250
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
251
        delta).
252
    """
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
253
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
254
        end_revision)
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
255
3936.3.20 by Ian Clatworthy
must use per-file-graph for full history still
256
    # Decide how file-ids are matched: delta-filtering vs per-file graph.
3936.3.17 by Ian Clatworthy
delta filtering bug fix
257
    # Delta filtering allows revisions to be displayed incrementally
3936.3.20 by Ian Clatworthy
must use per-file-graph for full history still
258
    # though the total time is much slower for huge repositories: log -v
259
    # is the *lower* performance bound. At least until the split
260
    # inventory format arrives, per-file-graph needs to remain the
261
    # default when no limits are given. Delta filtering should give more
262
    # accurate results (e.g. inclusion of FILE deletions) so arguably
263
    # it should always be used in the future.
3936.3.18 by Ian Clatworthy
faster incremental results for FILE logging
264
    use_deltas_for_matching = specific_fileid and (force_incremental_matching
3936.3.20 by Ian Clatworthy
must use per-file-graph for full history still
265
        or generate_delta or start_rev_id or end_rev_id)
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
266
    if use_deltas_for_matching:
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
267
        view_revisions = _calc_view_revisions(branch, start_rev_id, end_rev_id,
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
268
            direction, generate_merge_revisions, allow_single_merge_revision)
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
269
        if specific_fileid:
270
            fileids = set([specific_fileid])
271
        else:
272
            fileids = None
3936.3.17 by Ian Clatworthy
delta filtering bug fix
273
        return make_log_rev_iterator(branch, view_revisions, generate_delta,
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
274
            search, file_ids=fileids, direction=direction)
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
275
    else:
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
276
        view_revisions = _calc_view_revisions(branch, start_rev_id, end_rev_id,
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
277
            direction, generate_merge_revisions or specific_fileid,
278
            allow_single_merge_revision)
279
        if specific_fileid:
280
            view_revisions = _filter_revisions_touching_file_id(branch,
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
281
                specific_fileid, list(view_revisions),
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
282
                include_merges=generate_merge_revisions)
283
        return make_log_rev_iterator(branch, view_revisions, generate_delta,
284
            search)
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
285
286
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
287
class _StartNotLinearAncestor(Exception):
288
    """Raised when a start revision is not found walking left-hand history."""
289
290
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
291
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
292
    generate_merge_revisions, allow_single_merge_revision):
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
293
    """Calculate the revisions to view.
294
295
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
296
             a list of the same tuples.
297
    """
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
298
    br_revno, br_rev_id = branch.last_revision_info()
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
299
    if br_revno == 0:
300
        return []
301
3936.3.10 by Ian Clatworthy
more single revision clean-up
302
    # If a single revision is requested, check we can handle it
3936.3.35 by Ian Clatworthy
simplify single revision logic
303
    generate_single_revision = (end_rev_id and start_rev_id == end_rev_id and
304
        (not generate_merge_revisions or not _has_merges(branch, end_rev_id)))
3936.3.10 by Ian Clatworthy
more single revision clean-up
305
    if generate_single_revision:
3936.3.35 by Ian Clatworthy
simplify single revision logic
306
        if end_rev_id == br_rev_id:
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
307
            # It's the tip
3936.3.35 by Ian Clatworthy
simplify single revision logic
308
            return [(br_rev_id, br_revno, 0)]
309
        else:
310
            revno = branch.revision_id_to_dotted_revno(end_rev_id)
3936.3.26 by Ian Clatworthy
use new dotted-revno-revision-id conversion methods to simplify & speed up code
311
            if len(revno) > 1 and not allow_single_merge_revision:
312
                # It's a merge revision and the log formatter is
313
                # completely brain dead. This "feature" of allowing
314
                # log formatters incapable of displaying dotted revnos
315
                # ought to be deprecated IMNSHO. IGC 20091022
316
                raise errors.BzrCommandError('Selected log formatter only'
317
                    ' supports mainline revisions.')
318
            revno_str = '.'.join(str(n) for n in revno)
3936.3.35 by Ian Clatworthy
simplify single revision logic
319
            return [(end_rev_id, revno_str, 0)]
3936.3.10 by Ian Clatworthy
more single revision clean-up
320
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
321
    # If we only want to see linear revisions, we can iterate ...
3936.3.10 by Ian Clatworthy
more single revision clean-up
322
    if not generate_merge_revisions:
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
323
        result = _linear_view_revisions(branch, start_rev_id, end_rev_id)
3936.3.18 by Ian Clatworthy
faster incremental results for FILE logging
324
        # If a start limit was given and it's not obviously an
325
        # ancestor of the end limit, check it before outputting anything
3936.3.31 by Ian Clatworthy
nicer obvious ancestor checking
326
        if start_rev_id and not (_is_obvious_ancestor(branch, start_rev_id,
327
            end_rev_id)):
3936.3.13 by Ian Clatworthy
feedback from jameinel
328
            try:
329
                result = list(result)
330
            except _StartNotLinearAncestor:
331
                raise errors.BzrCommandError('Start revision not found in'
332
                    ' left-hand history of end revision.')
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
333
        if direction == 'forward':
334
            result = reversed(list(result))
335
        return result
336
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
337
    # On large trees, generating the merge graph can take 30+ seconds
338
    # so we delay doing it until a merge is detected, incrementally
339
    # returning initial (non-merge) revisions while we can.
340
    initial_revisions = []
341
    try:
342
        for rev_id, revno, depth in \
343
            _linear_view_revisions(branch, start_rev_id, end_rev_id):
344
            if _has_merges(branch, rev_id):
345
                end_rev_id = rev_id
346
                break
347
            else:
348
                initial_revisions.append((rev_id, revno, depth))
349
        else:
350
            # No merged revisions found
351
            if direction == 'reverse':
352
                return initial_revisions
353
            elif direction == 'forward':
354
                return reversed(initial_revisions)
355
            else:
356
                raise ValueError('invalid direction %r' % direction)
357
    except _StartNotLinearAncestor:
358
        # A merge was never detected so the lower revision limit can't
359
        # be nested down somewhere
360
        raise errors.BzrCommandError('Start revision not found in'
361
            ' history of end revision.')
3936.3.15 by Ian Clatworthy
faster long log for a limited range with no merges
362
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
363
    # A log including nested merges is required. If the direction is reverse,
364
    # we rebase the initial merge depths so that the development line is
365
    # shown naturally, i.e. just like it is for linear logging. We *could*
366
    # make forward the exact opposite display, but showing the merge revisions
367
    # indented at the end seems slightly nicer in that case.
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
368
    view_revisions = chain(iter(initial_revisions),
369
        _graph_view_revisions(branch, start_rev_id, end_rev_id,
370
        rebase_initial_depths=direction == 'reverse'))
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
371
    if direction == 'reverse':
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
372
        return view_revisions
373
    elif direction == 'forward':
374
        # Forward means oldest first, adjusting for depth.
375
        view_revisions = reverse_by_depth(list(view_revisions))
376
        return _rebase_merge_depth(view_revisions)
377
    else:
378
        raise ValueError('invalid direction %r' % direction)
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
379
530 by Martin Pool
- put back verbose log support for reversed logs
380
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
381
def _has_merges(branch, rev_id):
382
    """Does a revision have multiple parents or not?"""
383
    return len(branch.repository.get_revision(rev_id).parent_ids) > 1
384
385
3936.3.31 by Ian Clatworthy
nicer obvious ancestor checking
386
def _is_obvious_ancestor(branch, start_rev_id, end_rev_id):
387
    """Is start_rev_id an obvious ancestor of end_rev_id?"""
388
    if start_rev_id and end_rev_id:
389
        start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
390
        end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
391
        if len(start_dotted) == 1 and len(end_dotted) == 1:
392
            # both on mainline
393
            return start_dotted[0] <= end_dotted[0]
394
        elif (len(start_dotted) == 3 and len(end_dotted) == 3 and
395
            start_dotted[0:1] == end_dotted[0:1]):
396
            # both on same development line
397
            return start_dotted[2] <= end_dotted[2]
398
        else:
399
            # not obvious
3936.3.18 by Ian Clatworthy
faster incremental results for FILE logging
400
            return False
401
    return True
402
403
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
404
def _linear_view_revisions(branch, start_rev_id, end_rev_id):
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
405
    """Calculate a sequence of revisions to view, newest to oldest.
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
406
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
407
    :param start_rev_id: the lower revision-id
408
    :param end_rev_id: the upper revision-id
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
409
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
410
    :raises _StartNotLinearAncestor: if a start_rev_id is specified but
411
      is not found walking the left-hand history
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
412
    """
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
413
    br_revno, br_rev_id = branch.last_revision_info()
3943.4.5 by John Arbash Meinel
Restore _linear_view_revisions.
414
    repo = branch.repository
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
415
    if start_rev_id is None and end_rev_id is None:
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
416
        cur_revno = br_revno
417
        for revision_id in repo.iter_reverse_revision_history(br_rev_id):
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
418
            yield revision_id, str(cur_revno), 0
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
419
            cur_revno -= 1
3936.3.14 by Ian Clatworthy
bug fix
420
    else:
421
        if end_rev_id is None:
422
            end_rev_id = br_rev_id
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
423
        found_start = start_rev_id is None
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
424
        for revision_id in repo.iter_reverse_revision_history(end_rev_id):
3936.3.26 by Ian Clatworthy
use new dotted-revno-revision-id conversion methods to simplify & speed up code
425
            revno = branch.revision_id_to_dotted_revno(revision_id)
426
            revno_str = '.'.join(str(n) for n in revno)
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
427
            if not found_start and revision_id == start_rev_id:
428
                yield revision_id, revno_str, 0
429
                found_start = True
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
430
                break
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
431
            else:
432
                yield revision_id, revno_str, 0
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
433
        else:
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
434
            if not found_start:
435
                raise _StartNotLinearAncestor()
3302.1.3 by Aaron Bentley
Add optimization of the simple case of generating view revisions
436
437
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
438
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
439
    rebase_initial_depths=True):
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
440
    """Calculate revisions to view including merges, newest to oldest.
441
442
    :param branch: the branch
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
443
    :param start_rev_id: the lower revision-id
444
    :param end_rev_id: the upper revision-id
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
445
    :param rebase_initial_depth: should depths be rebased until a mainline
446
      revision is found?
447
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
448
    """
449
    view_revisions = branch.iter_merge_sorted_revisions(
450
        start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
451
        stop_rule="with-merges")
452
    if not rebase_initial_depths:
453
        for (rev_id, merge_depth, revno, end_of_merge
454
             ) in view_revisions:
455
            yield rev_id, '.'.join(map(str, revno)), merge_depth
456
    else:
457
        # We're following a development line starting at a merged revision.
458
        # We need to adjust depths down by the initial depth until we find
459
        # a depth less than it. Then we use that depth as the adjustment.
460
        # If and when we reach the mainline, depth adjustment ends.
461
        depth_adjustment = None
462
        for (rev_id, merge_depth, revno, end_of_merge
463
             ) in view_revisions:
464
            if depth_adjustment is None:
465
                depth_adjustment = merge_depth
466
            if depth_adjustment:
467
                if merge_depth < depth_adjustment:
468
                    depth_adjustment = merge_depth
469
                merge_depth -= depth_adjustment
470
            yield rev_id, '.'.join(map(str, revno)), merge_depth
471
472
3936.3.13 by Ian Clatworthy
feedback from jameinel
473
def calculate_view_revisions(branch, start_revision, end_revision, direction,
474
        specific_fileid, generate_merge_revisions, allow_single_merge_revision):
475
    """Calculate the revisions to view.
476
477
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
478
             a list of the same tuples.
479
    """
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
480
    # This method is no longer called by the main code path.
481
    # It is retained for API compatibility and may be deprecated
482
    # soon. IGC 20090116
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
483
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
484
        end_revision)
485
    view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
3936.3.13 by Ian Clatworthy
feedback from jameinel
486
        direction, generate_merge_revisions or specific_fileid,
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
487
        allow_single_merge_revision))
3936.3.13 by Ian Clatworthy
feedback from jameinel
488
    if specific_fileid:
489
        view_revisions = _filter_revisions_touching_file_id(branch,
490
            specific_fileid, view_revisions,
491
            include_merges=generate_merge_revisions)
3936.3.28 by Ian Clatworthy
api compatibility: calculate_view_revisions rebases merge depth again
492
    return _rebase_merge_depth(view_revisions)
3936.3.13 by Ian Clatworthy
feedback from jameinel
493
494
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
495
def _rebase_merge_depth(view_revisions):
496
    """Adjust depths upwards so the top level is 0."""
497
    # If either the first or last revision have a merge_depth of 0, we're done
498
    if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
499
        min_depth = min([d for r,n,d in view_revisions])
500
        if min_depth != 0:
501
            view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
502
    return view_revisions
503
504
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
505
def make_log_rev_iterator(branch, view_revisions, generate_delta, search,
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
506
        file_ids=None, direction='reverse'):
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
507
    """Create a revision iterator for log.
508
509
    :param branch: The branch being logged.
510
    :param view_revisions: The revisions being viewed.
511
    :param generate_delta: Whether to generate a delta for each revision.
512
    :param search: A user text search string.
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
513
    :param file_ids: If non empty, only revisions matching one or more of
514
      the file-ids are to be kept.
515
    :param direction: the direction in which view_revisions is sorted
3642.1.7 by Robert Collins
Review feedback.
516
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
517
        delta).
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
518
    """
3642.1.5 by Robert Collins
Separate out batching of revisions.
519
    # Convert view_revisions into (view, None, None) groups to fit with
520
    # the standard interface here.
521
    if type(view_revisions) == list:
3642.1.7 by Robert Collins
Review feedback.
522
        # A single batch conversion is faster than many incremental ones.
523
        # As we have all the data, do a batch conversion.
3642.1.5 by Robert Collins
Separate out batching of revisions.
524
        nones = [None] * len(view_revisions)
525
        log_rev_iterator = iter([zip(view_revisions, nones, nones)])
526
    else:
527
        def _convert():
528
            for view in view_revisions:
529
                yield (view, None, None)
530
        log_rev_iterator = iter([_convert()])
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
531
    for adapter in log_adapters:
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
532
        # It would be nicer if log adapter were first class objects
533
        # with custom parameters. This will do for now. IGC 20090127
534
        if adapter == _make_delta_filter:
535
            log_rev_iterator = adapter(branch, generate_delta,
536
                search, log_rev_iterator, file_ids, direction)
537
        else:
538
            log_rev_iterator = adapter(branch, generate_delta,
539
                search, log_rev_iterator)
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
540
    return log_rev_iterator
541
542
3642.1.7 by Robert Collins
Review feedback.
543
def _make_search_filter(branch, generate_delta, search, log_rev_iterator):
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
544
    """Create a filtered iterator of log_rev_iterator matching on a regex.
545
546
    :param branch: The branch being logged.
547
    :param generate_delta: Whether to generate a delta for each revision.
548
    :param search: A user text search string.
549
    :param log_rev_iterator: An input iterator containing all revisions that
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
550
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
551
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
552
        delta).
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
553
    """
554
    if search is None:
555
        return log_rev_iterator
556
    # Compile the search now to get early errors.
557
    searchRE = re.compile(search, re.IGNORECASE)
558
    return _filter_message_re(searchRE, log_rev_iterator)
559
560
561
def _filter_message_re(searchRE, log_rev_iterator):
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
562
    for revs in log_rev_iterator:
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
563
        new_revs = []
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
564
        for (rev_id, revno, merge_depth), rev, delta in revs:
565
            if searchRE.search(rev.message):
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
566
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
567
        yield new_revs
568
569
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
570
def _make_delta_filter(branch, generate_delta, search, log_rev_iterator,
571
    fileids=None, direction='reverse'):
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
572
    """Add revision deltas to a log iterator if needed.
573
574
    :param branch: The branch being logged.
575
    :param generate_delta: Whether to generate a delta for each revision.
576
    :param search: A user text search string.
577
    :param log_rev_iterator: An input iterator containing all revisions that
578
        could be displayed, in lists.
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
579
    :param file_ids: If non empty, only revisions matching one or more of
580
      the file-ids are to be kept.
581
    :param direction: the direction in which view_revisions is sorted
3642.1.7 by Robert Collins
Review feedback.
582
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
583
        delta).
584
    """
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
585
    if not generate_delta and not fileids:
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
586
        return log_rev_iterator
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
587
    return _generate_deltas(branch.repository, log_rev_iterator,
588
        generate_delta, fileids, direction)
589
590
591
def _generate_deltas(repository, log_rev_iterator, always_delta, fileids,
592
    direction):
3642.1.7 by Robert Collins
Review feedback.
593
    """Create deltas for each batch of revisions in log_rev_iterator."""
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
594
    check_fileids = fileids is not None and len(fileids) > 0
595
    if check_fileids:
596
        fileid_set = set(fileids)
597
        if direction == 'reverse':
598
            stop_on = 'add'
599
        else:
600
            stop_on = 'remove'
601
    else:
602
        fileid_set = None
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
603
    for revs in log_rev_iterator:
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
604
        # If we were matching against fileids and we've run out,
605
        # don't create deltas any longer
606
        if check_fileids and not fileid_set:
607
            yield revs
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
608
        revisions = [rev[1] for rev in revs]
609
        deltas = repository.get_deltas_for_revisions(revisions)
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
610
        new_revs = []
611
        for rev, delta in izip(revs, deltas):
612
            if check_fileids:
613
                if not _delta_matches_fileids(delta, fileid_set, stop_on):
614
                    continue
615
                elif not always_delta:
616
                    # Delta was created just for matching - ditch it
617
                    delta = None
618
            new_revs.append((rev[0], rev[1], delta))
619
        yield new_revs
620
621
622
def _delta_matches_fileids(delta, fileids, stop_on='add'):
623
    """Check is a delta matches one of more file-ids.
624
    
625
    :param fileids: a set of fileids to match against.
626
    :param stop_on: either 'add' or 'remove' - take file-ids out of the
627
      fileids set once their add or remove entry is detected respectively
628
    """
629
    if not fileids:
630
        return False
631
    result = False
632
    for item in delta.added:
633
        if item[1] in fileids:
634
            if stop_on == 'add':
635
                fileids.remove(item[1])
636
            result = True
637
    for item in delta.removed:
638
        if item[1] in fileids:
639
            if stop_on == 'delete':
640
                fileids.remove(item[1])
641
            result = True
642
    if result:
643
        return True
644
    for l in (delta.modified, delta.renamed, delta.kind_changed):
645
        for item in l:
646
            if item[1] in fileids:
647
                return True
648
    return False
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
649
650
3642.1.7 by Robert Collins
Review feedback.
651
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
3642.1.4 by Robert Collins
Factor out revision object extraction from revision batching.
652
    """Extract revision objects from the repository
653
654
    :param branch: The branch being logged.
655
    :param generate_delta: Whether to generate a delta for each revision.
656
    :param search: A user text search string.
657
    :param log_rev_iterator: An input iterator containing all revisions that
658
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
659
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
3642.1.4 by Robert Collins
Factor out revision object extraction from revision batching.
660
        delta).
661
    """
3642.1.5 by Robert Collins
Separate out batching of revisions.
662
    repository = branch.repository
3642.1.4 by Robert Collins
Factor out revision object extraction from revision batching.
663
    for revs in log_rev_iterator:
664
        # r = revision_id, n = revno, d = merge depth
665
        revision_ids = [view[0] for view, _, _ in revs]
666
        revisions = repository.get_revisions(revision_ids)
667
        revs = [(rev[0], revision, rev[2]) for rev, revision in
668
            izip(revs, revisions)]
669
        yield revs
670
671
3642.1.7 by Robert Collins
Review feedback.
672
def _make_batch_filter(branch, generate_delta, search, log_rev_iterator):
3642.1.5 by Robert Collins
Separate out batching of revisions.
673
    """Group up a single large batch into smaller ones.
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
674
675
    :param branch: The branch being logged.
676
    :param generate_delta: Whether to generate a delta for each revision.
677
    :param search: A user text search string.
3642.1.5 by Robert Collins
Separate out batching of revisions.
678
    :param log_rev_iterator: An input iterator containing all revisions that
679
        could be displayed, in lists.
3874.2.4 by Vincent Ladeuil
Fix too long lines.
680
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
681
        delta).
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
682
    """
683
    repository = branch.repository
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
684
    num = 9
3642.1.5 by Robert Collins
Separate out batching of revisions.
685
    for batch in log_rev_iterator:
686
        batch = iter(batch)
687
        while True:
688
            step = [detail for _, detail in zip(range(num), batch)]
689
            if len(step) == 0:
690
                break
691
            yield step
692
            num = min(int(num * 1.5), 200)
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
693
694
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
695
def _get_revision_limits(branch, start_revision, end_revision):
696
    """Get and check revision limits.
697
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
698
    :param  branch: The branch containing the revisions. 
699
700
    :param  start_revision: The first revision to be logged.
701
            For backwards compatibility this may be a mainline integer revno,
702
            but for merge revision support a RevisionInfo is expected.
703
704
    :param  end_revision: The last revision to be logged.
705
            For backwards compatibility this may be a mainline integer revno,
706
            but for merge revision support a RevisionInfo is expected.
707
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
708
    :return: (start_rev_id, end_rev_id) tuple.
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
709
    """
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
710
    branch_revno, branch_rev_id = branch.last_revision_info()
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
711
    start_rev_id = None
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
712
    if start_revision is None:
713
        start_revno = 1
714
    else:
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
715
        if isinstance(start_revision, revisionspec.RevisionInfo):
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
716
            start_rev_id = start_revision.rev_id
717
            start_revno = start_revision.revno or 1
718
        else:
719
            branch.check_real_revno(start_revision)
720
            start_revno = start_revision
3936.3.25 by Ian Clatworthy
fix bug when start/end revision are integers
721
            start_rev_id = branch.get_rev_id(start_revno)
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
722
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
723
    end_rev_id = None
724
    if end_revision is None:
3449.2.5 by John Arbash Meinel
Stop referencing the variable I removed.
725
        end_revno = branch_revno
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
726
    else:
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
727
        if isinstance(end_revision, revisionspec.RevisionInfo):
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
728
            end_rev_id = end_revision.rev_id
3449.2.5 by John Arbash Meinel
Stop referencing the variable I removed.
729
            end_revno = end_revision.revno or branch_revno
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
730
        else:
731
            branch.check_real_revno(end_revision)
732
            end_revno = end_revision
3936.3.25 by Ian Clatworthy
fix bug when start/end revision are integers
733
            end_rev_id = branch.get_rev_id(end_revno)
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
734
3936.3.4 by Ian Clatworthy
fix empty_branch log
735
    if branch_revno != 0:
736
        if (start_rev_id == _mod_revision.NULL_REVISION
737
            or end_rev_id == _mod_revision.NULL_REVISION):
738
            raise errors.BzrCommandError('Logging revision 0 is invalid.')
739
        if start_revno > end_revno:
740
            raise errors.BzrCommandError("Start revision must be older than "
741
                                         "the end revision.")
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
742
    return (start_rev_id, end_rev_id)
743
744
745
def _get_mainline_revs(branch, start_revision, end_revision):
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
746
    """Get the mainline revisions from the branch.
747
    
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
748
    Generates the list of mainline revisions for the branch.
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
749
    
750
    :param  branch: The branch containing the revisions. 
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
751
752
    :param  start_revision: The first revision to be logged.
753
            For backwards compatibility this may be a mainline integer revno,
754
            but for merge revision support a RevisionInfo is expected.
755
756
    :param  end_revision: The last revision to be logged.
757
            For backwards compatibility this may be a mainline integer revno,
758
            but for merge revision support a RevisionInfo is expected.
759
760
    :return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
761
    """
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
762
    branch_revno, branch_last_revision = branch.last_revision_info()
763
    if branch_revno == 0:
764
        return None, None, None, None
765
766
    # For mainline generation, map start_revision and end_revision to 
767
    # mainline revnos. If the revision is not on the mainline choose the 
768
    # appropriate extreme of the mainline instead - the extra will be 
769
    # filtered later.
770
    # Also map the revisions to rev_ids, to be used in the later filtering
771
    # stage.
772
    start_rev_id = None
773
    if start_revision is None:
774
        start_revno = 1
775
    else:
776
        if isinstance(start_revision, revisionspec.RevisionInfo):
777
            start_rev_id = start_revision.rev_id
778
            start_revno = start_revision.revno or 1
779
        else:
780
            branch.check_real_revno(start_revision)
781
            start_revno = start_revision
782
783
    end_rev_id = None
784
    if end_revision is None:
785
        end_revno = branch_revno
786
    else:
787
        if isinstance(end_revision, revisionspec.RevisionInfo):
788
            end_rev_id = end_revision.rev_id
789
            end_revno = end_revision.revno or branch_revno
790
        else:
791
            branch.check_real_revno(end_revision)
792
            end_revno = end_revision
793
794
    if ((start_rev_id == _mod_revision.NULL_REVISION)
795
        or (end_rev_id == _mod_revision.NULL_REVISION)):
796
        raise errors.BzrCommandError('Logging revision 0 is invalid.')
797
    if start_revno > end_revno:
798
        raise errors.BzrCommandError("Start revision must be older than "
799
                                     "the end revision.")
800
801
    if end_revno < start_revno:
802
        return None, None, None, None
803
    cur_revno = branch_revno
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
804
    rev_nos = {}
805
    mainline_revs = []
806
    for revision_id in branch.repository.iter_reverse_revision_history(
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
807
                        branch_last_revision):
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
808
        if cur_revno < start_revno:
3449.2.2 by John Arbash Meinel
Fix bug #172649. Cleanup, and handle the case where we are logging to the first revision.
809
            # We have gone far enough, but we always add 1 more revision
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
810
            rev_nos[revision_id] = cur_revno
811
            mainline_revs.append(revision_id)
812
            break
813
        if cur_revno <= end_revno:
814
            rev_nos[revision_id] = cur_revno
815
            mainline_revs.append(revision_id)
816
        cur_revno -= 1
3449.2.2 by John Arbash Meinel
Fix bug #172649. Cleanup, and handle the case where we are logging to the first revision.
817
    else:
818
        # We walked off the edge of all revisions, so we add a 'None' marker
819
        mainline_revs.append(None)
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
820
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
821
    mainline_revs.reverse()
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
822
823
    # override the mainline to look like the revision history.
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
824
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
825
826
827
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
828
    """Filter view_revisions based on revision ranges.
829
830
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth) 
831
            tuples to be filtered.
832
833
    :param start_rev_id: If not NONE specifies the first revision to be logged.
834
            If NONE then all revisions up to the end_rev_id are logged.
835
836
    :param end_rev_id: If not NONE specifies the last revision to be logged.
837
            If NONE then all revisions up to the end of the log are logged.
838
839
    :return: The filtered view_revisions.
840
    """
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
841
    # This method is no longer called by the main code path.
842
    # It may be removed soon. IGC 20090127
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
843
    if start_rev_id or end_rev_id:
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
844
        revision_ids = [r for r, n, d in view_revisions]
845
        if start_rev_id:
846
            start_index = revision_ids.index(start_rev_id)
847
        else:
848
            start_index = 0
849
        if start_rev_id == end_rev_id:
850
            end_index = start_index
851
        else:
852
            if end_rev_id:
853
                end_index = revision_ids.index(end_rev_id)
854
            else:
855
                end_index = len(view_revisions) - 1
856
        # To include the revisions merged into the last revision, 
857
        # extend end_rev_id down to, but not including, the next rev
858
        # with the same or lesser merge_depth
859
        end_merge_depth = view_revisions[end_index][2]
860
        try:
861
            for index in xrange(end_index+1, len(view_revisions)+1):
862
                if view_revisions[index][2] <= end_merge_depth:
863
                    end_index = index - 1
864
                    break
865
        except IndexError:
866
            # if the search falls off the end then log to the end as well
867
            end_index = len(view_revisions) - 1
868
        view_revisions = view_revisions[start_index:end_index+1]
869
    return view_revisions
870
871
3940.1.3 by Ian Clatworthy
fix code
872
def _filter_revisions_touching_file_id(branch, file_id, view_revisions,
873
    include_merges=True):
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
874
    r"""Return the list of revision ids which touch a given file id.
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
875
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
876
    The function filters view_revisions and returns a subset.
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
877
    This includes the revisions which directly change the file id,
878
    and the revisions which merge these changes. So if the
879
    revision graph is::
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
880
        A-.
881
        |\ \
882
        B C E
883
        |/ /
884
        D |
885
        |\|
886
        | F
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
887
        |/
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
888
        G
889
890
    And 'C' changes a file, then both C and D will be returned. F will not be
891
    returned even though it brings the changes to C into the branch starting
892
    with E. (Note that if we were using F as the tip instead of G, then we
893
    would see C, D, F.)
894
895
    This will also be restricted based on a subset of the mainline.
896
897
    :param branch: The branch where we can get text revision information.
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
898
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
899
    :param file_id: Filter out revisions that do not touch file_id.
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
900
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
901
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
902
        tuples. This is the list of revisions which will be filtered. It is
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
903
        assumed that view_revisions is in merge_sort order (i.e. newest
904
        revision first ).
905
3940.1.3 by Ian Clatworthy
fix code
906
    :param include_merges: include merge revisions in the result or not
907
2359.1.8 by John Arbash Meinel
doc
908
    :return: A list of (revision_id, dotted_revno, merge_depth) tuples.
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
909
    """
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
910
    # Lookup all possible text keys to determine which ones actually modified
911
    # the file.
912
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
3711.3.16 by John Arbash Meinel
Doc update.
913
    # Looking up keys in batches of 1000 can cut the time in half, as well as
914
    # memory consumption. GraphIndex *does* like to look for a few keys in
915
    # parallel, it just doesn't like looking for *lots* of keys in parallel.
3711.3.19 by John Arbash Meinel
Add a TODO discussing how our index requests should evolve.
916
    # TODO: This code needs to be re-evaluated periodically as we tune the
917
    #       indexing layer. We might consider passing in hints as to the known
918
    #       access pattern (sparse/clustered, high success rate/low success
919
    #       rate). This particular access is clustered with a low success rate.
3711.3.15 by John Arbash Meinel
Work around GraphIndex inefficiencies by requesting keys 1000 at a time.
920
    get_parent_map = branch.repository.texts.get_parent_map
921
    modified_text_revisions = set()
922
    chunk_size = 1000
923
    for start in xrange(0, len(text_keys), chunk_size):
924
        next_keys = text_keys[start:start + chunk_size]
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
925
        # Only keep the revision_id portion of the key
3711.3.15 by John Arbash Meinel
Work around GraphIndex inefficiencies by requesting keys 1000 at a time.
926
        modified_text_revisions.update(
927
            [k[1] for k in get_parent_map(next_keys)])
928
    del text_keys, next_keys
3711.3.14 by John Arbash Meinel
Change the per-file log algorithm dramatically.
929
930
    result = []
931
    # Track what revisions will merge the current revision, replace entries
932
    # with 'None' when they have been added to result
933
    current_merge_stack = [None]
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
934
    for info in view_revisions:
3711.3.14 by John Arbash Meinel
Change the per-file log algorithm dramatically.
935
        rev_id, revno, depth = info
936
        if depth == len(current_merge_stack):
937
            current_merge_stack.append(info)
938
        else:
939
            del current_merge_stack[depth + 1:]
940
            current_merge_stack[-1] = info
941
942
        if rev_id in modified_text_revisions:
943
            # This needs to be logged, along with the extra revisions
944
            for idx in xrange(len(current_merge_stack)):
945
                node = current_merge_stack[idx]
946
                if node is not None:
3940.1.3 by Ian Clatworthy
fix code
947
                    if include_merges or node[2] == 0:
948
                        result.append(node)
949
                        current_merge_stack[idx] = None
3711.3.4 by John Arbash Meinel
Significantly faster, but consuming more memory.
950
    return result
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
951
952
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
953
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
1756.2.22 by Aaron Bentley
Apply review comments
954
                       include_merges=True):
1756.2.18 by Aaron Bentley
Factor out the revision list generation
955
    """Produce an iterator of revisions to show
956
    :return: an iterator of (revision_id, revno, merge_depth)
957
    (if there is no revno for a revision, None is supplied)
958
    """
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
959
    # This method is no longer called by the main code path.
960
    # It is retained for API compatibility and may be deprecated
961
    # soon. IGC 20090127
3943.1.1 by Ian Clatworthy
apply jam's log --short fix (Ian Clatworthy)
962
    if not include_merges:
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
963
        revision_ids = mainline_revs[1:]
964
        if direction == 'reverse':
965
            revision_ids.reverse()
966
        for revision_id in revision_ids:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
967
            yield revision_id, str(rev_nos[revision_id]), 0
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
968
        return
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
969
    graph = branch.repository.get_graph()
970
    # This asks for all mainline revisions, which means we only have to spider
971
    # sideways, rather than depth history. That said, its still size-of-history
972
    # and should be addressed.
3373.5.4 by John Arbash Meinel
Track down another bogus location. Only triggered with --long
973
    # mainline_revisions always includes an extra revision at the beginning, so
974
    # don't request it.
3287.6.8 by Robert Collins
Reduce code duplication as per review.
975
    parent_map = dict(((key, value) for key, value in
3373.5.4 by John Arbash Meinel
Track down another bogus location. Only triggered with --long
976
        graph.iter_ancestry(mainline_revs[1:]) if value is not None))
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
977
    # filter out ghosts; merge_sort errors on ghosts.
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
978
    rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
979
    merge_sorted_revisions = tsort.merge_sort(
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
980
        rev_graph,
1756.2.18 by Aaron Bentley
Factor out the revision list generation
981
        mainline_revs[-1],
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
982
        mainline_revs,
983
        generate_revno=True)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
984
985
    if direction == 'forward':
986
        # forward means oldest first.
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
987
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
988
    elif direction != 'reverse':
989
        raise ValueError('invalid direction %r' % direction)
990
3874.2.4 by Vincent Ladeuil
Fix too long lines.
991
    for (sequence, rev_id, merge_depth, revno, end_of_merge
992
         ) in merge_sorted_revisions:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
993
        yield rev_id, '.'.join(map(str, revno)), merge_depth
1756.2.18 by Aaron Bentley
Factor out the revision list generation
994
995
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
996
def reverse_by_depth(merge_sorted_revisions, _depth=0):
997
    """Reverse revisions by depth.
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
998
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
999
    Revisions with a different depth are sorted as a group with the previous
1000
    revision of that depth.  There may be no topological justification for this,
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
1001
    but it looks much nicer.
1002
    """
3842.2.6 by Vincent Ladeuil
Fix typo.
1003
    # Add a fake revision at start so that we can always attach sub revisions
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1004
    merge_sorted_revisions = [(None, None, _depth)] + merge_sorted_revisions
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
1005
    zd_revisions = []
1006
    for val in merge_sorted_revisions:
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
1007
        if val[2] == _depth:
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1008
            # Each revision at the current depth becomes a chunk grouping all
1009
            # higher depth revisions.
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
1010
            zd_revisions.append([val])
1011
        else:
1012
            zd_revisions[-1].append(val)
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
1013
    for revisions in zd_revisions:
1014
        if len(revisions) > 1:
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1015
            # We have higher depth revisions, let reverse them locally
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
1016
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
1017
    zd_revisions.reverse()
1018
    result = []
1019
    for chunk in zd_revisions:
1020
        result.extend(chunk)
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1021
    if _depth == 0:
1022
        # Top level call, get rid of the fake revisions that have been added
1023
        result = [r for r in result if r[0] is not None and r[1] is not None]
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
1024
    return result
1025
1026
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1027
class LogRevision(object):
1028
    """A revision to be logged (by LogFormatter.log_revision).
1029
1030
    A simple wrapper for the attributes of a revision to be logged.
1031
    The attributes may or may not be populated, as determined by the 
1032
    logging options and the log formatter capabilities.
1033
    """
1034
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
1035
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
1036
                 tags=None):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1037
        self.rev = rev
1038
        self.revno = revno
1039
        self.merge_depth = merge_depth
1040
        self.delta = delta
1041
        self.tags = tags
1042
1043
794 by Martin Pool
- Merge John's nice short-log format.
1044
class LogFormatter(object):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1045
    """Abstract class to display log messages.
1046
1047
    At a minimum, a derived class must implement the log_revision method.
1048
1049
    If the LogFormatter needs to be informed of the beginning or end of
1050
    a log it should implement the begin_log and/or end_log hook methods.
1051
1052
    A LogFormatter should define the following supports_XXX flags 
1053
    to indicate which LogRevision attributes it supports:
1054
1055
    - supports_delta must be True if this log formatter supports delta.
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1056
        Otherwise the delta attribute may not be populated.  The 'delta_format'
1057
        attribute describes whether the 'short_status' format (1) or the long
3936.3.2 by Ian Clatworthy
minor cleanups
1058
        one (2) should be used.
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1059
 
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1060
    - supports_merge_revisions must be True if this log formatter supports 
3936.3.2 by Ian Clatworthy
minor cleanups
1061
        merge revisions.  If not, and if supports_single_merge_revision is
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
1062
        also not True, then only mainline revisions will be passed to the 
1063
        formatter.
1064
    - supports_single_merge_revision must be True if this log formatter
1065
        supports logging only a single merge revision.  This flag is
1066
        only relevant if supports_merge_revisions is not True.
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1067
    - supports_tags must be True if this log formatter supports tags.
1068
        Otherwise the tags attribute may not be populated.
3144.7.1 by Guillermo Gonzalez
* added show_properties to LonLogFormat and the hooks to register custom functions
1069
1070
    Plugins can register functions to show custom revision properties using
3144.7.13 by Guillermo Gonzalez
* fixed typo LogFormatter.show_properties in docstring
1071
    the properties_handler_registry. The registered function
3144.7.1 by Guillermo Gonzalez
* added show_properties to LonLogFormat and the hooks to register custom functions
1072
    must respect the following interface description:
3144.7.2 by Guillermo Gonzalez
* cleanup a bit the interface
1073
        def my_show_properties(properties_dict):
1074
            # code that returns a dict {'name':'value'} of the properties 
1075
            # to be shown
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1076
    """
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1077
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1078
    def __init__(self, to_file, show_ids=False, show_timezone='original',
1079
                 delta_format=None):
794 by Martin Pool
- Merge John's nice short-log format.
1080
        self.to_file = to_file
1081
        self.show_ids = show_ids
1082
        self.show_timezone = show_timezone
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1083
        if delta_format is None:
1084
            # Ensures backward compatibility
1085
            delta_format = 2 # long format
1086
        self.delta_format = delta_format
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1087
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1088
# TODO: uncomment this block after show() has been removed.
1089
# Until then defining log_revision would prevent _show_log calling show() 
1090
# in legacy formatters.
1091
#    def log_revision(self, revision):
1092
#        """Log a revision.
1093
#
1094
#        :param  revision:   The LogRevision to be logged.
1095
#        """
1096
#        raise NotImplementedError('not implemented in abstract base')
1097
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
1098
    def short_committer(self, rev):
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1099
        name, address = config.parse_username(rev.committer)
1100
        if name:
3063.3.1 by Lukáš Lalinský
Fall back to showing e-mail in ``log --short/--line`` if the committer/author has only e-mail.
1101
            return name
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1102
        return address
2388.1.11 by Alexander Belchenko
changes after John's review
1103
2671.5.4 by Lukáš Lalinsky
Replace the committer with the author in log, the committer is displayed only in the long format and only if it's different from the author.
1104
    def short_author(self, rev):
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1105
        name, address = config.parse_username(rev.get_apparent_author())
1106
        if name:
3063.3.1 by Lukáš Lalinský
Fall back to showing e-mail in ``log --short/--line`` if the committer/author has only e-mail.
1107
            return name
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1108
        return address
2671.5.4 by Lukáš Lalinsky
Replace the committer with the author in log, the committer is displayed only in the long format and only if it's different from the author.
1109
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
1110
    def show_properties(self, revision, indent):
3144.7.8 by Guillermo Gonzalez
* added error handling (and logging) to LogFormatter.show_properties when a handler raise an error
1111
        """Displays the custom properties returned by each registered handler.
1112
        
3144.7.13 by Guillermo Gonzalez
* fixed typo LogFormatter.show_properties in docstring
1113
        If a registered handler raises an error it is propagated.
3144.7.5 by Guillermo Gonzalez
* some improvements to the doctstring in show_properties method and in LogFormatter
1114
        """
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
1115
        for key, handler in properties_handler_registry.iteritems():
1116
            for key, value in handler(revision).items():
1117
                self.to_file.write(indent + key + ': ' + value + '\n')
3144.7.8 by Guillermo Gonzalez
* added error handling (and logging) to LogFormatter.show_properties when a handler raise an error
1118
2388.1.11 by Alexander Belchenko
changes after John's review
1119
794 by Martin Pool
- Merge John's nice short-log format.
1120
class LongLogFormatter(LogFormatter):
2388.1.11 by Alexander Belchenko
changes after John's review
1121
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1122
    supports_merge_revisions = True
1123
    supports_delta = True
1124
    supports_tags = True
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
1125
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1126
    def log_revision(self, revision):
1127
        """Log a revision, either merged or not."""
2671.2.5 by Lukáš Lalinský
Fixes for comments from the mailing list.
1128
        indent = '    ' * revision.merge_depth
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
1129
        to_file = self.to_file
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1130
        to_file.write(indent + '-' * 60 + '\n')
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1131
        if revision.revno is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1132
            to_file.write(indent + 'revno: %s\n' % (revision.revno,))
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1133
        if revision.tags:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1134
            to_file.write(indent + 'tags: %s\n' % (', '.join(revision.tags)))
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
1135
        if self.show_ids:
3257.2.1 by Adeodato Simó
Add a space after "revision-id:" in log output.
1136
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1137
            to_file.write('\n')
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1138
            for parent_id in revision.rev.parent_ids:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1139
                to_file.write(indent + 'parent: %s\n' % (parent_id,))
3144.7.11 by Guillermo Gonzalez
* updates LongLogFormatter to pass revision instead of the properties dict to show_properties method
1140
        self.show_properties(revision.rev, indent)
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
1141
2671.5.7 by Lukáš Lalinsky
Rename get_author to get_apparent_author, revert the long log back to displaying the committer.
1142
        author = revision.rev.properties.get('author', None)
1143
        if author is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1144
            to_file.write(indent + 'author: %s\n' % (author,))
1145
        to_file.write(indent + 'committer: %s\n' % (revision.rev.committer,))
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
1146
1147
        branch_nick = revision.rev.properties.get('branch-nick', None)
1148
        if branch_nick is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1149
            to_file.write(indent + 'branch nick: %s\n' % (branch_nick,))
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
1150
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1151
        date_str = format_date(revision.rev.timestamp,
1152
                               revision.rev.timezone or 0,
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
1153
                               self.show_timezone)
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1154
        to_file.write(indent + 'timestamp: %s\n' % (date_str,))
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
1155
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1156
        to_file.write(indent + 'message:\n')
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1157
        if not revision.rev.message:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1158
            to_file.write(indent + '  (no message)\n')
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
1159
        else:
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1160
            message = revision.rev.message.rstrip('\r\n')
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
1161
            for l in message.split('\n'):
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1162
                to_file.write(indent + '  %s\n' % (l,))
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1163
        if revision.delta is not None:
3874.1.7 by Vincent Ladeuil
Restrict '-v' change to log --short only.
1164
            # We don't respect delta_format for compatibility
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1165
            revision.delta.show(to_file, self.show_ids, indent=indent,
3874.1.7 by Vincent Ladeuil
Restrict '-v' change to log --short only.
1166
                                short_status=False)
794 by Martin Pool
- Merge John's nice short-log format.
1167
1168
1169
class ShortLogFormatter(LogFormatter):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1170
1171
    supports_delta = True
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1172
    supports_tags = True
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
1173
    supports_single_merge_revision = True
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1174
1175
    def log_revision(self, revision):
794 by Martin Pool
- Merge John's nice short-log format.
1176
        to_file = self.to_file
2483.2.2 by John Arbash Meinel
Add [merge] after the timestamp for revisions with merges.
1177
        is_merge = ''
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
1178
        if len(revision.rev.parent_ids) > 1:
2483.2.2 by John Arbash Meinel
Add [merge] after the timestamp for revisions with merges.
1179
            is_merge = ' [merge]'
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1180
        tags = ''
1181
        if revision.tags:
3946.3.2 by Ian Clatworthy
add tests & NEWS item
1182
            tags = ' {%s}' % (', '.join(revision.tags))
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1183
1184
        to_file.write("%5s %s\t%s%s%s\n" % (revision.revno,
2671.5.4 by Lukáš Lalinsky
Replace the committer with the author in log, the committer is displayed only in the long format and only if it's different from the author.
1185
                self.short_author(revision.rev),
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
1186
                format_date(revision.rev.timestamp,
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1187
                            revision.rev.timezone or 0,
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
1188
                            self.show_timezone, date_fmt="%Y-%m-%d",
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
1189
                            show_offset=False),
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1190
                tags, is_merge))
794 by Martin Pool
- Merge John's nice short-log format.
1191
        if self.show_ids:
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1192
            to_file.write('      revision-id:%s\n'
1193
                          % (revision.rev.revision_id,))
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1194
        if not revision.rev.message:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1195
            to_file.write('      (no message)\n')
794 by Martin Pool
- Merge John's nice short-log format.
1196
        else:
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1197
            message = revision.rev.message.rstrip('\r\n')
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
1198
            for l in message.split('\n'):
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
1199
                to_file.write('      %s\n' % (l,))
794 by Martin Pool
- Merge John's nice short-log format.
1200
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1201
        if revision.delta is not None:
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1202
            revision.delta.show(to_file, self.show_ids,
1203
                                short_status=self.delta_format==1)
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1204
        to_file.write('\n')
794 by Martin Pool
- Merge John's nice short-log format.
1205
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1206
1185.12.25 by Aaron Bentley
Added one-line log format
1207
class LineLogFormatter(LogFormatter):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1208
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1209
    supports_tags = True
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
1210
    supports_single_merge_revision = True
1211
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1212
    def __init__(self, *args, **kwargs):
1213
        super(LineLogFormatter, self).__init__(*args, **kwargs)
1214
        self._max_chars = terminal_width() - 1
1215
1185.12.25 by Aaron Bentley
Added one-line log format
1216
    def truncate(self, str, max_len):
1217
        if len(str) <= max_len:
1218
            return str
1219
        return str[:max_len-3]+'...'
1220
1221
    def date_string(self, rev):
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1222
        return format_date(rev.timestamp, rev.timezone or 0,
1185.12.25 by Aaron Bentley
Added one-line log format
1223
                           self.show_timezone, date_fmt="%Y-%m-%d",
1224
                           show_offset=False)
1225
1226
    def message(self, rev):
1227
        if not rev.message:
1228
            return '(no message)'
1229
        else:
1230
            return rev.message
1231
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1232
    def log_revision(self, revision):
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1233
        self.to_file.write(self.log_string(revision.revno, revision.rev,
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1234
            self._max_chars, revision.tags))
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1235
        self.to_file.write('\n')
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1236
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1237
    def log_string(self, revno, rev, max_chars, tags=None):
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1238
        """Format log info into one string. Truncate tail of string
3677.1.1 by Vincent Ladeuil
Begin fixing bug #233817.
1239
        :param  revno:      revision number or None.
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1240
                            Revision numbers counts from 1.
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1241
        :param  rev:        revision object
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1242
        :param  max_chars:  maximum length of resulting string
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1243
        :param  tags:       list of tags or None
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1244
        :return:            formatted truncated string
1245
        """
1246
        out = []
1247
        if revno:
1248
            # show revno only when is not None
3946.3.4 by Ian Clatworthy
minor cleanup
1249
            out.append("%s:" % revno)
2671.5.4 by Lukáš Lalinsky
Replace the committer with the author in log, the committer is displayed only in the long format and only if it's different from the author.
1250
        out.append(self.truncate(self.short_author(rev), 20))
1185.12.25 by Aaron Bentley
Added one-line log format
1251
        out.append(self.date_string(rev))
3946.3.3 by Ian Clatworthy
feedback from jelmer re position of tags in --line
1252
        if tags:
1253
            tag_str = '{%s}' % (', '.join(tags))
1254
            out.append(tag_str)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
1255
        out.append(rev.get_summary())
1185.12.25 by Aaron Bentley
Added one-line log format
1256
        return self.truncate(" ".join(out).rstrip('\n'), max_chars)
794 by Martin Pool
- Merge John's nice short-log format.
1257
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1258
1185.12.27 by Aaron Bentley
Use line log for pending merges
1259
def line_log(rev, max_chars):
1260
    lf = LineLogFormatter(None)
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1261
    return lf.log_string(None, rev, max_chars)
1185.12.27 by Aaron Bentley
Use line log for pending merges
1262
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1263
1264
class LogFormatterRegistry(registry.Registry):
1265
    """Registry for log formatters"""
1266
1267
    def make_formatter(self, name, *args, **kwargs):
1268
        """Construct a formatter from arguments.
1269
1270
        :param name: Name of the formatter to construct.  'short', 'long' and
1271
            'line' are built-in.
1272
        """
1273
        return self.get(name)(*args, **kwargs)
1274
1275
    def get_default(self, branch):
1276
        return self.get(branch.get_config().log_format())
1277
1278
1279
log_formatter_registry = LogFormatterRegistry()
1280
1281
1282
log_formatter_registry.register('short', ShortLogFormatter,
1283
                                'Moderately short log format')
1284
log_formatter_registry.register('long', LongLogFormatter,
1285
                                'Detailed log format')
1286
log_formatter_registry.register('line', LineLogFormatter,
1287
                                'Log format with one line per revision')
1288
794 by Martin Pool
- Merge John's nice short-log format.
1289
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
1290
def register_formatter(name, formatter):
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1291
    log_formatter_registry.register(name, formatter)
1292
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
1293
794 by Martin Pool
- Merge John's nice short-log format.
1294
def log_formatter(name, *args, **kwargs):
1393.1.56 by Martin Pool
- doc and small refactoring of log code
1295
    """Construct a formatter from arguments.
1296
1185.12.27 by Aaron Bentley
Use line log for pending merges
1297
    name -- Name of the formatter to construct; currently 'long', 'short' and
1298
        'line' are supported.
1393.1.56 by Martin Pool
- doc and small refactoring of log code
1299
    """
794 by Martin Pool
- Merge John's nice short-log format.
1300
    try:
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1301
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
1553.2.2 by Erik Bågfors
Made "unknown log formatter" error message work
1302
    except KeyError:
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
1303
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1304
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1305
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1306
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1307
    # deprecated; for compatibility
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1308
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
1309
    lf.show(revno, rev, delta)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1310
2490.1.4 by John Arbash Meinel
Update bzrlib.log.show_changed_revisions to use the new api
1311
1551.17.2 by Aaron Bentley
Stop showing deltas in pull -v output
1312
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
1313
                           log_format='long'):
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1314
    """Show the change in revision history comparing the old revision history to the new one.
1315
1316
    :param branch: The branch where the revisions exist
1317
    :param old_rh: The old revision history
1318
    :param new_rh: The new revision history
1319
    :param to_file: A file to write the results to. If None, stdout will be used
1320
    """
1321
    if to_file is None:
2997.1.3 by Alexander Belchenko
file wrapper around stdout should use terminal encoding, not user_encoding.
1322
        to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
1323
            errors='replace')
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1324
    lf = log_formatter(log_format,
1325
                       show_ids=False,
1326
                       to_file=to_file,
1327
                       show_timezone='original')
1328
1329
    # This is the first index which is different between
1330
    # old and new
1331
    base_idx = None
1332
    for i in xrange(max(len(new_rh),
1333
                        len(old_rh))):
1334
        if (len(new_rh) <= i
1335
            or len(old_rh) <= i
1336
            or new_rh[i] != old_rh[i]):
1337
            base_idx = i
1338
            break
1339
1340
    if base_idx is None:
1341
        to_file.write('Nothing seems to have changed\n')
1342
        return
1343
    ## TODO: It might be nice to do something like show_log
1344
    ##       and show the merged entries. But since this is the
1345
    ##       removed revisions, it shouldn't be as important
1346
    if base_idx < len(old_rh):
1347
        to_file.write('*'*60)
1348
        to_file.write('\nRemoved Revisions:\n')
1349
        for i in range(base_idx, len(old_rh)):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1350
            rev = branch.repository.get_revision(old_rh[i])
2490.1.4 by John Arbash Meinel
Update bzrlib.log.show_changed_revisions to use the new api
1351
            lr = LogRevision(rev, i+1, 0, None)
1352
            lf.log_revision(lr)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1353
        to_file.write('*'*60)
1354
        to_file.write('\n\n')
1355
    if base_idx < len(new_rh):
1356
        to_file.write('Added Revisions:\n')
1357
        show_log(branch,
1358
                 lf,
1359
                 None,
1551.17.2 by Aaron Bentley
Stop showing deltas in pull -v output
1360
                 verbose=False,
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1361
                 direction='forward',
1362
                 start_revision=base_idx+1,
1363
                 end_revision=len(new_rh),
1364
                 search=None)
1365
3144.7.4 by Guillermo Gonzalez
* move the function regisstry into a real Registry instead of a list
1366
3848.1.7 by Aaron Bentley
Use repository in get_history_change
1367
def get_history_change(old_revision_id, new_revision_id, repository):
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1368
    """Calculate the uncommon lefthand history between two revisions.
1369
1370
    :param old_revision_id: The original revision id.
1371
    :param new_revision_id: The new revision id.
3848.1.22 by Aaron Bentley
Fix spelling
1372
    :param repository: The repository to use for the calculation.
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1373
1374
    return old_history, new_history
1375
    """
3848.1.6 by Aaron Bentley
Implement get_history_change
1376
    old_history = []
1377
    old_revisions = set()
1378
    new_history = []
1379
    new_revisions = set()
3848.1.7 by Aaron Bentley
Use repository in get_history_change
1380
    new_iter = repository.iter_reverse_revision_history(new_revision_id)
1381
    old_iter = repository.iter_reverse_revision_history(old_revision_id)
3848.1.6 by Aaron Bentley
Implement get_history_change
1382
    stop_revision = None
1383
    do_old = True
1384
    do_new = True
1385
    while do_new or do_old:
1386
        if do_new:
1387
            try:
1388
                new_revision = new_iter.next()
1389
            except StopIteration:
1390
                do_new = False
1391
            else:
1392
                new_history.append(new_revision)
1393
                new_revisions.add(new_revision)
1394
                if new_revision in old_revisions:
1395
                    stop_revision = new_revision
1396
                    break
1397
        if do_old:
1398
            try:
1399
                old_revision = old_iter.next()
1400
            except StopIteration:
1401
                do_old = False
1402
            else:
1403
                old_history.append(old_revision)
1404
                old_revisions.add(old_revision)
1405
                if old_revision in new_revisions:
1406
                    stop_revision = old_revision
1407
                    break
1408
    new_history.reverse()
1409
    old_history.reverse()
1410
    if stop_revision is not None:
1411
        new_history = new_history[new_history.index(stop_revision) + 1:]
1412
        old_history = old_history[old_history.index(stop_revision) + 1:]
1413
    return old_history, new_history
1414
1415
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1416
def show_branch_change(branch, output, old_revno, old_revision_id):
1417
    """Show the changes made to a branch.
1418
1419
    :param branch: The branch to show changes about.
1420
    :param output: A file-like object to write changes to.
1421
    :param old_revno: The revno of the old tip.
1422
    :param old_revision_id: The revision_id of the old tip.
1423
    """
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1424
    new_revno, new_revision_id = branch.last_revision_info()
1425
    old_history, new_history = get_history_change(old_revision_id,
1426
                                                  new_revision_id,
1427
                                                  branch.repository)
1428
    if old_history == [] and new_history == []:
1429
        output.write('Nothing seems to have changed\n')
1430
        return
1431
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1432
    log_format = log_formatter_registry.get_default(branch)
1433
    lf = log_format(show_ids=False, to_file=output, show_timezone='original')
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1434
    if old_history != []:
1435
        output.write('*'*60)
1436
        output.write('\nRemoved Revisions:\n')
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1437
        show_flat_log(branch.repository, old_history, old_revno, lf)
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1438
        output.write('*'*60)
1439
        output.write('\n\n')
1440
    if new_history != []:
3848.1.9 by Aaron Bentley
new/old sections are omitted as appropriate.
1441
        output.write('Added Revisions:\n')
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1442
        start_revno = new_revno - len(new_history) + 1
1443
        show_log(branch, lf, None, verbose=False, direction='forward',
1444
                 start_revision=start_revno,)
1445
1446
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1447
def show_flat_log(repository, history, last_revno, lf):
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1448
    """Show a simple log of the specified history.
1449
1450
    :param repository: The repository to retrieve revisions from.
1451
    :param history: A list of revision_ids indicating the lefthand history.
1452
    :param last_revno: The revno of the last revision_id in the history.
1453
    :param lf: The log formatter to use.
1454
    """
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1455
    start_revno = last_revno - len(history) + 1
1456
    revisions = repository.get_revisions(history)
1457
    for i, rev in enumerate(revisions):
1458
        lr = LogRevision(rev, i + last_revno, 0, None)
1459
        lf.log_revision(lr)
1460
1461
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
1462
properties_handler_registry = registry.Registry()
3830.4.1 by Jelmer Vernooij
Add base classes for foreign branches.
1463
properties_handler_registry.register_lazy("foreign",
1464
                                          "bzrlib.foreign",
1465
                                          "show_foreign_properties")
1466
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1467
1468
# adapters which revision ids to log are filtered. When log is called, the
1469
# log_rev_iterator is adapted through each of these factory methods.
1470
# Plugins are welcome to mutate this list in any way they like - as long
1471
# as the overall behaviour is preserved. At this point there is no extensible
1472
# mechanism for getting parameters to each factory method, and until there is
1473
# this won't be considered a stable api.
1474
log_adapters = [
1475
    # core log logic
3642.1.7 by Robert Collins
Review feedback.
1476
    _make_batch_filter,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1477
    # read revision objects
3642.1.7 by Robert Collins
Review feedback.
1478
    _make_revision_objects,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1479
    # filter on log messages
3642.1.7 by Robert Collins
Review feedback.
1480
    _make_search_filter,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1481
    # generate deltas for things we will show
3642.1.7 by Robert Collins
Review feedback.
1482
    _make_delta_filter
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1483
    ]