/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,
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,
2466.9.1 by Kent Gibson
add bzr log --limit
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,
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
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
211
    log_count = 0
3936.3.1 by Ian Clatworthy
refactor _show_log
212
    revision_iterator = _create_log_revision_iterator(branch, start_revision,
213
        end_revision, direction, specific_fileid, search,
214
        generate_merge_revisions, allow_single_merge_revision, generate_delta)
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
215
    for revs in revision_iterator:
216
        for (rev_id, revno, merge_depth), rev, delta in revs:
217
            lr = LogRevision(rev, revno, merge_depth, delta,
218
                             rev_tag_dict.get(rev_id))
219
            lf.log_revision(lr)
220
            if limit:
221
                log_count += 1
222
                if log_count >= limit:
3660.1.1 by Robert Collins
Fix log --limit (broken by log filtering patch).
223
                    return
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
224
225
3936.3.1 by Ian Clatworthy
refactor _show_log
226
def _create_log_revision_iterator(branch, start_revision, end_revision,
227
    direction, specific_fileid, search, generate_merge_revisions,
228
    allow_single_merge_revision, generate_delta):
229
    """Create a revision iterator for log.
230
231
    :param branch: The branch being logged.
232
    :param start_revision: If not None, only show revisions >= start_revision
233
    :param end_revision: If not None, only show revisions <= end_revision
234
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
235
        earliest to latest.
236
    :param specific_fileid: If not None, list only the commits affecting the
237
        specified file.
238
    :param search: If not None, only show revisions with matching commit
239
        messages.
240
    :param generate_merge_revisions: If False, show only mainline revisions.
3936.3.2 by Ian Clatworthy
minor cleanups
241
    :param allow_single_merge_revision: If True, logging of a single
242
        revision off the mainline is to be allowed
3936.3.1 by Ian Clatworthy
refactor _show_log
243
    :param generate_delta: Whether to generate a delta for each revision.
244
245
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
246
        delta).
247
    """
248
    # Intial implementation - call existing functions
249
    view_revisions = calculate_view_revisions(branch, start_revision,
3936.3.2 by Ian Clatworthy
minor cleanups
250
        end_revision, direction, specific_fileid, generate_merge_revisions,
251
        allow_single_merge_revision)
3936.3.1 by Ian Clatworthy
refactor _show_log
252
    return make_log_rev_iterator(branch, view_revisions, generate_delta, search)
253
254
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
255
def calculate_view_revisions(branch, start_revision, end_revision, direction,
256
                             specific_fileid, generate_merge_revisions,
257
                             allow_single_merge_revision):
3936.3.1 by Ian Clatworthy
refactor _show_log
258
    if (not generate_merge_revisions
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
259
        and start_revision is end_revision is None
260
        and direction == 'reverse'
261
        and specific_fileid is None):
3302.1.3 by Aaron Bentley
Add optimization of the simple case of generating view revisions
262
        return _linear_view_revisions(branch)
263
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
264
    mainline_revs, rev_nos, start_rev_id, end_rev_id = _get_mainline_revs(
265
        branch, start_revision, end_revision)
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
266
    if not mainline_revs:
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
267
        return []
1756.2.18 by Aaron Bentley
Factor out the revision list generation
268
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
269
    generate_single_revision = False
