/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
369 by Martin Pool
- Split out log printing into new show_log function
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
369 by Martin Pool
- Split out log printing into new show_log function
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
369 by Martin Pool
- Split out log printing into new show_log function
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
375 by Martin Pool
- New command touching-revisions and function to trace
17
18
527 by Martin Pool
- refactor log command
19
"""Code to show logs of changes.
20
21
Various flavors of log can be produced:
22
23
* for one file, or the whole tree, and (not done yet) for
24
  files in a given directory
25
26
* in "verbose" mode with a description of what changed from one
27
  version to the next
28
29
* with file-ids and revision-ids shown
30
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
31
Logs are actually written out through an abstract LogFormatter
32
interface, which allows for different preferred formats.  Plugins can
33
register formats too.
34
35
Logs can be produced in either forward (oldest->newest) or reverse
36
(newest->oldest) order.
37
38
Logs can be filtered to show only revisions matching a particular
39
search string, or within a particular range of revisions.  The range
40
can be given as date/times, which are reduced to revisions before
41
calling in here.
42
43
In verbose mode we show a summary of what changed in each particular
44
revision.  Note that this is the delta for changes in that revision
2466.12.2 by Kent Gibson
shift log output with only merge revisions to the left margin
45
relative to its left-most parent, not the delta relative to the last
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
46
logged revision.  So for example if you ask for a verbose log of
47
changes touching hello.c you will get a list of those revisions also
48
listing other things that were changed in the same revision, but not
49
all the changes since the previous revision that touched hello.c.
527 by Martin Pool
- refactor log command
50
"""
51
2997.1.2 by Kent Gibson
Move all imports to top of log.py
52
import codecs
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 (
55
    izip,
56
    )
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
57
import re
2997.1.2 by Kent Gibson
Move all imports to top of log.py
58
import sys
59
from warnings import (
60
    warn,
61
    )
1185.33.41 by Martin Pool
Fix regression of 'bzr log -v' - it wasn't showing changed files at all. (#4676)
62
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
63
from bzrlib.lazy_import import lazy_import
64
lazy_import(globals(), """
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
65
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
66
from bzrlib import (
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
67
    config,
3943.5.1 by Ian Clatworthy
first cut at log --show-diff
68
    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.
69
    errors,
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
70
    repository as _mod_repository,
71
    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.
72
    revisionspec,
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
73
    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.
74
    tsort,
75
    )
76
""")
77
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
78
from bzrlib import (
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
79
    registry,
2997.1.2 by Kent Gibson
Move all imports to top of log.py
80
    )
81
from bzrlib.osutils import (
82
    format_date,
2997.1.3 by Alexander Belchenko
file wrapper around stdout should use terminal encoding, not user_encoding.
83
    get_terminal_encoding,
2997.1.2 by Kent Gibson
Move all imports to top of log.py
84
    terminal_width,
85
    )
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
86
375 by Martin Pool
- New command touching-revisions and function to trace
87
88
def find_touching_revisions(branch, file_id):
89
    """Yield a description of revisions which affect the file_id.
90
91
    Each returned element is (revno, revision_id, description)
92
93
    This is the list of revisions where the file is either added,
94
    modified, renamed or deleted.
95
96
    TODO: Perhaps some way to limit this to only particular revisions,
522 by Martin Pool
todo
97
    or to traverse a non-mainline set of revisions?
375 by Martin Pool
- New command touching-revisions and function to trace
98
    """
99
    last_ie = None
100
    last_path = None
101
    revno = 1
102
    for revision_id in branch.revision_history():
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
103
        this_inv = branch.repository.get_revision_inventory(revision_id)
375 by Martin Pool
- New command touching-revisions and function to trace
104
        if file_id in this_inv:
105
            this_ie = this_inv[file_id]
106
            this_path = this_inv.id2path(file_id)
107
        else:
108
            this_ie = this_path = None
109
110
        # now we know how it was last time, and how it is in this revision.
111
        # are those two states effectively the same or not?
112
113
        if not this_ie and not last_ie:
114
            # not present in either
115
            pass
116
        elif this_ie and not last_ie:
117
            yield revno, revision_id, "added " + this_path
118
        elif not this_ie and last_ie:
119
            # deleted here
120
            yield revno, revision_id, "deleted " + last_path
121
        elif this_path != last_path:
122
            yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
123
        elif (this_ie.text_size != last_ie.text_size
124
              or this_ie.text_sha1 != last_ie.text_sha1):
125
            yield revno, revision_id, "modified " + this_path
126
127
        last_ie = this_ie
128
        last_path = this_path
129
        revno += 1
130
131
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
132
def _enumerate_history(branch):
133
    rh = []
134
    revno = 1
135
    for rev_id in branch.revision_history():
136
        rh.append((revno, rev_id))
137
        revno += 1
138
    return rh
139
140
378 by Martin Pool
- New usage bzr log FILENAME
141
def show_log(branch,
794 by Martin Pool
- Merge John's nice short-log format.
142
             lf,
527 by Martin Pool
- refactor log command
143
             specific_fileid=None,
378 by Martin Pool
- New usage bzr log FILENAME
144
             verbose=False,
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
145
             direction='reverse',
146
             start_revision=None,
900 by Martin Pool
- patch from john to search for matching commits
147
             end_revision=None,
2466.9.1 by Kent Gibson
add bzr log --limit
148
             search=None,
3943.5.1 by Ian Clatworthy
first cut at log --show-diff
149
             limit=None,
150
             show_diff=False):
369 by Martin Pool
- Split out log printing into new show_log function
151
    """Write out human-readable log of commits to this branch.
152
3874.2.2 by Vincent Ladeuil
Cleanup show_log doc string.
153
    :param lf: The LogFormatter object showing the output.
154
155
    :param specific_fileid: If not None, list only the commits affecting the
156
        specified file, rather than all commits.
157
158
    :param verbose: If True show added/changed/deleted/renamed files.
159
160
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
161
        earliest to latest.
162
163
    :param start_revision: If not None, only show revisions >= start_revision
164
165
    :param end_revision: If not None, only show revisions <= end_revision
166
167
    :param search: If not None, only show revisions with matching commit
168
        messages
169
170
    :param limit: If set, shows only 'limit' revisions, all revisions are shown
171
        if None or 0.
3943.5.1 by Ian Clatworthy
first cut at log --show-diff
172
173
    :param show_diff: If True, output a diff after each revision.
369 by Martin Pool
- Split out log printing into new show_log function
174
    """
1417.1.7 by Robert Collins
teach log it needs a read lock
175
    branch.lock_read()
176
    try:
2466.8.2 by Kent Gibson
Move begin/end calls from _show_log to show_log. Fix long line.
177
        if getattr(lf, 'begin_log', None):
178
            lf.begin_log()
