/brz/remove-bazaar

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