2985.1.1 by Aaron Bentley
Better behavior when user requests a log that cannot be viewed (Kent Gibson)
270
    if ((not generate_merge_revisions)
2978.3.2 by Kent Gibson
Use in rather than has_key
271
        and ((start_rev_id and (start_rev_id not in rev_nos))
272
            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.
273
        generate_single_revision = ((start_rev_id == end_rev_id)
3302.1.2 by Aaron Bentley
Split out the major view_revision calculation logic
274
            and allow_single_merge_revision)
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
275
        if not generate_single_revision:
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
276
            raise errors.BzrCommandError('Selected log formatter only supports'
277
                ' mainline revisions.')
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
278
        generate_merge_revisions = generate_single_revision
2359.1.1 by Kent Gibson
Fix ``bzr log <file>`` so it only logs the revisions that changed the file, and does it faster.
279
    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.
280
                          direction, include_merges=generate_merge_revisions)
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
281
282
    if direction == 'reverse':
283
        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.
284
    view_revisions = _filter_revision_range(list(view_revs_iter),
285
                                            start_rev_id,
286
                                            end_rev_id)
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
287
    if view_revisions and generate_single_revision:
288
        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.
289
    if specific_fileid:
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
290
        view_revisions = _filter_revisions_touching_file_id(branch,
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
291
                                                            specific_fileid,
292
                                                            view_revisions)
2388.1.11 by Alexander Belchenko
changes after John's review
293
2466.12.2 by Kent Gibson
shift log output with only merge revisions to the left margin
294
    # rebase merge_depth - unless there are no revisions or 
295
    # either the first or last revision have merge_depth = 0.
296
    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
297
        min_depth = min([d for r,n,d in view_revisions])
298
        if min_depth != 0:
2466.12.2 by Kent Gibson
shift log output with only merge revisions to the left margin
299
            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
300
    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.
301
530 by Martin Pool
- put back verbose log support for reversed logs
302
3302.1.3 by Aaron Bentley
Add optimization of the simple case of generating view revisions
303
def _linear_view_revisions(branch):
304
    start_revno, start_revision_id = branch.last_revision_info()
305
    repo = branch.repository
306
    revision_ids = repo.iter_reverse_revision_history(start_revision_id)
307
    for num, revision_id in enumerate(revision_ids):
3302.1.4 by Aaron Bentley
Return revno as a string
308
        yield revision_id, str(start_revno - num), 0
3302.1.3 by Aaron Bentley
Add optimization of the simple case of generating view revisions
309
310
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
311
def make_log_rev_iterator(branch, view_revisions, generate_delta, search):
312
    """Create a revision iterator for log.
313
314
    :param branch: The branch being logged.
315
    :param view_revisions: The revisions being viewed.
316
    :param generate_delta: Whether to generate a delta for each revision.
317
    :param search: A user text search string.
3642.1.7 by Robert Collins
Review feedback.
318
    :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.
319
        delta).
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
320
    """
3642.1.5 by Robert Collins
Separate out batching of revisions.
321
    # Convert view_revisions into (view, None, None) groups to fit with
322
    # the standard interface here.
323
    if type(view_revisions) == list:
3642.1.7 by Robert Collins
Review feedback.
324
        # A single batch conversion is faster than many incremental ones.
325
        # As we have all the data, do a batch conversion.
3642.1.5 by Robert Collins
Separate out batching of revisions.
326
        nones = [None] * len(view_revisions)
327
        log_rev_iterator = iter([zip(view_revisions, nones, nones)])
328
    else:
329
        def _convert():
330
            for view in view_revisions:
331
                yield (view, None, None)
332
        log_rev_iterator = iter([_convert()])
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
333
    for adapter in log_adapters:
334
        log_rev_iterator = adapter(branch, generate_delta, search,
335
            log_rev_iterator)
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
336
    return log_rev_iterator
337
338
3642.1.7 by Robert Collins
Review feedback.
339
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.
340
    """Create a filtered iterator of log_rev_iterator matching on a regex.
341
342
    :param branch: The branch being logged.
343
    :param generate_delta: Whether to generate a delta for each revision.
344
    :param search: A user text search string.
345
    :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.
346
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
347
    :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.
348
        delta).
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
349
    """
350
    if search is None:
351
        return log_rev_iterator
352
    # Compile the search now to get early errors.
353
    searchRE = re.compile(search, re.IGNORECASE)
354
    return _filter_message_re(searchRE, log_rev_iterator)
355
356
357
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.
358
    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.
359
        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.
360
        for (rev_id, revno, merge_depth), rev, delta in revs:
361
            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.
362
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
363
        yield new_revs
364
365
3642.1.7 by Robert Collins
Review feedback.
366
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.
367
    """Add revision deltas to a log iterator if needed.
368
369
    :param branch: The branch being logged.
370
    :param generate_delta: Whether to generate a delta for each revision.
371
    :param search: A user text search string.
372
    :param log_rev_iterator: An input iterator containing all revisions that
373
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
374
    :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.
375
        delta).
376
    """
377
    if not generate_delta:
378
        return log_rev_iterator
379
    return _generate_deltas(branch.repository, log_rev_iterator)
380
381
382
def _generate_deltas(repository, log_rev_iterator):
3642.1.7 by Robert Collins
Review feedback.
383
    """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.
384
    for revs in log_rev_iterator:
385
        revisions = [rev[1] for rev in revs]
386
        deltas = repository.get_deltas_for_revisions(revisions)
387
        revs = [(rev[0], rev[1], delta) for rev, delta in izip(revs, deltas)]
388
        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.
389
390
3642.1.7 by Robert Collins
Review feedback.
391
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.
392
    """Extract revision objects from the repository
393
394
    :param branch: The branch being logged.
395
    :param generate_delta: Whether to generate a delta for each revision.
396
    :param search: A user text search string.
397
    :param log_rev_iterator: An input iterator containing all revisions that
398
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
399
    :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.
400
        delta).
401
    """
3642.1.5 by Robert Collins
Separate out batching of revisions.
402
    repository = branch.repository
3642.1.4 by Robert Collins
Factor out revision object extraction from revision batching.
403
    for revs in log_rev_iterator:
404
        # r = revision_id, n = revno, d = merge depth
405
        revision_ids = [view[0] for view, _, _ in revs]
406
        revisions = repository.get_revisions(revision_ids)
407
        revs = [(rev[0], revision, rev[2]) for rev, revision in
408
            izip(revs, revisions)]
409
        yield revs
410
411
3642.1.7 by Robert Collins
Review feedback.
412
def _make_batch_filter(branch, generate_delta, search, log_rev_iterator):
3642.1.5 by Robert Collins
Separate out batching of revisions.
413
    """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.
414
415
    :param branch: The branch being logged.
416
    :param generate_delta: Whether to generate a delta for each revision.
417
    :param search: A user text search string.
3642.1.5 by Robert Collins
Separate out batching of revisions.
418
    :param log_rev_iterator: An input iterator containing all revisions that
419
        could be displayed, in lists.