179
1756.1.6 by Aaron Bentley
Revert locking fix
180
        _show_log(branch, lf, specific_fileid, verbose, direction,
3943.5.1 by Ian Clatworthy
first cut at log --show-diff
181
                  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.
182
183
        if getattr(lf, 'end_log', None):
184
            lf.end_log()
1417.1.7 by Robert Collins
teach log it needs a read lock
185
    finally:
186
        branch.unlock()
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
187
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
188
1417.1.7 by Robert Collins
teach log it needs a read lock
189
def _show_log(branch,
190
             lf,
191
             specific_fileid=None,
192
             verbose=False,
193
             direction='reverse',
194
             start_revision=None,
195
             end_revision=None,
2466.9.1 by Kent Gibson
add bzr log --limit
196
             search=None,
3943.5.1 by Ian Clatworthy
first cut at log --show-diff
197
             limit=None,
198
             show_diff=False):
1417.1.7 by Robert Collins
teach log it needs a read lock
199
    """Worker function for show_log - see show_log."""
794 by Martin Pool
- Merge John's nice short-log format.
200
    if not isinstance(lf, LogFormatter):
201
        warn("not a LogFormatter instance: %r" % lf)
533 by Martin Pool
- fix up asking for the log for the root of a remote branch
202
203
    if specific_fileid:
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
204
        trace.mutter('get log for file_id %r', specific_fileid)
3947.1.10 by Ian Clatworthy
review feedback from vila
205
    levels_to_display = lf.get_levels()
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
206
    generate_merge_revisions = levels_to_display != 1
207
    allow_single_merge_revision = True
208
    if not getattr(lf, 'supports_merge_revisions', False):
209
        allow_single_merge_revision = getattr(lf,
210
            'supports_single_merge_revision', False)
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
211
    view_revisions = calculate_view_revisions(branch, start_revision,
212
                                              end_revision, direction,
213
                                              specific_fileid,
214
                                              generate_merge_revisions,
215
                                              allow_single_merge_revision)
216
    rev_tag_dict = {}
217
    generate_tags = getattr(lf, 'supports_tags', False)
218
    if generate_tags:
219
        if branch.supports_tags():
220
            rev_tag_dict = branch.tags.get_reverse_tag_dict()
221
222
    generate_delta = verbose and getattr(lf, 'supports_delta', False)
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
223
    generate_diff = show_diff and getattr(lf, 'supports_diff', False)
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
224
225
    # now we just print all the revisions
3943.5.1 by Ian Clatworthy
first cut at log --show-diff
226
    repo = branch.repository
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
227
    log_count = 0
3642.1.5 by Robert Collins
Separate out batching of revisions.
228
    revision_iterator = make_log_rev_iterator(branch, view_revisions,
229
        generate_delta, search)
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
230
    for revs in revision_iterator:
231
        for (rev_id, revno, merge_depth), rev, delta in revs:
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
232
            # Note: 0 levels means show everything; merge_depth counts from 0
233
            if levels_to_display != 0 and merge_depth >= levels_to_display:
234
                continue
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
235
            if generate_diff:
3943.5.4 by Ian Clatworthy
filter diff by file
236
                diff = _format_diff(repo, rev, rev_id, specific_fileid)
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
237
            else:
238
                diff = None
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
239
            lr = LogRevision(rev, revno, merge_depth, delta,
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
240
                             rev_tag_dict.get(rev_id), diff)
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
241
            lf.log_revision(lr)
242
            if limit:
243
                log_count += 1
244
                if log_count >= limit:
3660.1.1 by Robert Collins
Fix log --limit (broken by log filtering patch).
245
                    return
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
246
247
3943.5.4 by Ian Clatworthy
filter diff by file
248
def _format_diff(repo, rev, rev_id, specific_fileid):
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
249
    if len(rev.parent_ids) == 0:
250
        ancestor_id = _mod_revision.NULL_REVISION
251
    else:
252
        ancestor_id = rev.parent_ids[0]
253
    tree_1 = repo.revision_tree(ancestor_id)
254
    tree_2 = repo.revision_tree(rev_id)
3943.5.4 by Ian Clatworthy
filter diff by file
255
    if specific_fileid:
256
        specific_files = [tree_2.id2path(specific_fileid)]
257
    else:
258
        specific_files = None
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
259
    s = StringIO()
3943.5.4 by Ian Clatworthy
filter diff by file
260
    diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
261
        new_label='')
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
262
    return s.getvalue()
263
264
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
265
def calculate_view_revisions(branch, start_revision, end_revision, direction,
266
                             specific_fileid, generate_merge_revisions,
267
                             allow_single_merge_revision):
3943.4.5 by John Arbash Meinel
Restore _linear_view_revisions.
268
    if (    not generate_merge_revisions
269
        and start_revision is end_revision is None
270
        and direction == 'reverse'
271
        and specific_fileid is None):
272
        return _linear_view_revisions(branch)
273
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
274
    mainline_revs, rev_nos, start_rev_id, end_rev_id = _get_mainline_revs(
275
        branch, start_revision, end_revision)
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
276
    if not mainline_revs:
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
277
        return []
1756.2.18 by Aaron Bentley
Factor out the revision list generation
278
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
279
    generate_single_revision = False
2985.1.1 by Aaron Bentley
Better behavior when user requests a log that cannot be viewed (Kent Gibson)
280
    if ((not generate_merge_revisions)
2978.3.2 by Kent Gibson
Use in rather than has_key
281
        and ((start_rev_id and (start_rev_id not in rev_nos))
282
            or (end_rev_id and (end_rev_id not in rev_nos)))):
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
283
        generate_single_revision = ((start_rev_id == end_rev_id)
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
284
            and allow_single_merge_revision)
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
285
        if not generate_single_revision:
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
286
            raise errors.BzrCommandError('Selected log formatter only supports'
287
                ' mainline revisions.')
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
288
        generate_merge_revisions = generate_single_revision
3940.1.3 by Ian Clatworthy
fix code
289
    include_merges = generate_merge_revisions or specific_fileid
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
290
    view_revs_iter = get_view_revisions(mainline_revs, rev_nos, branch,
3940.1.3 by Ian Clatworthy
fix code
291
                          direction, include_merges=include_merges)
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
292
293
    if direction == 'reverse':
294
        start_rev_id, end_rev_id = end_rev_id, start_rev_id
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
295
    view_revisions = _filter_revision_range(list(view_revs_iter),
296
                                            start_rev_id,
297
                                            end_rev_id)
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
298
    if view_revisions and generate_single_revision:
299
        view_revisions = view_revisions[0:1]
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
300
    if specific_fileid:
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
301
        view_revisions = _filter_revisions_touching_file_id(branch,
3940.1.5 by Ian Clatworthy
feedback from vila
302
            specific_fileid, view_revisions,
303
            include_merges=generate_merge_revisions)
2388.1.11 by Alexander Belchenko
changes after John's review
304
2466.12.2 by Kent Gibson
shift log output with only merge revisions to the left margin
305
    # rebase merge_depth - unless there are no revisions or 
306
    # either the first or last revision have merge_depth = 0.
307
    if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
2466.12.3 by Kent Gibson
Fix JAM's review comments for left align patch
308
        min_depth = min([d for r,n,d in view_revisions])
309
        if min_depth != 0:
2466.12.2 by Kent Gibson
shift log output with only merge revisions to the left margin
310
            view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
311
    return view_revisions
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.
312
530 by Martin Pool
- put back verbose log support for reversed logs
313
3943.4.5 by John Arbash Meinel
Restore _linear_view_revisions.
314
def _linear_view_revisions(branch):
315
    start_revno, start_revision_id = branch.last_revision_info()
316
    repo = branch.repository
317
    revision_ids = repo.iter_reverse_revision_history(start_revision_id)
