/brz/remove-bazaar

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