3874.2.4 by Vincent Ladeuil
Fix too long lines.
420
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
421
        delta).
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
422
    """
423
    repository = branch.repository
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
424
    num = 9
3642.1.5 by Robert Collins
Separate out batching of revisions.
425
    for batch in log_rev_iterator:
426
        batch = iter(batch)
427
        while True:
428
            step = [detail for _, detail in zip(range(num), batch)]
429
            if len(step) == 0:
430
                break
431
            yield step
432
            num = min(int(num * 1.5), 200)
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
433
434
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
435
def _get_mainline_revs(branch, start_revision, end_revision):
436
    """Get the mainline revisions from the branch.
437
    
438
    Generates the list of mainline revisions for the branch.
439
    
440
    :param  branch: The branch containing the revisions. 
441
442
    :param  start_revision: The first revision to be logged.
443
            For backwards compatibility this may be a mainline integer revno,
444
            but for merge revision support a RevisionInfo is expected.
445
446
    :param  end_revision: The last revision to be logged.
447
            For backwards compatibility this may be a mainline integer revno,
448
            but for merge revision support a RevisionInfo is expected.
449
450
    :return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
451
    """
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
452
    branch_revno, branch_last_revision = branch.last_revision_info()
453
    if branch_revno == 0:
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
454
        return None, None, None, None
455
456
    # For mainline generation, map start_revision and end_revision to 
457
    # mainline revnos. If the revision is not on the mainline choose the 
458
    # appropriate extreme of the mainline instead - the extra will be 
459
    # filtered later.
460
    # Also map the revisions to rev_ids, to be used in the later filtering
461
    # stage.
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
462
    start_rev_id = None
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
463
    if start_revision is None:
464
        start_revno = 1
465
    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.
466
        if isinstance(start_revision, revisionspec.RevisionInfo):
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
467
            start_rev_id = start_revision.rev_id
468
            start_revno = start_revision.revno or 1
469
        else:
470
            branch.check_real_revno(start_revision)
471
            start_revno = start_revision
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
472
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
473
    end_rev_id = None
474
    if end_revision is None:
3449.2.5 by John Arbash Meinel
Stop referencing the variable I removed.
475
        end_revno = branch_revno
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
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(end_revision, revisionspec.RevisionInfo):
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
478
            end_rev_id = end_revision.rev_id
3449.2.5 by John Arbash Meinel
Stop referencing the variable I removed.
479
            end_revno = end_revision.revno or branch_revno
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
480
        else:
481
            branch.check_real_revno(end_revision)
482
            end_revno = end_revision
483
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
484
    if ((start_rev_id == _mod_revision.NULL_REVISION)
485
        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.
486
        raise errors.BzrCommandError('Logging revision 0 is invalid.')
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
487
    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.
488
        raise errors.BzrCommandError("Start revision must be older than "
489
                                     "the end revision.")
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
490
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
491
    cur_revno = branch_revno
492
    rev_nos = {}
493
    mainline_revs = []
494
    for revision_id in branch.repository.iter_reverse_revision_history(
495
                        branch_last_revision):
496
        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.
497
            # 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()'
498
            rev_nos[revision_id] = cur_revno
499
            mainline_revs.append(revision_id)
500
            break
501
        if cur_revno <= end_revno:
502
            rev_nos[revision_id] = cur_revno
503
            mainline_revs.append(revision_id)
504
        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.
505
    else:
506
        # We walked off the edge of all revisions, so we add a 'None' marker
507
        mainline_revs.append(None)
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
508
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
509
    mainline_revs.reverse()
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
510
511
    # override the mainline to look like the revision history.
512
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
513
514
515
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
516
    """Filter view_revisions based on revision ranges.
517
518
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth) 
519
            tuples to be filtered.
520
521
    :param start_rev_id: If not NONE specifies the first revision to be logged.
522
            If NONE then all revisions up to the end_rev_id are logged.
523
524
    :param end_rev_id: If not NONE specifies the last revision to be logged.
525
            If NONE then all revisions up to the end of the log are logged.
526
527
    :return: The filtered view_revisions.
528
    """
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
529
    if start_rev_id or end_rev_id:
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
530
        revision_ids = [r for r, n, d in view_revisions]
531
        if start_rev_id:
532
            start_index = revision_ids.index(start_rev_id)
533
        else:
534
            start_index = 0
535
        if start_rev_id == end_rev_id:
536
            end_index = start_index
537
        else:
538
            if end_rev_id:
539
                end_index = revision_ids.index(end_rev_id)
540
            else:
541
                end_index = len(view_revisions) - 1
542
        # To include the revisions merged into the last revision, 
543
        # extend end_rev_id down to, but not including, the next rev
544
        # with the same or lesser merge_depth
545
        end_merge_depth = view_revisions[end_index][2]
546
        try:
547
            for index in xrange(end_index+1, len(view_revisions)+1):
548
                if view_revisions[index][2] <= end_merge_depth:
549
                    end_index = index - 1
550
                    break
551
        except IndexError:
552
            # if the search falls off the end then log to the end as well
553
            end_index = len(view_revisions) - 1
554
        view_revisions = view_revisions[start_index:end_index+1]
555
    return view_revisions
556
557
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
558
def _filter_revisions_touching_file_id(branch, file_id, view_revisions):
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
559
    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.
560
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
561
    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.
562
    This includes the revisions which directly change the file id,
563
    and the revisions which merge these changes. So if the
564
    revision graph is::
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
565
        A-.
566
        |\ \
567
        B C E
568
        |/ /
569
        D |
570
        |\|
571
        | F
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
572
        |/
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
573
        G
574
575
    And 'C' changes a file, then both C and D will be returned. F will not be
576
    returned even though it brings the changes to C into the branch starting
577
    with E. (Note that if we were using F as the tip instead of G, then we
578
    would see C, D, F.)
579
580
    This will also be restricted based on a subset of the mainline.
581
582
    :param branch: The branch where we can get text revision information.
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
583
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
584
    :param file_id: Filter out revisions that do not touch file_id.
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
585
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
586
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
587
        tuples. This is the list of revisions which will be filtered. It is
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
588
        assumed that view_revisions is in merge_sort order (i.e. newest
589
        revision first ).
590
2359.1.8 by John Arbash Meinel
doc
591
    :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.
592
    """
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
593
    # Lookup all possible text keys to determine which ones actually modified