318
    for num, revision_id in enumerate(revision_ids):
319
        yield revision_id, str(start_revno - num), 0
320
321
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
322
def make_log_rev_iterator(branch, view_revisions, generate_delta, search):
323
    """Create a revision iterator for log.
324
325
    :param branch: The branch being logged.
326
    :param view_revisions: The revisions being viewed.
327
    :param generate_delta: Whether to generate a delta for each revision.
328
    :param search: A user text search string.
3642.1.7 by Robert Collins
Review feedback.
329
    :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.
330
        delta).
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
331
    """
3642.1.5 by Robert Collins
Separate out batching of revisions.
332
    # Convert view_revisions into (view, None, None) groups to fit with
333
    # the standard interface here.
334
    if type(view_revisions) == list:
3642.1.7 by Robert Collins
Review feedback.
335
        # A single batch conversion is faster than many incremental ones.
336
        # As we have all the data, do a batch conversion.
3642.1.5 by Robert Collins
Separate out batching of revisions.
337
        nones = [None] * len(view_revisions)
338
        log_rev_iterator = iter([zip(view_revisions, nones, nones)])
339
    else:
340
        def _convert():
341
            for view in view_revisions:
342
                yield (view, None, None)
343
        log_rev_iterator = iter([_convert()])
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
344
    for adapter in log_adapters:
345
        log_rev_iterator = adapter(branch, generate_delta, search,
346
            log_rev_iterator)
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
347
    return log_rev_iterator
348
349
3642.1.7 by Robert Collins
Review feedback.
350
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.
351
    """Create a filtered iterator of log_rev_iterator matching on a regex.
352
353
    :param branch: The branch being logged.
354
    :param generate_delta: Whether to generate a delta for each revision.
355
    :param search: A user text search string.
356
    :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.
357
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
358
    :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.
359
        delta).
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
360
    """
361
    if search is None:
362
        return log_rev_iterator
363
    # Compile the search now to get early errors.
364
    searchRE = re.compile(search, re.IGNORECASE)
365
    return _filter_message_re(searchRE, log_rev_iterator)
366
367
368
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.
369
    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.
370
        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.
371
        for (rev_id, revno, merge_depth), rev, delta in revs:
372
            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.
373
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
374
        yield new_revs
375
376
3642.1.7 by Robert Collins
Review feedback.
377
def _make_delta_filter(branch, generate_delta, search, 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.
378
    """Add revision deltas to a log iterator if needed.
379
380
    :param branch: The branch being logged.
381
    :param generate_delta: Whether to generate a delta for each revision.
382
    :param search: A user text search string.
383
    :param log_rev_iterator: An input iterator containing all revisions that
384
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
385
    :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.
386
        delta).
387
    """
388
    if not generate_delta:
389
        return log_rev_iterator
390
    return _generate_deltas(branch.repository, log_rev_iterator)
391
392
393
def _generate_deltas(repository, log_rev_iterator):
3642.1.7 by Robert Collins
Review feedback.
394
    """Create deltas for each batch of revisions 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.
395
    for revs in log_rev_iterator:
396
        revisions = [rev[1] for rev in revs]
397
        deltas = repository.get_deltas_for_revisions(revisions)
398
        revs = [(rev[0], rev[1], delta) for rev, delta in izip(revs, deltas)]
399
        yield revs
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
400
401
3642.1.7 by Robert Collins
Review feedback.
402
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.
403
    """Extract revision objects from the repository
404
405
    :param branch: The branch being logged.
406
    :param generate_delta: Whether to generate a delta for each revision.
407
    :param search: A user text search string.
408
    :param log_rev_iterator: An input iterator containing all revisions that
409
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
410
    :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.
411
        delta).
412
    """
3642.1.5 by Robert Collins
Separate out batching of revisions.
413
    repository = branch.repository
3642.1.4 by Robert Collins
Factor out revision object extraction from revision batching.
414
    for revs in log_rev_iterator:
415
        # r = revision_id, n = revno, d = merge depth
416
        revision_ids = [view[0] for view, _, _ in revs]
417
        revisions = repository.get_revisions(revision_ids)
418
        revs = [(rev[0], revision, rev[2]) for rev, revision in
419
            izip(revs, revisions)]
420
        yield revs
421
422
3642.1.7 by Robert Collins
Review feedback.
423
def _make_batch_filter(branch, generate_delta, search, log_rev_iterator):
3642.1.5 by Robert Collins
Separate out batching of revisions.
424
    """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.
425
426
    :param branch: The branch being logged.
427
    :param generate_delta: Whether to generate a delta for each revision.
428
    :param search: A user text search string.
3642.1.5 by Robert Collins
Separate out batching of revisions.
429
    :param log_rev_iterator: An input iterator containing all revisions that
430
        could be displayed, in lists.
3874.2.4 by Vincent Ladeuil
Fix too long lines.
431
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
432
        delta).
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
433
    """
434
    repository = branch.repository
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
435
    num = 9
3642.1.5 by Robert Collins
Separate out batching of revisions.
436
    for batch in log_rev_iterator:
437
        batch = iter(batch)
438
        while True:
439
            step = [detail for _, detail in zip(range(num), batch)]
440
            if len(step) == 0:
441
                break
442
            yield step
443
            num = min(int(num * 1.5), 200)
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
444
445
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
446
def _get_mainline_revs(branch, start_revision, end_revision):
447
    """Get the mainline revisions from the branch.
448
    
449
    Generates the list of mainline revisions for the branch.
450
    
451
    :param  branch: The branch containing the revisions. 
452
453
    :param  start_revision: The first revision to be logged.
454
            For backwards compatibility this may be a mainline integer revno,
455
            but for merge revision support a RevisionInfo is expected.
456
457
    :param  end_revision: The last revision to be logged.
458
            For backwards compatibility this may be a mainline integer revno,
459
            but for merge revision support a RevisionInfo is expected.
460
461
    :return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
