~bzr-pqm/bzr/bzr.dev

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