594
    # the file.
595
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
3711.3.16 by John Arbash Meinel
Doc update.
596
    # Looking up keys in batches of 1000 can cut the time in half, as well as
597
    # memory consumption. GraphIndex *does* like to look for a few keys in
598
    # 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.
599
    # TODO: This code needs to be re-evaluated periodically as we tune the
600
    #       indexing layer. We might consider passing in hints as to the known
601
    #       access pattern (sparse/clustered, high success rate/low success
602
    #       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.
603
    get_parent_map = branch.repository.texts.get_parent_map
604
    modified_text_revisions = set()
605
    chunk_size = 1000
606
    for start in xrange(0, len(text_keys), chunk_size):
607
        next_keys = text_keys[start:start + chunk_size]
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
608
        # 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.
609
        modified_text_revisions.update(
610
            [k[1] for k in get_parent_map(next_keys)])
611
    del text_keys, next_keys
3711.3.14 by John Arbash Meinel
Change the per-file log algorithm dramatically.
612
613
    result = []
614
    # Track what revisions will merge the current revision, replace entries
615
    # with 'None' when they have been added to result
616
    current_merge_stack = [None]
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
617
    for info in view_revisions:
3711.3.14 by John Arbash Meinel
Change the per-file log algorithm dramatically.
618
        rev_id, revno, depth = info
619
        if depth == len(current_merge_stack):
620
            current_merge_stack.append(info)
621
        else:
622
            del current_merge_stack[depth + 1:]
623
            current_merge_stack[-1] = info
624
625
        if rev_id in modified_text_revisions:
626
            # This needs to be logged, along with the extra revisions
627
            for idx in xrange(len(current_merge_stack)):
628
                node = current_merge_stack[idx]
629
                if node is not None:
630
                    result.append(node)
631
                    current_merge_stack[idx] = None
3711.3.4 by John Arbash Meinel
Significantly faster, but consuming more memory.
632
    return result
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
633
634
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
635
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
1756.2.22 by Aaron Bentley
Apply review comments
636
                       include_merges=True):
1756.2.18 by Aaron Bentley
Factor out the revision list generation
637
    """Produce an iterator of revisions to show
638
    :return: an iterator of (revision_id, revno, merge_depth)
639
    (if there is no revno for a revision, None is supplied)
640
    """
1756.2.22 by Aaron Bentley
Apply review comments
641
    if include_merges is False:
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
642
        revision_ids = mainline_revs[1:]
643
        if direction == 'reverse':
644
            revision_ids.reverse()
645
        for revision_id in revision_ids:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
646
            yield revision_id, str(rev_nos[revision_id]), 0
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
647
        return
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
648
    graph = branch.repository.get_graph()
649
    # This asks for all mainline revisions, which means we only have to spider
650
    # sideways, rather than depth history. That said, its still size-of-history
651
    # and should be addressed.
3373.5.4 by John Arbash Meinel
Track down another bogus location. Only triggered with --long
652
    # mainline_revisions always includes an extra revision at the beginning, so
653
    # don't request it.
3287.6.8 by Robert Collins
Reduce code duplication as per review.
654
    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
655
        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.
656
    # filter out ghosts; merge_sort errors on ghosts.
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
657
    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.
658
    merge_sorted_revisions = tsort.merge_sort(
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
659
        rev_graph,
1756.2.18 by Aaron Bentley
Factor out the revision list generation
660
        mainline_revs[-1],
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
661
        mainline_revs,
662
        generate_revno=True)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
663
664
    if direction == 'forward':
665
        # forward means oldest first.
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
666
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
667
    elif direction != 'reverse':
668
        raise ValueError('invalid direction %r' % direction)
669
3874.2.4 by Vincent Ladeuil
Fix too long lines.
670
    for (sequence, rev_id, merge_depth, revno, end_of_merge
671
         ) in merge_sorted_revisions:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
672
        yield rev_id, '.'.join(map(str, revno)), merge_depth