462
    """
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
463
    branch_revno, branch_last_revision = branch.last_revision_info()
464
    if branch_revno == 0:
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
465
        return None, None, None, None
466
467
    # For mainline generation, map start_revision and end_revision to 
468
    # mainline revnos. If the revision is not on the mainline choose the 
469
    # appropriate extreme of the mainline instead - the extra will be 
470
    # filtered later.
471
    # Also map the revisions to rev_ids, to be used in the later filtering
472
    # stage.
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
473
    start_rev_id = None
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
474
    if start_revision is None:
475
        start_revno = 1
476
    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.
477
        if isinstance(start_revision, revisionspec.RevisionInfo):
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
478
            start_rev_id = start_revision.rev_id
479
            start_revno = start_revision.revno or 1
480
        else:
481
            branch.check_real_revno(start_revision)
482
            start_revno = start_revision
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
483
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
484
    end_rev_id = None
485
    if end_revision is None:
3449.2.5 by John Arbash Meinel
Stop referencing the variable I removed.
486
        end_revno = branch_revno
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
487
    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.
488
        if isinstance(end_revision, revisionspec.RevisionInfo):
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
489
            end_rev_id = end_revision.rev_id
3449.2.5 by John Arbash Meinel
Stop referencing the variable I removed.
490
            end_revno = end_revision.revno or branch_revno
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
491
        else:
492
            branch.check_real_revno(end_revision)
493
            end_revno = end_revision
494
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
495
    if ((start_rev_id == _mod_revision.NULL_REVISION)
496
        or (end_rev_id == _mod_revision.NULL_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.
497
        raise errors.BzrCommandError('Logging revision 0 is invalid.')
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
498
    if start_revno > end_revno:
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.
499
        raise errors.BzrCommandError("Start revision must be older than "
500
                                     "the end revision.")
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
501
3449.2.7 by John Arbash Meinel
Minor tweak from Ian
502
    if end_revno < start_revno:
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
503
        return None, None, None, None
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
504
    cur_revno = branch_revno
505
    rev_nos = {}
506
    mainline_revs = []
507
    for revision_id in branch.repository.iter_reverse_revision_history(
508
                        branch_last_revision):
509
        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.
510
            # 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()'
511
            rev_nos[revision_id] = cur_revno
512
            mainline_revs.append(revision_id)
513
            break
514
        if cur_revno <= end_revno:
515
            rev_nos[revision_id] = cur_revno
516
            mainline_revs.append(revision_id)
517
        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.
518
    else:
519
        # We walked off the edge of all revisions, so we add a 'None' marker
520
        mainline_revs.append(None)
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
521
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
522
    mainline_revs.reverse()
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
523
524
    # override the mainline to look like the revision history.
525
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
526
527
528
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
529
    """Filter view_revisions based on revision ranges.
530
531
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth) 
532
            tuples to be filtered.
533
534
    :param start_rev_id: If not NONE specifies the first revision to be logged.
535
            If NONE then all revisions up to the end_rev_id are logged.
536
537
    :param end_rev_id: If not NONE specifies the last revision to be logged.
538
            If NONE then all revisions up to the end of the log are logged.
539
540
    :return: The filtered view_revisions.
541
    """
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
542
    if start_rev_id or end_rev_id:
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
543
        revision_ids = [r for r, n, d in view_revisions]
544
        if start_rev_id:
545
            start_index = revision_ids.index(start_rev_id)
546
        else:
547
            start_index = 0
548
        if start_rev_id == end_rev_id:
549
            end_index = start_index
550
        else:
551
            if end_rev_id:
552
                end_index = revision_ids.index(end_rev_id)
553
            else:
554
                end_index = len(view_revisions) - 1
555
        # To include the revisions merged into the last revision, 
556
        # extend end_rev_id down to, but not including, the next rev
557
        # with the same or lesser merge_depth
558
        end_merge_depth = view_revisions[end_index][2]
559
        try:
560
            for index in xrange(end_index+1, len(view_revisions)+1):
561
                if view_revisions[index][2] <= end_merge_depth:
562
                    end_index = index - 1
563
                    break
564
        except IndexError:
565
            # if the search falls off the end then log to the end as well
566
            end_index = len(view_revisions) - 1
567
        view_revisions = view_revisions[start_index:end_index+1]
568
    return view_revisions
569
570
3940.1.3 by Ian Clatworthy
fix code
571
def _filter_revisions_touching_file_id(branch, file_id, view_revisions,
572
    include_merges=True):
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
573
    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.
574
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
575
    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.
576
    This includes the revisions which directly change the file id,
577
    and the revisions which merge these changes. So if the
578
    revision graph is::
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
579
        A-.
580
        |\ \
581
        B C E
582
        |/ /
583
        D |
584
        |\|
585
        | F
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
586
        |/
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
587
        G
588
589
    And 'C' changes a file, then both C and D will be returned. F will not be
590
    returned even though it brings the changes to C into the branch starting
591
    with E. (Note that if we were using F as the tip instead of G, then we
592
    would see C, D, F.)
593
594
    This will also be restricted based on a subset of the mainline.
595
596
    :param branch: The branch where we can get text revision information.
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
597
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
598
    :param file_id: Filter out revisions that do not touch file_id.
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
599
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
600
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
601
        tuples. This is the list of revisions which will be filtered. It is
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
602
        assumed that view_revisions is in merge_sort order (i.e. newest
603
        revision first ).
604
3940.1.3 by Ian Clatworthy
fix code
605
    :param include_merges: include merge revisions in the result or not
606
2359.1.8 by John Arbash Meinel
doc
607
    :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.
608
    """
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
609
    # Lookup all possible text keys to determine which ones actually modified
610
    # the file.
611
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
3711.3.16 by John Arbash Meinel
Doc update.
612
    # Looking up keys in batches of 1000 can cut the time in half, as well as
613
    # memory consumption. GraphIndex *does* like to look for a few keys in
614
    # 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.
615
    # TODO: This code needs to be re-evaluated periodically as we tune the
616
    #       indexing layer. We might consider passing in hints as to the known
617
    #       access pattern (sparse/clustered, high success rate/low success
618
    #       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.
619
    get_parent_map = branch.repository.texts.get_parent_map
620
    modified_text_revisions = set()
621
    chunk_size = 1000
622
    for start in xrange(0, len(text_keys), chunk_size):
623
        next_keys = text_keys[start:start + chunk_size]
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
624
        # 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.
625
        modified_text_revisions.update(
626
            [k[1] for k in get_parent_map(next_keys)])
627
    del text_keys, next_keys
3711.3.14 by John Arbash Meinel
Change the per-file log algorithm dramatically.
628
629
    result = []
630
    # Track what revisions will merge the current revision, replace entries
631
    # with 'None' when they have been added to result
632
    current_merge_stack = [None]
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
633
    for info in view_revisions:
3711.3.14 by John Arbash Meinel
Change the per-file log algorithm dramatically.
634
        rev_id, revno, depth = info
635
        if depth == len(current_merge_stack):
636
            current_merge_stack.append(info)
637
        else:
638
            del current_merge_stack[depth + 1:]
639
            current_merge_stack[-1] = info
640
641
        if rev_id in modified_text_revisions:
642
            # This needs to be logged, along with the extra revisions
643
            for idx in xrange(len(current_merge_stack)):
644
                node = current_merge_stack[idx]
645
                if node is not None:
3940.1.3 by Ian Clatworthy
fix code
646
                    if include_merges or node[2] == 0:
647
                        result.append(node)
648
                        current_merge_stack[idx] = None
3711.3.4 by John Arbash Meinel
Significantly faster, but consuming more memory.
649
    return result
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
650
651
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
652
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
1756.2.22 by Aaron Bentley
Apply review comments
653
                       include_merges=True):
1756.2.18 by Aaron Bentley
Factor out the revision list generation
654
    """Produce an iterator of revisions to show
655
    :return: an iterator of (revision_id, revno, merge_depth)
656
    (if there is no revno for a revision, None is supplied)
657
    """
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
658
    if not include_merges:
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
659
        revision_ids = mainline_revs[1:]
660
        if direction == 'reverse':
661
            revision_ids.reverse()
662
        for revision_id in revision_ids:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
663
            yield revision_id, str(rev_nos[revision_id]), 0
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
664
        return
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
665
    graph = branch.repository.get_graph()
666
    # This asks for all mainline revisions, which means we only have to spider
667
    # sideways, rather than depth history. That said, its still size-of-history
668
    # and should be addressed.
3373.5.4 by John Arbash Meinel
Track down another bogus location. Only triggered with --long
669
    # mainline_revisions always includes an extra revision at the beginning, so
670
    # don't request it.
3287.6.8 by Robert Collins
Reduce code duplication as per review.
671
    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
672
        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.
673
    # filter out ghosts; merge_sort errors on ghosts.
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
674
    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.
675
    merge_sorted_revisions = tsort.merge_sort(
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
676
        rev_graph,
1756.2.18 by Aaron Bentley
Factor out the revision list generation
677
        mainline_revs[-1],
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
678
        mainline_revs,
679
        generate_revno=True)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
680
681
    if direction == 'forward':
682
        # forward means oldest first.
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
683
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
684
    elif direction != 'reverse':
685
        raise ValueError('invalid direction %r' % direction)
686
3874.2.4 by Vincent Ladeuil
Fix too long lines.
687
    for (sequence, rev_id, merge_depth, revno, end_of_merge
688
         ) in merge_sorted_revisions:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
689
        yield rev_id, '.'.join(map(str, revno)), merge_depth
1756.2.18 by Aaron Bentley
Factor out the revision list generation
690
691
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
692
def reverse_by_depth(merge_sorted_revisions, _depth=0):
693
    """Reverse revisions by depth.
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
694
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
695
    Revisions with a different depth are sorted as a group with the previous
696
    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
697
    but it looks much nicer.
698
    """
3842.2.6 by Vincent Ladeuil
Fix typo.
699
    # 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.
700
    merge_sorted_revisions = [(None, None, _depth)] + merge_sorted_revisions
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
701
    zd_revisions = []
702
    for val in merge_sorted_revisions:
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
703
        if val[2] == _depth:
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
704
            # Each revision at the current depth becomes a chunk grouping all
705
            # higher depth revisions.
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
706
            zd_revisions.append([val])
707
        else:
708
            zd_revisions[-1].append(val)
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
709
    for revisions in zd_revisions:
710
        if len(revisions) > 1:
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
711
            # 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.
712
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
713
    zd_revisions.reverse()
714
    result = []
715
    for chunk in zd_revisions:
716
        result.extend(chunk)
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
717
    if _depth == 0:
718
        # Top level call, get rid of the fake revisions that have been added
719
        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
720
    return result
721
722
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.
723
class LogRevision(object):
724
    """A revision to be logged (by LogFormatter.log_revision).
725
726
    A simple wrapper for the attributes of a revision to be logged.
727
    The attributes may or may not be populated, as determined by the 
728
    logging options and the log formatter capabilities.
729
    """
730
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
731
    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
732
                 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.
733
        self.rev = rev
734
        self.revno = revno
735
        self.merge_depth = merge_depth
736
        self.delta = delta
737
        self.tags = tags
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
738
        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.
739
740
794 by Martin Pool
- Merge John's nice short-log format.
741
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.
742
    """Abstract class to display log messages.
743
744
    At a minimum, a derived class must implement the log_revision method.
745
746
    If the LogFormatter needs to be informed of the beginning or end of
747
    a log it should implement the begin_log and/or end_log hook methods.
748
749
    A LogFormatter should define the following supports_XXX flags 
750
    to indicate which LogRevision attributes it supports:
751
752
    - supports_delta must be True if this log formatter supports delta.
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
753
        Otherwise the delta attribute may not be populated.  The 'delta_format'
754
        attribute describes whether the 'short_status' format (1) or the long
755
        one (2) sould be used.
756
 
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.
757
    - supports_merge_revisions must be True if this log formatter supports 
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
758
        merge revisions.  If not, and if supports_single_merge_revisions is
759
        also not True, then only mainline revisions will be passed to the 
760
        formatter.
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
761
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
762
    - preferred_levels is the number of levels this formatter defaults to.
763
        The default value is zero meaning display all levels.
764
        This value is only relevant if supports_merge_revisions is True.
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
765
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
766
    - supports_single_merge_revision must be True if this log formatter
767
        supports logging only a single merge revision.  This flag is
768
        only relevant if supports_merge_revisions is not True.
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
769
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.
770
    - supports_tags must be True if this log formatter supports tags.
771
        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
772
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
773
    - supports_diff must be True if this log formatter supports diffs.
774
        Otherwise the diff attribute may not be populated.
775
3144.7.1 by Guillermo Gonzalez
* added show_properties to LonLogFormat and the hooks to register custom functions
776
    Plugins can register functions to show custom revision properties using
3144.7.13 by Guillermo Gonzalez
* fixed typo LogFormatter.show_properties in docstring
777
    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
778
    must respect the following interface description:
3144.7.2 by Guillermo Gonzalez
* cleanup a bit the interface
779
        def my_show_properties(properties_dict):
780
            # code that returns a dict {'name':'value'} of the properties 
781
            # 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.
782
    """
3947.1.10 by Ian Clatworthy
review feedback from vila
783
    preferred_levels = 0
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
784
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
785
    def __init__(self, to_file, show_ids=False, show_timezone='original',
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
786
                 delta_format=None, levels=None):
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
787
        """Create a LogFormatter.
788
789
        :param to_file: the file to output to
790
        :param show_ids: if True, revision-ids are to be displayed
791
        :param show_timezone: the timezone to use
792
        :param delta_format: the level of delta information to display
793
          or None to leave it u to the formatter to decide
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
794
        :param levels: the number of levels to display; None or -1 to
795
          let the log formatter decide.
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
796
        """
794 by Martin Pool
- Merge John's nice short-log format.
797
        self.to_file = to_file
798
        self.show_ids = show_ids
799
        self.show_timezone = show_timezone
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
800
        if delta_format is None:
801
            # Ensures backward compatibility
802
            delta_format = 2 # long format
803
        self.delta_format = delta_format
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
804
        self.levels = levels
805
3947.1.10 by Ian Clatworthy
review feedback from vila
806
    def get_levels(self):
807
        """Get the number of levels to display or 0 for all."""
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
808
        if getattr(self, 'supports_merge_revisions', False):
809
            if self.levels is None or self.levels == -1:
3947.1.10 by Ian Clatworthy
review feedback from vila
810
                return self.preferred_levels
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
811
            else:
812
                return self.levels
813
        return 1
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
814
3947.1.10 by Ian Clatworthy
review feedback from vila
815
    def log_revision(self, revision):
816
        """Log a revision.
817
818
        :param  revision:   The LogRevision to be logged.
819
        """
820
        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.
821
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
822
    def short_committer(self, rev):
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
823
        name, address = config.parse_username(rev.committer)
824
        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.
825
            return name
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
826
        return address
2388.1.11 by Alexander Belchenko
changes after John's review
827
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.
828
    def short_author(self, rev):
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
829
        name, address = config.parse_username(rev.get_apparent_author())
830
        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.
831
            return name
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
832
        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.
833
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
834
    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
835
        """Displays the custom properties returned by each registered handler.
836
        
3144.7.13 by Guillermo Gonzalez
* fixed typo LogFormatter.show_properties in docstring
837
        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
838
        """
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
839
        for key, handler in properties_handler_registry.iteritems():
840
            for key, value in handler(revision).items():
841
                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
842
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
843
    def show_diff(self, to_file, diff, indent):
844
        for l in diff.rstrip().split('\n'):
845
            to_file.write(indent + '%s\n' % (l,))