1756.2.18 by Aaron Bentley
Factor out the revision list generation
673
674
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
675
def reverse_by_depth(merge_sorted_revisions, _depth=0):
676
    """Reverse revisions by depth.
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
677
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
678
    Revisions with a different depth are sorted as a group with the previous
679
    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
680
    but it looks much nicer.
681
    """
3842.2.6 by Vincent Ladeuil
Fix typo.
682
    # 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.
683
    merge_sorted_revisions = [(None, None, _depth)] + merge_sorted_revisions
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
684
    zd_revisions = []
685
    for val in merge_sorted_revisions:
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
686
        if val[2] == _depth:
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
687
            # Each revision at the current depth becomes a chunk grouping all
688
            # higher depth revisions.
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
689
            zd_revisions.append([val])
690
        else:
691
            zd_revisions[-1].append(val)
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
692
    for revisions in zd_revisions:
693
        if len(revisions) > 1:
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
694
            # 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.
695
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
696
    zd_revisions.reverse()
697
    result = []
698
    for chunk in zd_revisions:
699
        result.extend(chunk)
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
700
    if _depth == 0:
701
        # Top level call, get rid of the fake revisions that have been added
702
        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
703
    return result
704
705
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.
706
class LogRevision(object):
707
    """A revision to be logged (by LogFormatter.log_revision).
708
709
    A simple wrapper for the attributes of a revision to be logged.
710
    The attributes may or may not be populated, as determined by the 
711
    logging options and the log formatter capabilities.
712
    """
713
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
714
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
715
                 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.
716
        self.rev = rev
717
        self.revno = revno
718
        self.merge_depth = merge_depth
719
        self.delta = delta
720
        self.tags = tags
721
722
794 by Martin Pool
- Merge John's nice short-log format.
723
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.
724
    """Abstract class to display log messages.
725
726
    At a minimum, a derived class must implement the log_revision method.
727
728
    If the LogFormatter needs to be informed of the beginning or end of
729
    a log it should implement the begin_log and/or end_log hook methods.
730
731
    A LogFormatter should define the following supports_XXX flags 
732
    to indicate which LogRevision attributes it supports:
733
734
    - supports_delta must be True if this log formatter supports delta.
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
735
        Otherwise the delta attribute may not be populated.  The 'delta_format'
736
        attribute describes whether the 'short_status' format (1) or the long
3936.3.2 by Ian Clatworthy
minor cleanups
737
        one (2) should be used.
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
738
 
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
    - supports_merge_revisions must be True if this log formatter supports 
3936.3.2 by Ian Clatworthy
minor cleanups
740
        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.
741
        also not True, then only mainline revisions will be passed to the 
742
        formatter.
743
    - supports_single_merge_revision must be True if this log formatter
744
        supports logging only a single merge revision.  This flag is
745
        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.
746
    - supports_tags must be True if this log formatter supports tags.
747
        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
748
749
    Plugins can register functions to show custom revision properties using
3144.7.13 by Guillermo Gonzalez
* fixed typo LogFormatter.show_properties in docstring
750
    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
751
    must respect the following interface description:
3144.7.2 by Guillermo Gonzalez
* cleanup a bit the interface
752
        def my_show_properties(properties_dict):
753
            # code that returns a dict {'name':'value'} of the properties 
754
            # 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.
755
    """
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
756
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
757
    def __init__(self, to_file, show_ids=False, show_timezone='original',
758
                 delta_format=None):
794 by Martin Pool
- Merge John's nice short-log format.
759
        self.to_file = to_file
760
        self.show_ids = show_ids
761
        self.show_timezone = show_timezone
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
762
        if delta_format is None:
763
            # Ensures backward compatibility
764
            delta_format = 2 # long format
765
        self.delta_format = delta_format
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
766
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.
767
# TODO: uncomment this block after show() has been removed.
768
# Until then defining log_revision would prevent _show_log calling show() 
769
# in legacy formatters.
770
#    def log_revision(self, revision):
771
#        """Log a revision.
772
#
773
#        :param  revision:   The LogRevision to be logged.
774
#        """
775
#        raise NotImplementedError('not implemented in abstract base')
776
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
777
    def short_committer(self, rev):
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
778
        name, address = config.parse_username(rev.committer)
779
        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.
780
            return name
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
781
        return address
2388.1.11 by Alexander Belchenko
changes after John's review
782
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.
783
    def short_author(self, rev):
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
784
        name, address = config.parse_username(rev.get_apparent_author())
785
        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.
786
            return name
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
787
        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.
788
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
789
    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
790
        """Displays the custom properties returned by each registered handler.
791
        
3144.7.13 by Guillermo Gonzalez
* fixed typo LogFormatter.show_properties in docstring
792
        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
793
        """
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
794
        for key, handler in properties_handler_registry.iteritems():
795
            for key, value in handler(revision).items():
796
                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
797
2388.1.11 by Alexander Belchenko
changes after John's review
798
794 by Martin Pool
- Merge John's nice short-log format.
799
class LongLogFormatter(LogFormatter):
2388.1.11 by Alexander Belchenko
changes after John's review
800
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
    supports_merge_revisions = True
802
    supports_delta = True
803
    supports_tags = True
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
804
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.
805
    def log_revision(self, revision):
806
        """Log a revision, either merged or not."""