846
2388.1.11 by Alexander Belchenko
changes after John's review
847
794 by Martin Pool
- Merge John's nice short-log format.
848
class LongLogFormatter(LogFormatter):
2388.1.11 by Alexander Belchenko
changes after John's review
849
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.
850
    supports_merge_revisions = True
851
    supports_delta = True
852
    supports_tags = True
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
853
    supports_diff = True
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
854
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.
855
    def log_revision(self, revision):
856
        """Log a revision, either merged or not."""
2671.2.5 by Lukáš Lalinský
Fixes for comments from the mailing list.
857
        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.
858
        to_file = self.to_file
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
859
        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.
860
        if revision.revno is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
861
            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.
862
        if revision.tags:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
863
            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.
864
        if self.show_ids:
3257.2.1 by Adeodato Simó
Add a space after "revision-id:" in log output.
865
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
866
            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.
867
            for parent_id in revision.rev.parent_ids:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
868
                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
869
        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.
870
2671.5.7 by Lukáš Lalinsky
Rename get_author to get_apparent_author, revert the long log back to displaying the committer.
871
        author = revision.rev.properties.get('author', None)
872
        if author is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
873
            to_file.write(indent + 'author: %s\n' % (author,))
874
        to_file.write(indent + 'committer: %s\n' % (revision.rev.committer,))
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
875
876
        branch_nick = revision.rev.properties.get('branch-nick', None)
877
        if branch_nick is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
878
            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.
879
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.
880
        date_str = format_date(revision.rev.timestamp,
881
                               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.
882
                               self.show_timezone)
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
883
        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.
884
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
885
        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.
886
        if not revision.rev.message:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
887
            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.
888
        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.
889
            message = revision.rev.message.rstrip('\r\n')
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
890
            for l in message.split('\n'):
3943.5.3 by Ian Clatworthy
add tests
891
                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.
892
        if revision.delta is not None:
3874.1.7 by Vincent Ladeuil
Restrict '-v' change to log --short only.
893
            # We don't respect delta_format for compatibility
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
894
            revision.delta.show(to_file, self.show_ids, indent=indent,
3874.1.7 by Vincent Ladeuil
Restrict '-v' change to log --short only.
895
                                short_status=False)
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
896
        if revision.diff is not None:
897
            to_file.write(indent + 'diff:\n')
3943.5.6 by Ian Clatworthy
feedback from jam's review
898
            # Note: we explicitly don't indent the diff (relative to the
899
            # revision information) so that the output can be fed to patch -p0
900
            self.show_diff(to_file, revision.diff, indent)
794 by Martin Pool
- Merge John's nice short-log format.
901
902
903
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.
904
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
905
    supports_merge_revisions = True
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
906
    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.
907
    supports_delta = True
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
908
    supports_tags = True
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
909
    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.
910
3947.1.9 by Ian Clatworthy
get offset right when dotted-revno in column 1
911
    def __init__(self, *args, **kwargs):
912
        super(ShortLogFormatter, self).__init__(*args, **kwargs)
913
        self.revno_width_by_depth = {}
914
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.
915
    def log_revision(self, revision):
3947.1.7 by Ian Clatworthy
tweak indenting/offsetting for --short given dotted revno lengths
916
        # We need two indents: one per depth and one for the information
917
        # relative to that indent. Most mainline revnos are 5 chars or
3970.1.1 by Ian Clatworthy
log -n/--levels (Ian Clatworthy)
918
        # 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
919
        # calculated, we need to remember the offset for a given depth
920
        # as we might be starting from a dotted revno in the first column
921
        # and we want subsequent mainline revisions to line up.
922
        depth = revision.merge_depth
923
        indent = '    ' * depth
924
        revno_width = self.revno_width_by_depth.get(depth)
925
        if revno_width is None:
926
            if revision.revno.find('.') == -1:
3947.1.10 by Ian Clatworthy
review feedback from vila
927
                # mainline revno, e.g. 12345
3947.1.9 by Ian Clatworthy
get offset right when dotted-revno in column 1
928
                revno_width = 5
929
            else:
3947.1.10 by Ian Clatworthy
review feedback from vila
930
                # dotted revno, e.g. 12345.10.55
931
                revno_width = 11
3947.1.9 by Ian Clatworthy
get offset right when dotted-revno in column 1
932
            self.revno_width_by_depth[depth] = revno_width
3947.1.7 by Ian Clatworthy
tweak indenting/offsetting for --short given dotted revno lengths
933
        offset = ' ' * (revno_width + 1)
934
794 by Martin Pool
- Merge John's nice short-log format.
935
        to_file = self.to_file
2483.2.2 by John Arbash Meinel
Add [merge] after the timestamp for revisions with merges.
936
        is_merge = ''
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
937
        if len(revision.rev.parent_ids) > 1:
2483.2.2 by John Arbash Meinel
Add [merge] after the timestamp for revisions with merges.
938
            is_merge = ' [merge]'
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
939
        tags = ''
940
        if revision.tags:
3946.3.2 by Ian Clatworthy
add tests & NEWS item
941
            tags = ' {%s}' % (', '.join(revision.tags))
3947.1.8 by Ian Clatworthy
merge bzr.dev r3954
942
        to_file.write(indent + "%*s %s\t%s%s%s\n" % (revno_width,
943
                revision.revno, self.short_author(revision.rev),
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
944
                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.
945
                            revision.rev.timezone or 0,
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
946
                            self.show_timezone, date_fmt="%Y-%m-%d",
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
947
                            show_offset=False),
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
948
                tags, is_merge))
794 by Martin Pool
- Merge John's nice short-log format.
949
        if self.show_ids:
3947.1.7 by Ian Clatworthy
tweak indenting/offsetting for --short given dotted revno lengths
950
            to_file.write(indent + offset + 'revision-id:%s\n'
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
951
                          % (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.
952
        if not revision.rev.message:
3947.1.7 by Ian Clatworthy
tweak indenting/offsetting for --short given dotted revno lengths
953
            to_file.write(indent + offset + '(no message)\n')
794 by Martin Pool
- Merge John's nice short-log format.
954
        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.
955
            message = revision.rev.message.rstrip('\r\n')
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
956
            for l in message.split('\n'):
3947.1.7 by Ian Clatworthy
tweak indenting/offsetting for --short given dotted revno lengths
957
                to_file.write(indent + offset + '%s\n' % (l,))
794 by Martin Pool
- Merge John's nice short-log format.
958
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.
959
        if revision.delta is not None:
3947.1.7 by Ian Clatworthy
tweak indenting/offsetting for --short given dotted revno lengths
960
            revision.delta.show(to_file, self.show_ids, indent=indent + offset,
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
961
                                short_status=self.delta_format==1)
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
962
        if revision.diff is not None:
963
            self.show_diff(to_file, revision.diff, '      ')
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
964
        to_file.write('\n')
794 by Martin Pool
- Merge John's nice short-log format.
965
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
966
1185.12.25 by Aaron Bentley
Added one-line log format
967
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.
968
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
969
    supports_merge_revisions = True
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
970
    preferred_levels = 1
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
971
    supports_tags = True
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
972
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.
973
    def __init__(self, *args, **kwargs):
974
        super(LineLogFormatter, self).__init__(*args, **kwargs)
975
        self._max_chars = terminal_width() - 1
976
1185.12.25 by Aaron Bentley
Added one-line log format
977
    def truncate(self, str, max_len):
978
        if len(str) <= max_len:
979
            return str
980
        return str[:max_len-3]+'...'
981
982
    def date_string(self, rev):
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
983
        return format_date(rev.timestamp, rev.timezone or 0,
1185.12.25 by Aaron Bentley
Added one-line log format
984
                           self.show_timezone, date_fmt="%Y-%m-%d",
985
                           show_offset=False)
986
987
    def message(self, rev):
988
        if not rev.message:
989
            return '(no message)'
990
        else:
991
            return rev.message
992
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.
993
    def log_revision(self, revision):
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
994
        indent = '  ' * revision.merge_depth
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
995
        self.to_file.write(self.log_string(revision.revno, revision.rev,
3947.1.8 by Ian Clatworthy
merge bzr.dev r3954
996
            self._max_chars, revision.tags, indent))
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
997
        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.
998
3947.1.8 by Ian Clatworthy
merge bzr.dev r3954
999
    def log_string(self, revno, rev, max_chars, tags=None, prefix=''):
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1000
        """Format log info into one string. Truncate tail of string
3677.1.1 by Vincent Ladeuil
Begin fixing bug #233817.
1001
        :param  revno:      revision number or None.
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1002
                            Revision numbers counts from 1.
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1003
        :param  rev:        revision object
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1004
        :param  max_chars:  maximum length of resulting string
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1005
        :param  tags:       list of tags or None
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
1006
        :param  prefix:     string to prefix each line
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1007
        :return:            formatted truncated string
1008
        """
1009
        out = []
1010
        if revno:
1011
            # show revno only when is not None
3946.3.4 by Ian Clatworthy
minor cleanup
1012
            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.
1013
        out.append(self.truncate(self.short_author(rev), 20))
1185.12.25 by Aaron Bentley
Added one-line log format
1014
        out.append(self.date_string(rev))
3946.3.3 by Ian Clatworthy
feedback from jelmer re position of tags in --line
1015
        if tags:
1016
            tag_str = '{%s}' % (', '.join(tags))
1017
            out.append(tag_str)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
1018
        out.append(rev.get_summary())
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
1019
        return self.truncate(prefix + " ".join(out).rstrip('\n'), max_chars)
794 by Martin Pool
- Merge John's nice short-log format.
1020
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1021
1185.12.27 by Aaron Bentley
Use line log for pending merges
1022
def line_log(rev, max_chars):
1023
    lf = LineLogFormatter(None)
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1024
    return lf.log_string(None, rev, max_chars)
1185.12.27 by Aaron Bentley
Use line log for pending merges
1025
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1026
1027
class LogFormatterRegistry(registry.Registry):
1028
    """Registry for log formatters"""
1029
1030
    def make_formatter(self, name, *args, **kwargs):
1031
        """Construct a formatter from arguments.
1032
1033
        :param name: Name of the formatter to construct.  'short', 'long' and
1034
            'line' are built-in.
1035
        """
1036
        return self.get(name)(*args, **kwargs)
1037
1038
    def get_default(self, branch):
1039
        return self.get(branch.get_config().log_format())
1040
1041
1042
log_formatter_registry = LogFormatterRegistry()
1043
1044
1045
log_formatter_registry.register('short', ShortLogFormatter,
1046
                                'Moderately short log format')
1047
log_formatter_registry.register('long', LongLogFormatter,
1048
                                'Detailed log format')
1049
log_formatter_registry.register('line', LineLogFormatter,
1050
                                'Log format with one line per revision')
1051
794 by Martin Pool
- Merge John's nice short-log format.
1052
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
1053
def register_formatter(name, formatter):
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1054
    log_formatter_registry.register(name, formatter)
1055
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
1056
794 by Martin Pool
- Merge John's nice short-log format.
1057
def log_formatter(name, *args, **kwargs):
1393.1.56 by Martin Pool
- doc and small refactoring of log code
1058
    """Construct a formatter from arguments.
1059
1185.12.27 by Aaron Bentley
Use line log for pending merges
1060
    name -- Name of the formatter to construct; currently 'long', 'short' and
1061
        'line' are supported.
1393.1.56 by Martin Pool
- doc and small refactoring of log code
1062
    """
794 by Martin Pool
- Merge John's nice short-log format.
1063
    try:
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1064
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
1553.2.2 by Erik Bågfors
Made "unknown log formatter" error message work
1065
    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.
1066
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1067
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1068
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1069
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1070
    # deprecated; for compatibility
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1071
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
1072
    lf.show(revno, rev, delta)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1073
2490.1.4 by John Arbash Meinel
Update bzrlib.log.show_changed_revisions to use the new api
1074
1551.17.2 by Aaron Bentley
Stop showing deltas in pull -v output
1075
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
1076
                           log_format='long'):
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1077
    """Show the change in revision history comparing the old revision history to the new one.
1078
1079
    :param branch: The branch where the revisions exist
1080
    :param old_rh: The old revision history
1081
    :param new_rh: The new revision history
1082
    :param to_file: A file to write the results to. If None, stdout will be used
1083
    """
1084
    if to_file is None:
2997.1.3 by Alexander Belchenko
file wrapper around stdout should use terminal encoding, not user_encoding.
1085
        to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
1086
            errors='replace')
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1087
    lf = log_formatter(log_format,
1088
                       show_ids=False,
1089
                       to_file=to_file,
1090
                       show_timezone='original')
1091
1092
    # This is the first index which is different between
1093
    # old and new
1094
    base_idx = None
1095
    for i in xrange(max(len(new_rh),
1096
                        len(old_rh))):
1097
        if (len(new_rh) <= i
1098
            or len(old_rh) <= i
1099
            or new_rh[i] != old_rh[i]):
1100
            base_idx = i
1101
            break
1102
1103
    if base_idx is None:
1104
        to_file.write('Nothing seems to have changed\n')
1105
        return
1106
    ## TODO: It might be nice to do something like show_log
1107
    ##       and show the merged entries. But since this is the
1108
    ##       removed revisions, it shouldn't be as important
1109
    if base_idx < len(old_rh):
1110
        to_file.write('*'*60)
1111
        to_file.write('\nRemoved Revisions:\n')
1112
        for i in range(base_idx, len(old_rh)):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1113
            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
1114
            lr = LogRevision(rev, i+1, 0, None)
1115
            lf.log_revision(lr)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1116
        to_file.write('*'*60)
1117
        to_file.write('\n\n')
1118
    if base_idx < len(new_rh):
1119
        to_file.write('Added Revisions:\n')
1120
        show_log(branch,
1121
                 lf,
1122
                 None,
1551.17.2 by Aaron Bentley
Stop showing deltas in pull -v output
1123
                 verbose=False,
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1124
                 direction='forward',
1125
                 start_revision=base_idx+1,
1126
                 end_revision=len(new_rh),
1127
                 search=None)