2671.2.5 by Lukáš Lalinský
Fixes for comments from the mailing list.
807
        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.
808
        to_file = self.to_file
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
809
        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.
810
        if revision.revno is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
811
            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.
812
        if revision.tags:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
813
            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.
814
        if self.show_ids:
3257.2.1 by Adeodato Simó
Add a space after "revision-id:" in log output.
815
            to_file.write(indent + 'revision-id: ' + revision.rev.revision_id)
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
816
            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.
817
            for parent_id in revision.rev.parent_ids:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
818
                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
819
        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.
820
2671.5.7 by Lukáš Lalinsky
Rename get_author to get_apparent_author, revert the long log back to displaying the committer.
821
        author = revision.rev.properties.get('author', None)
822
        if author is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
823
            to_file.write(indent + 'author: %s\n' % (author,))
824
        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.
825
826
        branch_nick = revision.rev.properties.get('branch-nick', None)
827
        if branch_nick is not None:
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
828
            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.
829
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.
830
        date_str = format_date(revision.rev.timestamp,
831
                               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.
832
                               self.show_timezone)
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
833
        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.
834
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
835
        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.
836
        if not revision.rev.message:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
837
            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.
838
        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.
839
            message = revision.rev.message.rstrip('\r\n')
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
840
            for l in message.split('\n'):
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
841
                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.
842
        if revision.delta is not None:
3874.1.7 by Vincent Ladeuil
Restrict '-v' change to log --short only.
843
            # We don't respect delta_format for compatibility
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
844
            revision.delta.show(to_file, self.show_ids, indent=indent,
3874.1.7 by Vincent Ladeuil
Restrict '-v' change to log --short only.
845
                                short_status=False)
794 by Martin Pool
- Merge John's nice short-log format.
846
847
848
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.
849
850
    supports_delta = True
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
851
    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.
852
853
    def log_revision(self, revision):
794 by Martin Pool
- Merge John's nice short-log format.
854
        to_file = self.to_file
2483.2.2 by John Arbash Meinel
Add [merge] after the timestamp for revisions with merges.
855
        is_merge = ''
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
856
        if len(revision.rev.parent_ids) > 1:
2483.2.2 by John Arbash Meinel
Add [merge] after the timestamp for revisions with merges.
857
            is_merge = ' [merge]'
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
858
        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.
859
                self.short_author(revision.rev),
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
860
                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.
861
                            revision.rev.timezone or 0,
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
862
                            self.show_timezone, date_fmt="%Y-%m-%d",
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
863
                            show_offset=False),
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
864
                is_merge))