1128
3144.7.4 by Guillermo Gonzalez
* move the function regisstry into a real Registry instead of a list
1129
3848.1.7 by Aaron Bentley
Use repository in get_history_change
1130
def get_history_change(old_revision_id, new_revision_id, repository):
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1131
    """Calculate the uncommon lefthand history between two revisions.
1132
1133
    :param old_revision_id: The original revision id.
1134
    :param new_revision_id: The new revision id.
3848.1.22 by Aaron Bentley
Fix spelling
1135
    :param repository: The repository to use for the calculation.
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1136
1137
    return old_history, new_history
1138
    """
3848.1.6 by Aaron Bentley
Implement get_history_change
1139
    old_history = []
1140
    old_revisions = set()
1141
    new_history = []
1142
    new_revisions = set()
3848.1.7 by Aaron Bentley
Use repository in get_history_change
1143
    new_iter = repository.iter_reverse_revision_history(new_revision_id)
1144
    old_iter = repository.iter_reverse_revision_history(old_revision_id)
3848.1.6 by Aaron Bentley
Implement get_history_change
1145
    stop_revision = None
1146
    do_old = True
1147
    do_new = True
1148
    while do_new or do_old:
1149
        if do_new:
1150
            try:
1151
                new_revision = new_iter.next()
1152
            except StopIteration:
1153
                do_new = False
1154
            else:
1155
                new_history.append(new_revision)
1156
                new_revisions.add(new_revision)
1157
                if new_revision in old_revisions:
1158
                    stop_revision = new_revision
1159
                    break
1160
        if do_old:
1161
            try:
1162
                old_revision = old_iter.next()
1163
            except StopIteration:
1164
                do_old = False
1165
            else:
1166
                old_history.append(old_revision)
1167
                old_revisions.add(old_revision)
1168
                if old_revision in new_revisions:
1169
                    stop_revision = old_revision
1170
                    break
1171
    new_history.reverse()
1172
    old_history.reverse()
1173
    if stop_revision is not None:
1174
        new_history = new_history[new_history.index(stop_revision) + 1:]
1175
        old_history = old_history[old_history.index(stop_revision) + 1:]
1176
    return old_history, new_history
1177
1178
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1179
def show_branch_change(branch, output, old_revno, old_revision_id):
1180
    """Show the changes made to a branch.
1181
1182
    :param branch: The branch to show changes about.
1183
    :param output: A file-like object to write changes to.
1184
    :param old_revno: The revno of the old tip.
1185
    :param old_revision_id: The revision_id of the old tip.
1186
    """
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1187
    new_revno, new_revision_id = branch.last_revision_info()
1188
    old_history, new_history = get_history_change(old_revision_id,
1189
                                                  new_revision_id,
1190
                                                  branch.repository)
1191
    if old_history == [] and new_history == []:
1192
        output.write('Nothing seems to have changed\n')
1193
        return
1194
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1195
    log_format = log_formatter_registry.get_default(branch)
1196
    lf = log_format(show_ids=False, to_file=output, show_timezone='original')
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1197
    if old_history != []:
1198
        output.write('*'*60)
1199
        output.write('\nRemoved Revisions:\n')
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1200
        show_flat_log(branch.repository, old_history, old_revno, lf)
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1201
        output.write('*'*60)
1202
        output.write('\n\n')
1203
    if new_history != []:
3848.1.9 by Aaron Bentley
new/old sections are omitted as appropriate.
1204
        output.write('Added Revisions:\n')
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1205
        start_revno = new_revno - len(new_history) + 1
1206
        show_log(branch, lf, None, verbose=False, direction='forward',
1207
                 start_revision=start_revno,)
1208
1209
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1210
def show_flat_log(repository, history, last_revno, lf):
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1211
    """Show a simple log of the specified history.
1212
1213
    :param repository: The repository to retrieve revisions from.
1214
    :param history: A list of revision_ids indicating the lefthand history.
1215
    :param last_revno: The revno of the last revision_id in the history.
1216
    :param lf: The log formatter to use.
1217
    """
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1218
    start_revno = last_revno - len(history) + 1
1219
    revisions = repository.get_revisions(history)
1220
    for i, rev in enumerate(revisions):
1221
        lr = LogRevision(rev, i + last_revno, 0, None)
1222
        lf.log_revision(lr)
1223
1224
3943.6.4 by Ian Clatworthy
review feedback from vila
1225
def _get_fileid_to_log(revision, tree, b, fp):
1226
    """Find the file-id to log for a file path in a revision range.
1227
1228
    :param revision: the revision range as parsed on the command line
1229
    :param tree: the working tree, if any
1230
    :param b: the branch
1231
    :param fp: file path
1232
    """
1233
    if revision is None:
1234
        if tree is None:
1235
            tree = b.basis_tree()
1236
        file_id = tree.path2id(fp)
1237
        if file_id is None:
1238
            # go back to when time began
3972.1.2 by Ian Clatworthy
fix failing test when history completely empty
1239
            try:
1240
                rev1 = b.get_rev_id(1)
1241
            except errors.NoSuchRevision:
1242
                # No history at all
1243
                file_id = None
1244
            else:
1245
                tree = b.repository.revision_tree(rev1)
1246
                file_id = tree.path2id(fp)
3943.6.4 by Ian Clatworthy
review feedback from vila
1247
1248
    elif len(revision) == 1:
1249
        # One revision given - file must exist in it
1250
        tree = revision[0].as_tree(b)
1251
        file_id = tree.path2id(fp)
1252
1253
    elif len(revision) == 2:
1254
        # Revision range given. Get the file-id from the end tree.
1255
        # If that fails, try the start tree.
1256
        rev_id = revision[1].as_revision_id(b)
1257
        if rev_id is None:
1258
            tree = b.basis_tree()
1259
        else:
1260
            tree = revision[1].as_tree(b)
1261
        file_id = tree.path2id(fp)
1262
        if file_id is None:
1263
            rev_id = revision[0].as_revision_id(b)
1264
            if rev_id is None:
1265
                rev1 = b.get_rev_id(1)
1266
                tree = b.repository.revision_tree(rev1)
1267
            else:
1268
                tree = revision[0].as_tree(b)
1269
            file_id = tree.path2id(fp)
1270
    else:
1271
        raise errors.BzrCommandError(
1272
            'bzr log --revision takes one or two values.')
1273
    return file_id
1274
1275
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
1276
properties_handler_registry = registry.Registry()
3830.4.1 by Jelmer Vernooij
Add base classes for foreign branches.
1277
properties_handler_registry.register_lazy("foreign",
1278
                                          "bzrlib.foreign",
1279
                                          "show_foreign_properties")
1280
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1281
1282
# adapters which revision ids to log are filtered. When log is called, the
1283
# log_rev_iterator is adapted through each of these factory methods.
1284
# Plugins are welcome to mutate this list in any way they like - as long
1285
# as the overall behaviour is preserved. At this point there is no extensible
1286
# mechanism for getting parameters to each factory method, and until there is
1287
# this won't be considered a stable api.
1288
log_adapters = [
1289
    # core log logic
3642.1.7 by Robert Collins
Review feedback.
1290
    _make_batch_filter,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1291
    # read revision objects
3642.1.7 by Robert Collins
Review feedback.
1292
    _make_revision_objects,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1293
    # filter on log messages
3642.1.7 by Robert Collins
Review feedback.
1294
    _make_search_filter,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1295
    # generate deltas for things we will show
3642.1.7 by Robert Collins
Review feedback.
1296
    _make_delta_filter
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1297
    ]