794 by Martin Pool
- Merge John's nice short-log format.
865
        if self.show_ids:
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
866
            to_file.write('      revision-id:%s\n'
867
                          % (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.
868
        if not revision.rev.message:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
869
            to_file.write('      (no message)\n')
794 by Martin Pool
- Merge John's nice short-log format.
870
        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.
871
            message = revision.rev.message.rstrip('\r\n')
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
872
            for l in message.split('\n'):
2911.6.3 by Blake Winton
Implemented suggestions from John Arbash Meinel.
873
                to_file.write('      %s\n' % (l,))
794 by Martin Pool
- Merge John's nice short-log format.
874
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.
875
        if revision.delta is not None:
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
876
            revision.delta.show(to_file, self.show_ids,
877
                                short_status=self.delta_format==1)
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
878
        to_file.write('\n')
794 by Martin Pool
- Merge John's nice short-log format.
879
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
880
1185.12.25 by Aaron Bentley
Added one-line log format
881
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.
882
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
883
    supports_single_merge_revision = True
884
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.
885
    def __init__(self, *args, **kwargs):
886
        super(LineLogFormatter, self).__init__(*args, **kwargs)
887
        self._max_chars = terminal_width() - 1
888
1185.12.25 by Aaron Bentley
Added one-line log format
889
    def truncate(self, str, max_len):
890
        if len(str) <= max_len:
891
            return str
892
        return str[:max_len-3]+'...'
893
894
    def date_string(self, rev):
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
895
        return format_date(rev.timestamp, rev.timezone or 0,
1185.12.25 by Aaron Bentley
Added one-line log format
896
                           self.show_timezone, date_fmt="%Y-%m-%d",
897
                           show_offset=False)
898
899
    def message(self, rev):
900
        if not rev.message:
901
            return '(no message)'
902
        else:
903
            return rev.message
904
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.
905
    def log_revision(self, revision):
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
906
        self.to_file.write(self.log_string(revision.revno, revision.rev,
907
                                              self._max_chars))
908
        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.
909
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
910
    def log_string(self, revno, rev, max_chars):
911
        """Format log info into one string. Truncate tail of string
3677.1.1 by Vincent Ladeuil
Begin fixing bug #233817.
912
        :param  revno:      revision number or None.
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
913
                            Revision numbers counts from 1.
914
        :param  rev:        revision info object
915
        :param  max_chars:  maximum length of resulting string
916
        :return:            formatted truncated string
917
        """
918
        out = []
919
        if revno:
920
            # show revno only when is not None
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
921
            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.
922
        out.append(self.truncate(self.short_author(rev), 20))
1185.12.25 by Aaron Bentley
Added one-line log format
923
        out.append(self.date_string(rev))
1740.2.5 by Aaron Bentley
Merge from bzr.dev
924
        out.append(rev.get_summary())
1185.12.25 by Aaron Bentley
Added one-line log format
925
        return self.truncate(" ".join(out).rstrip('\n'), max_chars)
794 by Martin Pool
- Merge John's nice short-log format.
926
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
927
1185.12.27 by Aaron Bentley
Use line log for pending merges
928
def line_log(rev, max_chars):
929
    lf = LineLogFormatter(None)
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
930
    return lf.log_string(None, rev, max_chars)
1185.12.27 by Aaron Bentley
Use line log for pending merges
931
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
932
933
class LogFormatterRegistry(registry.Registry):
934
    """Registry for log formatters"""
935
936
    def make_formatter(self, name, *args, **kwargs):
937
        """Construct a formatter from arguments.
938
939
        :param name: Name of the formatter to construct.  'short', 'long' and
940
            'line' are built-in.
941
        """
942
        return self.get(name)(*args, **kwargs)
943
944
    def get_default(self, branch):
945
        return self.get(branch.get_config().log_format())
946
947
948
log_formatter_registry = LogFormatterRegistry()
949
950
951
log_formatter_registry.register('short', ShortLogFormatter,
952
                                'Moderately short log format')
953
log_formatter_registry.register('long', LongLogFormatter,
954
                                'Detailed log format')
955
log_formatter_registry.register('line', LineLogFormatter,
956
                                'Log format with one line per revision')
957
794 by Martin Pool
- Merge John's nice short-log format.
958
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
959
def register_formatter(name, formatter):
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
960
    log_formatter_registry.register(name, formatter)
961
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
962
794 by Martin Pool
- Merge John's nice short-log format.
963
def log_formatter(name, *args, **kwargs):
1393.1.56 by Martin Pool
- doc and small refactoring of log code
964
    """Construct a formatter from arguments.
965
1185.12.27 by Aaron Bentley
Use line log for pending merges
966
    name -- Name of the formatter to construct; currently 'long', 'short' and
967
        'line' are supported.
1393.1.56 by Martin Pool
- doc and small refactoring of log code
968
    """
794 by Martin Pool
- Merge John's nice short-log format.
969
    try:
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
970
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
1553.2.2 by Erik Bågfors
Made "unknown log formatter" error message work
971
    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.
972
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
973
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
974
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
975
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
976
    # deprecated; for compatibility
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
977
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
978
    lf.show(revno, rev, delta)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
979
2490.1.4 by John Arbash Meinel
Update bzrlib.log.show_changed_revisions to use the new api
980
1551.17.2 by Aaron Bentley
Stop showing deltas in pull -v output
981
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
982
                           log_format='long'):
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
983
    """Show the change in revision history comparing the old revision history to the new one.
984
985
    :param branch: The branch where the revisions exist
986
    :param old_rh: The old revision history
987
    :param new_rh: The new revision history
988
    :param to_file: A file to write the results to. If None, stdout will be used
989
    """
990
    if to_file is None:
2997.1.3 by Alexander Belchenko
file wrapper around stdout should use terminal encoding, not user_encoding.
991
        to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
992
            errors='replace')
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
993
    lf = log_formatter(log_format,
994
                       show_ids=False,
995
                       to_file=to_file,
996
                       show_timezone='original')
997
998
    # This is the first index which is different between
999
    # old and new
1000
    base_idx = None
1001
    for i in xrange(max(len(new_rh),
1002
                        len(old_rh))):
1003
        if (len(new_rh) <= i
1004
            or len(old_rh) <= i
1005
            or new_rh[i] != old_rh[i]):
1006
            base_idx = i
1007
            break
1008
1009
    if base_idx is None:
1010
        to_file.write('Nothing seems to have changed\n')
1011
        return
1012
    ## TODO: It might be nice to do something like show_log
1013
    ##       and show the merged entries. But since this is the
1014
    ##       removed revisions, it shouldn't be as important
1015
    if base_idx < len(old_rh):
1016
        to_file.write('*'*60)
1017
        to_file.write('\nRemoved Revisions:\n')
1018
        for i in range(base_idx, len(old_rh)):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1019
            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
1020
            lr = LogRevision(rev, i+1, 0, None)
1021
            lf.log_revision(lr)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1022
        to_file.write('*'*60)
1023
        to_file.write('\n\n')
1024
    if base_idx < len(new_rh):
1025
        to_file.write('Added Revisions:\n')
1026
        show_log(branch,
1027
                 lf,
1028
                 None,
1551.17.2 by Aaron Bentley
Stop showing deltas in pull -v output
1029
                 verbose=False,
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1030
                 direction='forward',
1031
                 start_revision=base_idx+1,
1032
                 end_revision=len(new_rh),
1033
                 search=None)
1034
3144.7.4 by Guillermo Gonzalez
* move the function regisstry into a real Registry instead of a list
1035
3848.1.7 by Aaron Bentley
Use repository in get_history_change
1036
def get_history_change(old_revision_id, new_revision_id, repository):
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1037
    """Calculate the uncommon lefthand history between two revisions.
1038
1039
    :param old_revision_id: The original revision id.
1040
    :param new_revision_id: The new revision id.
3848.1.22 by Aaron Bentley
Fix spelling
1041
    :param repository: The repository to use for the calculation.
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1042
1043
    return old_history, new_history
1044
    """
3848.1.6 by Aaron Bentley
Implement get_history_change
1045
    old_history = []
1046
    old_revisions = set()
1047
    new_history = []
1048
    new_revisions = set()
3848.1.7 by Aaron Bentley
Use repository in get_history_change
1049
    new_iter = repository.iter_reverse_revision_history(new_revision_id)
1050
    old_iter = repository.iter_reverse_revision_history(old_revision_id)
3848.1.6 by Aaron Bentley
Implement get_history_change
1051
    stop_revision = None
1052
    do_old = True
1053
    do_new = True
1054
    while do_new or do_old:
1055
        if do_new:
1056
            try:
1057
                new_revision = new_iter.next()
1058
            except StopIteration:
1059
                do_new = False
1060
            else:
1061
                new_history.append(new_revision)
1062
                new_revisions.add(new_revision)
1063
                if new_revision in old_revisions:
1064
                    stop_revision = new_revision
1065
                    break
1066
        if do_old:
1067
            try:
1068
                old_revision = old_iter.next()
1069
            except StopIteration:
1070
                do_old = False
1071
            else:
1072
                old_history.append(old_revision)
1073
                old_revisions.add(old_revision)
1074
                if old_revision in new_revisions:
1075
                    stop_revision = old_revision
1076
                    break
1077
    new_history.reverse()
1078
    old_history.reverse()
1079
    if stop_revision is not None:
1080
        new_history = new_history[new_history.index(stop_revision) + 1:]
1081
        old_history = old_history[old_history.index(stop_revision) + 1:]
1082
    return old_history, new_history
1083
1084
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1085
def show_branch_change(branch, output, old_revno, old_revision_id):
1086
    """Show the changes made to a branch.
1087
1088
    :param branch: The branch to show changes about.
1089
    :param output: A file-like object to write changes to.
1090
    :param old_revno: The revno of the old tip.
1091
    :param old_revision_id: The revision_id of the old tip.
1092
    """
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1093
    new_revno, new_revision_id = branch.last_revision_info()
1094
    old_history, new_history = get_history_change(old_revision_id,
1095
                                                  new_revision_id,
1096
                                                  branch.repository)
1097
    if old_history == [] and new_history == []:
1098
        output.write('Nothing seems to have changed\n')
1099
        return
1100
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1101
    log_format = log_formatter_registry.get_default(branch)
1102
    lf = log_format(show_ids=False, to_file=output, show_timezone='original')
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1103
    if old_history != []:
1104
        output.write('*'*60)
1105
        output.write('\nRemoved Revisions:\n')
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1106
        show_flat_log(branch.repository, old_history, old_revno, lf)
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1107
        output.write('*'*60)
1108
        output.write('\n\n')
1109
    if new_history != []:
3848.1.9 by Aaron Bentley
new/old sections are omitted as appropriate.
1110
        output.write('Added Revisions:\n')
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
1111
        start_revno = new_revno - len(new_history) + 1
1112
        show_log(branch, lf, None, verbose=False, direction='forward',
1113
                 start_revision=start_revno,)
1114
1115
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1116
def show_flat_log(repository, history, last_revno, lf):
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1117
    """Show a simple log of the specified history.
1118
1119
    :param repository: The repository to retrieve revisions from.
1120
    :param history: A list of revision_ids indicating the lefthand history.
1121
    :param last_revno: The revno of the last revision_id in the history.
1122
    :param lf: The log formatter to use.
1123
    """
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
1124
    start_revno = last_revno - len(history) + 1
1125
    revisions = repository.get_revisions(history)
1126
    for i, rev in enumerate(revisions):
1127
        lr = LogRevision(rev, i + last_revno, 0, None)
1128
        lf.log_revision(lr)
1129
1130
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
1131
properties_handler_registry = registry.Registry()
3830.4.1 by Jelmer Vernooij
Add base classes for foreign branches.
1132
properties_handler_registry.register_lazy("foreign",
1133
                                          "bzrlib.foreign",
1134
                                          "show_foreign_properties")
1135
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1136
1137
# adapters which revision ids to log are filtered. When log is called, the
1138
# log_rev_iterator is adapted through each of these factory methods.
1139
# Plugins are welcome to mutate this list in any way they like - as long
1140
# as the overall behaviour is preserved. At this point there is no extensible
1141
# mechanism for getting parameters to each factory method, and until there is
1142
# this won't be considered a stable api.
1143
log_adapters = [
1144
    # core log logic
3642.1.7 by Robert Collins
Review feedback.
1145
    _make_batch_filter,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1146
    # read revision objects
3642.1.7 by Robert Collins
Review feedback.
1147
    _make_revision_objects,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1148
    # filter on log messages
3642.1.7 by Robert Collins
Review feedback.
1149
    _make_search_filter,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1150
    # generate deltas for things we will show
3642.1.7 by Robert Collins
Review feedback.
1151
    _make_delta_filter
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
1152
    ]